repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
edx/edx-submissions
submissions/api.py
get_score
python
def get_score(student_item): try: student_item_model = StudentItem.objects.get(**student_item) score = ScoreSummary.objects.get(student_item=student_item_model).latest except (ScoreSummary.DoesNotExist, StudentItem.DoesNotExist): return None # By convention, scores are hidden if "points possible" is set to 0. # This can occur when an instructor has reset scores for a student. if score.is_hidden(): return None else: return ScoreSerializer(score).data
Get the score for a particular student item Each student item should have a unique score. This function will return the score if it is available. A score is only calculated for a student item if it has completed the workflow for a particular assessment module. Args: student_item (dict): The dictionary representation of a student item. Function returns the score related to this student item. Returns: score (dict): The score associated with this student item. None if there is no score found. Raises: SubmissionInternalError: Raised if a score cannot be retrieved because of an internal server error. Examples: >>> student_item = { >>> "student_id":"Tim", >>> "course_id":"TestCourse", >>> "item_id":"u_67", >>> "item_type":"openassessment" >>> } >>> >>> get_score(student_item) [{ 'student_item': 2, 'submission': 2, 'points_earned': 8, 'points_possible': 20, 'created_at': datetime.datetime(2014, 2, 7, 18, 30, 1, 807911, tzinfo=<UTC>) }]
train
https://github.com/edx/edx-submissions/blob/8d531ca25f7c2886dfcb1bb8febe0910e1433ca2/submissions/api.py#L628-L676
null
""" Public interface for the submissions app. """ from __future__ import absolute_import import copy import itertools import logging import operator import json from uuid import UUID from django.conf import settings from django.core.cache import cache from django.db import IntegrityError, DatabaseError from submissions.serializers import ( SubmissionSerializer, StudentItemSerializer, ScoreSerializer, UnannotatedScoreSerializer ) from submissions.models import Submission, StudentItem, Score, ScoreSummary, ScoreAnnotation, score_set, score_reset import six logger = logging.getLogger("submissions.api") # By default, limit the number of top submissions # Anything above this limit will result in a request error MAX_TOP_SUBMISSIONS = 100 # Set a relatively low cache timeout for top submissions. TOP_SUBMISSIONS_CACHE_TIMEOUT = 300 class SubmissionError(Exception): """An error that occurs during submission actions. This error is raised when the submission API cannot perform a requested action. """ pass class SubmissionInternalError(SubmissionError): """An error internal to the Submission API has occurred. This error is raised when an error occurs that is not caused by incorrect use of the API, but rather internal implementation of the underlying services. """ pass class SubmissionNotFoundError(SubmissionError): """This error is raised when no submission is found for the request. If a state is specified in a call to the API that results in no matching Submissions, this error may be raised. """ pass class SubmissionRequestError(SubmissionError): """This error is raised when there was a request-specific error This error is reserved for problems specific to the use of the API. """ def __init__(self, msg="", field_errors=None): """ Configure the submission request error. Keyword Args: msg (unicode): The error message. field_errors (dict): A dictionary of errors (list of unicode) specific to a fields provided in the request. Example usage: >>> raise SubmissionRequestError( >>> "An unexpected error occurred" >>> {"answer": ["Maximum answer length exceeded."]} >>> ) """ super(SubmissionRequestError, self).__init__(msg) self.field_errors = ( copy.deepcopy(field_errors) if field_errors is not None else {} ) self.args += (self.field_errors,) def __repr__(self): """ Show the field errors upon output. """ return '{}(msg="{}", field_errors={})'.format( self.__class__.__name__, self.message, self.field_errors ) def create_submission(student_item_dict, answer, submitted_at=None, attempt_number=None): """Creates a submission for assessment. Generic means by which to submit an answer for assessment. Args: student_item_dict (dict): The student_item this submission is associated with. This is used to determine which course, student, and location this submission belongs to. answer (JSON-serializable): The answer given by the student to be assessed. submitted_at (datetime): The date in which this submission was submitted. If not specified, defaults to the current date. attempt_number (int): A student may be able to submit multiple attempts per question. This allows the designated attempt to be overridden. If the attempt is not specified, it will take the most recent submission, as specified by the submitted_at time, and use its attempt_number plus one. Returns: dict: A representation of the created Submission. The submission contains five attributes: student_item, attempt_number, submitted_at, created_at, and answer. 'student_item' is the ID of the related student item for the submission. 'attempt_number' is the attempt this submission represents for this question. 'submitted_at' represents the time this submission was submitted, which can be configured, versus the 'created_at' date, which is when the submission is first created. Raises: SubmissionRequestError: Raised when there are validation errors for the student item or submission. This can be caused by the student item missing required values, the submission being too long, the attempt_number is negative, or the given submitted_at time is invalid. SubmissionInternalError: Raised when submission access causes an internal error. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> create_submission(student_item_dict, "The answer is 42.", datetime.utcnow, 1) { 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 649284 tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' } """ student_item_model = _get_or_create_student_item(student_item_dict) if attempt_number is None: try: submissions = Submission.objects.filter( student_item=student_item_model)[:1] except DatabaseError: error_message = u"An error occurred while filtering submissions for student item: {}".format( student_item_dict) logger.exception(error_message) raise SubmissionInternalError(error_message) attempt_number = submissions[0].attempt_number + 1 if submissions else 1 model_kwargs = { "student_item": student_item_model.pk, "answer": answer, "attempt_number": attempt_number, } if submitted_at: model_kwargs["submitted_at"] = submitted_at try: submission_serializer = SubmissionSerializer(data=model_kwargs) if not submission_serializer.is_valid(): raise SubmissionRequestError(field_errors=submission_serializer.errors) submission_serializer.save() sub_data = submission_serializer.data _log_submission(sub_data, student_item_dict) return sub_data except DatabaseError: error_message = u"An error occurred while creating submission {} for student item: {}".format( model_kwargs, student_item_dict ) logger.exception(error_message) raise SubmissionInternalError(error_message) def _get_submission_model(uuid, read_replica=False): """ Helper to retrieve a given Submission object from the database. Helper is needed to centralize logic that fixes EDUCATOR-1090, because uuids are stored both with and without hyphens. """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) try: submission = submission_qs.get(uuid=uuid) except Submission.DoesNotExist: try: hyphenated_value = six.text_type(UUID(uuid)) query = """ SELECT `submissions_submission`.`id`, `submissions_submission`.`uuid`, `submissions_submission`.`student_item_id`, `submissions_submission`.`attempt_number`, `submissions_submission`.`submitted_at`, `submissions_submission`.`created_at`, `submissions_submission`.`raw_answer`, `submissions_submission`.`status` FROM `submissions_submission` WHERE ( NOT (`submissions_submission`.`status` = 'D') AND `submissions_submission`.`uuid` = '{}' ) """ query = query.replace("{}", hyphenated_value) # We can use Submission.objects instead of the SoftDeletedManager, we'll include that logic manually submission = Submission.objects.raw(query)[0] except IndexError: raise Submission.DoesNotExist() # Avoid the extra hit next time submission.save(update_fields=['uuid']) return submission def get_submission(submission_uuid, read_replica=False): """Retrieves a single submission by uuid. Args: submission_uuid (str): Identifier for the submission. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Raises: SubmissionNotFoundError: Raised if the submission does not exist. SubmissionRequestError: Raised if the search parameter is not a string. SubmissionInternalError: Raised for unknown errors. Examples: >>> get_submission("20b78e0f32df805d21064fc912f40e9ae5ab260d") { 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' } """ if not isinstance(submission_uuid, six.string_types): if isinstance(submission_uuid, UUID): submission_uuid = six.text_type(submission_uuid) else: raise SubmissionRequestError( msg="submission_uuid ({!r}) must be serializable".format(submission_uuid) ) cache_key = Submission.get_cache_key(submission_uuid) try: cached_submission_data = cache.get(cache_key) except Exception: # The cache backend could raise an exception # (for example, memcache keys that contain spaces) logger.exception("Error occurred while retrieving submission from the cache") cached_submission_data = None if cached_submission_data: logger.info("Get submission {} (cached)".format(submission_uuid)) return cached_submission_data try: submission = _get_submission_model(submission_uuid, read_replica) submission_data = SubmissionSerializer(submission).data cache.set(cache_key, submission_data) except Submission.DoesNotExist: logger.error("Submission {} not found.".format(submission_uuid)) raise SubmissionNotFoundError( u"No submission matching uuid {}".format(submission_uuid) ) except Exception as exc: # Something very unexpected has just happened (like DB misconfig) err_msg = "Could not get submission due to error: {}".format(exc) logger.exception(err_msg) raise SubmissionInternalError(err_msg) logger.info("Get submission {}".format(submission_uuid)) return submission_data def get_submission_and_student(uuid, read_replica=False): """ Retrieve a submission by its unique identifier, including the associated student item. Args: uuid (str): the unique identifier of the submission. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: Serialized Submission model (dict) containing a serialized StudentItem model Raises: SubmissionNotFoundError: Raised if the submission does not exist. SubmissionRequestError: Raised if the search parameter is not a string. SubmissionInternalError: Raised for unknown errors. """ # This may raise API exceptions submission = get_submission(uuid, read_replica=read_replica) # Retrieve the student item from the cache cache_key = "submissions.student_item.{}".format(submission['student_item']) try: cached_student_item = cache.get(cache_key) except Exception: # The cache backend could raise an exception # (for example, memcache keys that contain spaces) logger.exception("Error occurred while retrieving student item from the cache") cached_student_item = None if cached_student_item is not None: submission['student_item'] = cached_student_item else: # There is probably a more idiomatic way to do this using the Django REST framework try: student_item_qs = StudentItem.objects if read_replica: student_item_qs = _use_read_replica(student_item_qs) student_item = student_item_qs.get(id=submission['student_item']) submission['student_item'] = StudentItemSerializer(student_item).data cache.set(cache_key, submission['student_item']) except Exception as ex: err_msg = "Could not get submission due to error: {}".format(ex) logger.exception(err_msg) raise SubmissionInternalError(err_msg) return submission def get_submissions(student_item_dict, limit=None): """Retrieves the submissions for the specified student item, ordered by most recent submitted date. Returns the submissions relative to the specified student item. Exception thrown if no submission is found relative to this location. Args: student_item_dict (dict): The location of the problem this submission is associated with, as defined by a course, student, and item. limit (int): Optional parameter for limiting the returned number of submissions associated with this student item. If not specified, all associated submissions are returned. Returns: List dict: A list of dicts for the associated student item. The submission contains five attributes: student_item, attempt_number, submitted_at, created_at, and answer. 'student_item' is the ID of the related student item for the submission. 'attempt_number' is the attempt this submission represents for this question. 'submitted_at' represents the time this submission was submitted, which can be configured, versus the 'created_at' date, which is when the submission is first created. Raises: SubmissionRequestError: Raised when the associated student item fails validation. SubmissionNotFoundError: Raised when a submission cannot be found for the associated student item. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> get_submissions(student_item_dict, 3) [{ 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' }] """ student_item_model = _get_or_create_student_item(student_item_dict) try: submission_models = Submission.objects.filter( student_item=student_item_model) except DatabaseError: error_message = ( u"Error getting submission request for student item {}" .format(student_item_dict) ) logger.exception(error_message) raise SubmissionNotFoundError(error_message) if limit: submission_models = submission_models[:limit] return SubmissionSerializer(submission_models, many=True).data def get_all_submissions(course_id, item_id, item_type, read_replica=True): """For the given item, get the most recent submission for every student who has submitted. This may return a very large result set! It is implemented as a generator for efficiency. Args: course_id, item_id, item_type (string): The values of the respective student_item fields to filter the submissions by. read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Yields: Dicts representing the submissions with the following fields: student_item student_id attempt_number submitted_at created_at answer Raises: Cannot fail unless there's a database error, but may return an empty iterable. """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) # We cannot use SELECT DISTINCT ON because it's PostgreSQL only, so unfortunately # our results will contain every entry of each student, not just the most recent. # We sort by student_id and primary key, so the reults will be grouped be grouped by # student, with the most recent submission being the first one in each group. query = submission_qs.select_related('student_item').filter( student_item__course_id=course_id, student_item__item_id=item_id, student_item__item_type=item_type, ).order_by('student_item__student_id', '-submitted_at', '-id').iterator() for unused_student_id, row_iter in itertools.groupby(query, operator.attrgetter('student_item.student_id')): submission = next(row_iter) data = SubmissionSerializer(submission).data data['student_id'] = submission.student_item.student_id yield data def get_all_course_submission_information(course_id, item_type, read_replica=True): """ For the given course, get all student items of the given item type, all the submissions for those itemes, and the latest scores for each item. If a submission was given a score that is not the latest score for the relevant student item, it will still be included but without score. Args: course_id (str): The course that we are getting submissions from. item_type (str): The type of items that we are getting submissions for. read_replica (bool): Try to use the database's read replica if it's available. Yields: A tuple of three dictionaries representing: (1) a student item with the following fields: student_id course_id student_item item_type (2) a submission with the following fields: student_item attempt_number submitted_at created_at answer (3) a score with the following fields, if one exists and it is the latest score: (if both conditions are not met, an empty dict is returned here) student_item submission points_earned points_possible created_at submission_uuid """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) query = submission_qs.select_related('student_item__scoresummary__latest__submission').filter( student_item__course_id=course_id, student_item__item_type=item_type, ).iterator() for submission in query: student_item = submission.student_item serialized_score = {} if hasattr(student_item, 'scoresummary'): latest_score = student_item.scoresummary.latest # Only include the score if it is not a reset score (is_hidden), and if the current submission is the same # as the student_item's latest score's submission. This matches the behavior of the API's get_score method. if (not latest_score.is_hidden()) and latest_score.submission.uuid == submission.uuid: serialized_score = ScoreSerializer(latest_score).data yield ( StudentItemSerializer(student_item).data, SubmissionSerializer(submission).data, serialized_score ) def get_top_submissions(course_id, item_id, item_type, number_of_top_scores, use_cache=True, read_replica=True): """Get a number of top scores for an assessment based on a particular student item This function will return top scores for the piece of assessment. It will consider only the latest and greater than 0 score for a piece of assessment. A score is only calculated for a student item if it has completed the workflow for a particular assessment module. In general, users of top submissions can tolerate some latency in the search results, so by default this call uses a cache and the read replica (if available). Args: course_id (str): The course to retrieve for the top scores item_id (str): The item within the course to retrieve for the top scores item_type (str): The type of item to retrieve number_of_top_scores (int): The number of scores to return, greater than 0 and no more than 100. Kwargs: use_cache (bool): If true, check the cache before retrieving querying the database. read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: topscores (dict): The top scores for the assessment for the student item. An empty array if there are no scores or all scores are 0. Raises: SubmissionNotFoundError: Raised when a submission cannot be found for the associated student item. SubmissionRequestError: Raised when the number of top scores is higher than the MAX_TOP_SUBMISSIONS constant. Examples: >>> course_id = "TestCourse" >>> item_id = "u_67" >>> item_type = "openassessment" >>> number_of_top_scores = 10 >>> >>> get_top_submissions(course_id, item_id, item_type, number_of_top_scores) [{ 'score': 20, 'content': "Platypus" },{ 'score': 16, 'content': "Frog" }] """ if number_of_top_scores < 1 or number_of_top_scores > MAX_TOP_SUBMISSIONS: error_msg = ( u"Number of top scores must be a number between 1 and {}.".format(MAX_TOP_SUBMISSIONS) ) logger.exception(error_msg) raise SubmissionRequestError(msg=error_msg) # First check the cache (unless caching is disabled) cache_key = "submissions.top_submissions.{course}.{item}.{type}.{number}".format( course=course_id, item=item_id, type=item_type, number=number_of_top_scores ) top_submissions = cache.get(cache_key) if use_cache else None # If we can't find it in the cache (or caching is disabled), check the database # By default, prefer the read-replica. if top_submissions is None: try: query = ScoreSummary.objects.filter( student_item__course_id=course_id, student_item__item_id=item_id, student_item__item_type=item_type, latest__points_earned__gt=0 ).select_related('latest', 'latest__submission').order_by("-latest__points_earned") if read_replica: query = _use_read_replica(query) score_summaries = query[:number_of_top_scores] except DatabaseError: msg = u"Could not fetch top score summaries for course {}, item {} of type {}".format( course_id, item_id, item_type ) logger.exception(msg) raise SubmissionInternalError(msg) # Retrieve the submission content for each top score top_submissions = [ { "score": score_summary.latest.points_earned, "content": SubmissionSerializer(score_summary.latest.submission).data['answer'] } for score_summary in score_summaries ] # Always store the retrieved list in the cache cache.set(cache_key, top_submissions, TOP_SUBMISSIONS_CACHE_TIMEOUT) return top_submissions def get_scores(course_id, student_id): """Return a dict mapping item_ids to scores. Scores are represented by serialized Score objects in JSON-like dict format. This method would be used by an LMS to find all the scores for a given student in a given course. Scores that are "hidden" (because they have points earned set to zero) are excluded from the results. Args: course_id (str): Course ID, used to do a lookup on the `StudentItem`. student_id (str): Student ID, used to do a lookup on the `StudentItem`. Returns: dict: The keys are `item_id`s (`str`) and the values are tuples of `(points_earned, points_possible)`. All points are integer values and represent the raw, unweighted scores. Submissions does not have any concept of weights. If there are no entries matching the `course_id` or `student_id`, we simply return an empty dictionary. This is not considered an error because there might be many queries for the progress page of a person who has never submitted anything. Raises: SubmissionInternalError: An unexpected error occurred while resetting scores. """ try: score_summaries = ScoreSummary.objects.filter( student_item__course_id=course_id, student_item__student_id=student_id, ).select_related('latest', 'latest__submission', 'student_item') except DatabaseError: msg = u"Could not fetch scores for course {}, student {}".format( course_id, student_id ) logger.exception(msg) raise SubmissionInternalError(msg) scores = { summary.student_item.item_id: UnannotatedScoreSerializer(summary.latest).data for summary in score_summaries if not summary.latest.is_hidden() } return scores def get_latest_score_for_submission(submission_uuid, read_replica=False): """ Retrieve the latest score for a particular submission. Args: submission_uuid (str): The UUID of the submission to retrieve. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: dict: The serialized score model, or None if no score is available. """ try: # Ensure that submission_uuid is valid before fetching score submission_model = _get_submission_model(submission_uuid, read_replica) score_qs = Score.objects.filter( submission__uuid=submission_model.uuid ).order_by("-id").select_related("submission") if read_replica: score_qs = _use_read_replica(score_qs) score = score_qs[0] if score.is_hidden(): return None except (IndexError, Submission.DoesNotExist): return None return ScoreSerializer(score).data def reset_score(student_id, course_id, item_id, clear_state=False, emit_signal=True): """ Reset scores for a specific student on a specific problem. Note: this does *not* delete `Score` models from the database, since these are immutable. It simply creates a new score with the "reset" flag set to True. Args: student_id (unicode): The ID of the student for whom to reset scores. course_id (unicode): The ID of the course containing the item to reset. item_id (unicode): The ID of the item for which to reset scores. clear_state (bool): If True, will appear to delete any submissions associated with the specified StudentItem Returns: None Raises: SubmissionInternalError: An unexpected error occurred while resetting scores. """ # Retrieve the student item try: student_item = StudentItem.objects.get( student_id=student_id, course_id=course_id, item_id=item_id ) except StudentItem.DoesNotExist: # If there is no student item, then there is no score to reset, # so we can return immediately. return # Create a "reset" score try: score = Score.create_reset_score(student_item) if emit_signal: # Send a signal out to any listeners who are waiting for scoring events. score_reset.send( sender=None, anonymous_user_id=student_id, course_id=course_id, item_id=item_id, created_at=score.created_at, ) if clear_state: for sub in student_item.submission_set.all(): # soft-delete the Submission sub.status = Submission.DELETED sub.save(update_fields=["status"]) # Also clear out cached values cache_key = Submission.get_cache_key(sub.uuid) cache.delete(cache_key) except DatabaseError: msg = ( u"Error occurred while reseting scores for" u" item {item_id} in course {course_id} for student {student_id}" ).format(item_id=item_id, course_id=course_id, student_id=student_id) logger.exception(msg) raise SubmissionInternalError(msg) else: msg = u"Score reset for item {item_id} in course {course_id} for student {student_id}".format( item_id=item_id, course_id=course_id, student_id=student_id ) logger.info(msg) def set_score(submission_uuid, points_earned, points_possible, annotation_creator=None, annotation_type=None, annotation_reason=None): """Set a score for a particular submission. Sets the score for a particular submission. This score is calculated externally to the API. Args: submission_uuid (str): UUID for the submission (must exist). points_earned (int): The earned points for this submission. points_possible (int): The total points possible for this particular student item. annotation_creator (str): An optional field for recording who gave this particular score annotation_type (str): An optional field for recording what type of annotation should be created, e.g. "staff_override". annotation_reason (str): An optional field for recording why this score was set to its value. Returns: None Raises: SubmissionInternalError: Thrown if there was an internal error while attempting to save the score. SubmissionRequestError: Thrown if the given student item or submission are not found. Examples: >>> set_score("a778b933-9fb3-11e3-9c0f-040ccee02800", 11, 12) { 'student_item': 2, 'submission': 1, 'points_earned': 11, 'points_possible': 12, 'created_at': datetime.datetime(2014, 2, 7, 20, 6, 42, 331156, tzinfo=<UTC>) } """ try: submission_model = _get_submission_model(submission_uuid) except Submission.DoesNotExist: raise SubmissionNotFoundError( u"No submission matching uuid {}".format(submission_uuid) ) except DatabaseError: error_msg = u"Could not retrieve submission {}.".format( submission_uuid ) logger.exception(error_msg) raise SubmissionRequestError(msg=error_msg) score = ScoreSerializer( data={ "student_item": submission_model.student_item.pk, "submission": submission_model.pk, "points_earned": points_earned, "points_possible": points_possible, } ) if not score.is_valid(): logger.exception(score.errors) raise SubmissionInternalError(score.errors) # When we save the score, a score summary will be created if # it does not already exist. # When the database's isolation level is set to repeatable-read, # it's possible for a score summary to exist for this student item, # even though we cannot retrieve it. # In this case, we assume that someone else has already created # a score summary and ignore the error. # TODO: once we're using Django 1.8, use transactions to ensure that these # two models are saved at the same time. try: score_model = score.save() _log_score(score_model) if annotation_creator is not None: score_annotation = ScoreAnnotation( score=score_model, creator=annotation_creator, annotation_type=annotation_type, reason=annotation_reason ) score_annotation.save() # Send a signal out to any listeners who are waiting for scoring events. score_set.send( sender=None, points_possible=points_possible, points_earned=points_earned, anonymous_user_id=submission_model.student_item.student_id, course_id=submission_model.student_item.course_id, item_id=submission_model.student_item.item_id, created_at=score_model.created_at, ) except IntegrityError: pass def _log_submission(submission, student_item): """ Log the creation of a submission. Args: submission (dict): The serialized submission model. student_item (dict): The serialized student item model. Returns: None """ logger.info( u"Created submission uuid={submission_uuid} for " u"(course_id={course_id}, item_id={item_id}, " u"anonymous_student_id={anonymous_student_id})" .format( submission_uuid=submission["uuid"], course_id=student_item["course_id"], item_id=student_item["item_id"], anonymous_student_id=student_item["student_id"] ) ) def _log_score(score): """ Log the creation of a score. Args: score (Score): The score model. Returns: None """ logger.info( "Score of ({}/{}) set for submission {}" .format(score.points_earned, score.points_possible, score.submission.uuid) ) def _get_or_create_student_item(student_item_dict): """Gets or creates a Student Item that matches the values specified. Attempts to get the specified Student Item. If it does not exist, the specified parameters are validated, and a new Student Item is created. Args: student_item_dict (dict): The dict containing the student_id, item_id, course_id, and item_type that uniquely defines a student item. Returns: StudentItem: The student item that was retrieved or created. Raises: SubmissionInternalError: Thrown if there was an internal error while attempting to create or retrieve the specified student item. SubmissionRequestError: Thrown if the given student item parameters fail validation. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> _get_or_create_student_item(student_item_dict) {'item_id': 'item_1', 'item_type': 'type_one', 'course_id': 'course_1', 'student_id': 'Tim'} """ try: try: return StudentItem.objects.get(**student_item_dict) except StudentItem.DoesNotExist: student_item_serializer = StudentItemSerializer( data=student_item_dict ) if not student_item_serializer.is_valid(): logger.error( u"Invalid StudentItemSerializer: errors:{} data:{}".format( student_item_serializer.errors, student_item_dict ) ) raise SubmissionRequestError(field_errors=student_item_serializer.errors) return student_item_serializer.save() except DatabaseError: error_message = u"An error occurred creating student item: {}".format( student_item_dict ) logger.exception(error_message) raise SubmissionInternalError(error_message) def _use_read_replica(queryset): """ Use the read replica if it's available. Args: queryset (QuerySet) Returns: QuerySet """ return ( queryset.using("read_replica") if "read_replica" in settings.DATABASES else queryset )
edx/edx-submissions
submissions/api.py
get_scores
python
def get_scores(course_id, student_id): try: score_summaries = ScoreSummary.objects.filter( student_item__course_id=course_id, student_item__student_id=student_id, ).select_related('latest', 'latest__submission', 'student_item') except DatabaseError: msg = u"Could not fetch scores for course {}, student {}".format( course_id, student_id ) logger.exception(msg) raise SubmissionInternalError(msg) scores = { summary.student_item.item_id: UnannotatedScoreSerializer(summary.latest).data for summary in score_summaries if not summary.latest.is_hidden() } return scores
Return a dict mapping item_ids to scores. Scores are represented by serialized Score objects in JSON-like dict format. This method would be used by an LMS to find all the scores for a given student in a given course. Scores that are "hidden" (because they have points earned set to zero) are excluded from the results. Args: course_id (str): Course ID, used to do a lookup on the `StudentItem`. student_id (str): Student ID, used to do a lookup on the `StudentItem`. Returns: dict: The keys are `item_id`s (`str`) and the values are tuples of `(points_earned, points_possible)`. All points are integer values and represent the raw, unweighted scores. Submissions does not have any concept of weights. If there are no entries matching the `course_id` or `student_id`, we simply return an empty dictionary. This is not considered an error because there might be many queries for the progress page of a person who has never submitted anything. Raises: SubmissionInternalError: An unexpected error occurred while resetting scores.
train
https://github.com/edx/edx-submissions/blob/8d531ca25f7c2886dfcb1bb8febe0910e1433ca2/submissions/api.py#L679-L722
null
""" Public interface for the submissions app. """ from __future__ import absolute_import import copy import itertools import logging import operator import json from uuid import UUID from django.conf import settings from django.core.cache import cache from django.db import IntegrityError, DatabaseError from submissions.serializers import ( SubmissionSerializer, StudentItemSerializer, ScoreSerializer, UnannotatedScoreSerializer ) from submissions.models import Submission, StudentItem, Score, ScoreSummary, ScoreAnnotation, score_set, score_reset import six logger = logging.getLogger("submissions.api") # By default, limit the number of top submissions # Anything above this limit will result in a request error MAX_TOP_SUBMISSIONS = 100 # Set a relatively low cache timeout for top submissions. TOP_SUBMISSIONS_CACHE_TIMEOUT = 300 class SubmissionError(Exception): """An error that occurs during submission actions. This error is raised when the submission API cannot perform a requested action. """ pass class SubmissionInternalError(SubmissionError): """An error internal to the Submission API has occurred. This error is raised when an error occurs that is not caused by incorrect use of the API, but rather internal implementation of the underlying services. """ pass class SubmissionNotFoundError(SubmissionError): """This error is raised when no submission is found for the request. If a state is specified in a call to the API that results in no matching Submissions, this error may be raised. """ pass class SubmissionRequestError(SubmissionError): """This error is raised when there was a request-specific error This error is reserved for problems specific to the use of the API. """ def __init__(self, msg="", field_errors=None): """ Configure the submission request error. Keyword Args: msg (unicode): The error message. field_errors (dict): A dictionary of errors (list of unicode) specific to a fields provided in the request. Example usage: >>> raise SubmissionRequestError( >>> "An unexpected error occurred" >>> {"answer": ["Maximum answer length exceeded."]} >>> ) """ super(SubmissionRequestError, self).__init__(msg) self.field_errors = ( copy.deepcopy(field_errors) if field_errors is not None else {} ) self.args += (self.field_errors,) def __repr__(self): """ Show the field errors upon output. """ return '{}(msg="{}", field_errors={})'.format( self.__class__.__name__, self.message, self.field_errors ) def create_submission(student_item_dict, answer, submitted_at=None, attempt_number=None): """Creates a submission for assessment. Generic means by which to submit an answer for assessment. Args: student_item_dict (dict): The student_item this submission is associated with. This is used to determine which course, student, and location this submission belongs to. answer (JSON-serializable): The answer given by the student to be assessed. submitted_at (datetime): The date in which this submission was submitted. If not specified, defaults to the current date. attempt_number (int): A student may be able to submit multiple attempts per question. This allows the designated attempt to be overridden. If the attempt is not specified, it will take the most recent submission, as specified by the submitted_at time, and use its attempt_number plus one. Returns: dict: A representation of the created Submission. The submission contains five attributes: student_item, attempt_number, submitted_at, created_at, and answer. 'student_item' is the ID of the related student item for the submission. 'attempt_number' is the attempt this submission represents for this question. 'submitted_at' represents the time this submission was submitted, which can be configured, versus the 'created_at' date, which is when the submission is first created. Raises: SubmissionRequestError: Raised when there are validation errors for the student item or submission. This can be caused by the student item missing required values, the submission being too long, the attempt_number is negative, or the given submitted_at time is invalid. SubmissionInternalError: Raised when submission access causes an internal error. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> create_submission(student_item_dict, "The answer is 42.", datetime.utcnow, 1) { 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 649284 tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' } """ student_item_model = _get_or_create_student_item(student_item_dict) if attempt_number is None: try: submissions = Submission.objects.filter( student_item=student_item_model)[:1] except DatabaseError: error_message = u"An error occurred while filtering submissions for student item: {}".format( student_item_dict) logger.exception(error_message) raise SubmissionInternalError(error_message) attempt_number = submissions[0].attempt_number + 1 if submissions else 1 model_kwargs = { "student_item": student_item_model.pk, "answer": answer, "attempt_number": attempt_number, } if submitted_at: model_kwargs["submitted_at"] = submitted_at try: submission_serializer = SubmissionSerializer(data=model_kwargs) if not submission_serializer.is_valid(): raise SubmissionRequestError(field_errors=submission_serializer.errors) submission_serializer.save() sub_data = submission_serializer.data _log_submission(sub_data, student_item_dict) return sub_data except DatabaseError: error_message = u"An error occurred while creating submission {} for student item: {}".format( model_kwargs, student_item_dict ) logger.exception(error_message) raise SubmissionInternalError(error_message) def _get_submission_model(uuid, read_replica=False): """ Helper to retrieve a given Submission object from the database. Helper is needed to centralize logic that fixes EDUCATOR-1090, because uuids are stored both with and without hyphens. """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) try: submission = submission_qs.get(uuid=uuid) except Submission.DoesNotExist: try: hyphenated_value = six.text_type(UUID(uuid)) query = """ SELECT `submissions_submission`.`id`, `submissions_submission`.`uuid`, `submissions_submission`.`student_item_id`, `submissions_submission`.`attempt_number`, `submissions_submission`.`submitted_at`, `submissions_submission`.`created_at`, `submissions_submission`.`raw_answer`, `submissions_submission`.`status` FROM `submissions_submission` WHERE ( NOT (`submissions_submission`.`status` = 'D') AND `submissions_submission`.`uuid` = '{}' ) """ query = query.replace("{}", hyphenated_value) # We can use Submission.objects instead of the SoftDeletedManager, we'll include that logic manually submission = Submission.objects.raw(query)[0] except IndexError: raise Submission.DoesNotExist() # Avoid the extra hit next time submission.save(update_fields=['uuid']) return submission def get_submission(submission_uuid, read_replica=False): """Retrieves a single submission by uuid. Args: submission_uuid (str): Identifier for the submission. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Raises: SubmissionNotFoundError: Raised if the submission does not exist. SubmissionRequestError: Raised if the search parameter is not a string. SubmissionInternalError: Raised for unknown errors. Examples: >>> get_submission("20b78e0f32df805d21064fc912f40e9ae5ab260d") { 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' } """ if not isinstance(submission_uuid, six.string_types): if isinstance(submission_uuid, UUID): submission_uuid = six.text_type(submission_uuid) else: raise SubmissionRequestError( msg="submission_uuid ({!r}) must be serializable".format(submission_uuid) ) cache_key = Submission.get_cache_key(submission_uuid) try: cached_submission_data = cache.get(cache_key) except Exception: # The cache backend could raise an exception # (for example, memcache keys that contain spaces) logger.exception("Error occurred while retrieving submission from the cache") cached_submission_data = None if cached_submission_data: logger.info("Get submission {} (cached)".format(submission_uuid)) return cached_submission_data try: submission = _get_submission_model(submission_uuid, read_replica) submission_data = SubmissionSerializer(submission).data cache.set(cache_key, submission_data) except Submission.DoesNotExist: logger.error("Submission {} not found.".format(submission_uuid)) raise SubmissionNotFoundError( u"No submission matching uuid {}".format(submission_uuid) ) except Exception as exc: # Something very unexpected has just happened (like DB misconfig) err_msg = "Could not get submission due to error: {}".format(exc) logger.exception(err_msg) raise SubmissionInternalError(err_msg) logger.info("Get submission {}".format(submission_uuid)) return submission_data def get_submission_and_student(uuid, read_replica=False): """ Retrieve a submission by its unique identifier, including the associated student item. Args: uuid (str): the unique identifier of the submission. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: Serialized Submission model (dict) containing a serialized StudentItem model Raises: SubmissionNotFoundError: Raised if the submission does not exist. SubmissionRequestError: Raised if the search parameter is not a string. SubmissionInternalError: Raised for unknown errors. """ # This may raise API exceptions submission = get_submission(uuid, read_replica=read_replica) # Retrieve the student item from the cache cache_key = "submissions.student_item.{}".format(submission['student_item']) try: cached_student_item = cache.get(cache_key) except Exception: # The cache backend could raise an exception # (for example, memcache keys that contain spaces) logger.exception("Error occurred while retrieving student item from the cache") cached_student_item = None if cached_student_item is not None: submission['student_item'] = cached_student_item else: # There is probably a more idiomatic way to do this using the Django REST framework try: student_item_qs = StudentItem.objects if read_replica: student_item_qs = _use_read_replica(student_item_qs) student_item = student_item_qs.get(id=submission['student_item']) submission['student_item'] = StudentItemSerializer(student_item).data cache.set(cache_key, submission['student_item']) except Exception as ex: err_msg = "Could not get submission due to error: {}".format(ex) logger.exception(err_msg) raise SubmissionInternalError(err_msg) return submission def get_submissions(student_item_dict, limit=None): """Retrieves the submissions for the specified student item, ordered by most recent submitted date. Returns the submissions relative to the specified student item. Exception thrown if no submission is found relative to this location. Args: student_item_dict (dict): The location of the problem this submission is associated with, as defined by a course, student, and item. limit (int): Optional parameter for limiting the returned number of submissions associated with this student item. If not specified, all associated submissions are returned. Returns: List dict: A list of dicts for the associated student item. The submission contains five attributes: student_item, attempt_number, submitted_at, created_at, and answer. 'student_item' is the ID of the related student item for the submission. 'attempt_number' is the attempt this submission represents for this question. 'submitted_at' represents the time this submission was submitted, which can be configured, versus the 'created_at' date, which is when the submission is first created. Raises: SubmissionRequestError: Raised when the associated student item fails validation. SubmissionNotFoundError: Raised when a submission cannot be found for the associated student item. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> get_submissions(student_item_dict, 3) [{ 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' }] """ student_item_model = _get_or_create_student_item(student_item_dict) try: submission_models = Submission.objects.filter( student_item=student_item_model) except DatabaseError: error_message = ( u"Error getting submission request for student item {}" .format(student_item_dict) ) logger.exception(error_message) raise SubmissionNotFoundError(error_message) if limit: submission_models = submission_models[:limit] return SubmissionSerializer(submission_models, many=True).data def get_all_submissions(course_id, item_id, item_type, read_replica=True): """For the given item, get the most recent submission for every student who has submitted. This may return a very large result set! It is implemented as a generator for efficiency. Args: course_id, item_id, item_type (string): The values of the respective student_item fields to filter the submissions by. read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Yields: Dicts representing the submissions with the following fields: student_item student_id attempt_number submitted_at created_at answer Raises: Cannot fail unless there's a database error, but may return an empty iterable. """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) # We cannot use SELECT DISTINCT ON because it's PostgreSQL only, so unfortunately # our results will contain every entry of each student, not just the most recent. # We sort by student_id and primary key, so the reults will be grouped be grouped by # student, with the most recent submission being the first one in each group. query = submission_qs.select_related('student_item').filter( student_item__course_id=course_id, student_item__item_id=item_id, student_item__item_type=item_type, ).order_by('student_item__student_id', '-submitted_at', '-id').iterator() for unused_student_id, row_iter in itertools.groupby(query, operator.attrgetter('student_item.student_id')): submission = next(row_iter) data = SubmissionSerializer(submission).data data['student_id'] = submission.student_item.student_id yield data def get_all_course_submission_information(course_id, item_type, read_replica=True): """ For the given course, get all student items of the given item type, all the submissions for those itemes, and the latest scores for each item. If a submission was given a score that is not the latest score for the relevant student item, it will still be included but without score. Args: course_id (str): The course that we are getting submissions from. item_type (str): The type of items that we are getting submissions for. read_replica (bool): Try to use the database's read replica if it's available. Yields: A tuple of three dictionaries representing: (1) a student item with the following fields: student_id course_id student_item item_type (2) a submission with the following fields: student_item attempt_number submitted_at created_at answer (3) a score with the following fields, if one exists and it is the latest score: (if both conditions are not met, an empty dict is returned here) student_item submission points_earned points_possible created_at submission_uuid """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) query = submission_qs.select_related('student_item__scoresummary__latest__submission').filter( student_item__course_id=course_id, student_item__item_type=item_type, ).iterator() for submission in query: student_item = submission.student_item serialized_score = {} if hasattr(student_item, 'scoresummary'): latest_score = student_item.scoresummary.latest # Only include the score if it is not a reset score (is_hidden), and if the current submission is the same # as the student_item's latest score's submission. This matches the behavior of the API's get_score method. if (not latest_score.is_hidden()) and latest_score.submission.uuid == submission.uuid: serialized_score = ScoreSerializer(latest_score).data yield ( StudentItemSerializer(student_item).data, SubmissionSerializer(submission).data, serialized_score ) def get_top_submissions(course_id, item_id, item_type, number_of_top_scores, use_cache=True, read_replica=True): """Get a number of top scores for an assessment based on a particular student item This function will return top scores for the piece of assessment. It will consider only the latest and greater than 0 score for a piece of assessment. A score is only calculated for a student item if it has completed the workflow for a particular assessment module. In general, users of top submissions can tolerate some latency in the search results, so by default this call uses a cache and the read replica (if available). Args: course_id (str): The course to retrieve for the top scores item_id (str): The item within the course to retrieve for the top scores item_type (str): The type of item to retrieve number_of_top_scores (int): The number of scores to return, greater than 0 and no more than 100. Kwargs: use_cache (bool): If true, check the cache before retrieving querying the database. read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: topscores (dict): The top scores for the assessment for the student item. An empty array if there are no scores or all scores are 0. Raises: SubmissionNotFoundError: Raised when a submission cannot be found for the associated student item. SubmissionRequestError: Raised when the number of top scores is higher than the MAX_TOP_SUBMISSIONS constant. Examples: >>> course_id = "TestCourse" >>> item_id = "u_67" >>> item_type = "openassessment" >>> number_of_top_scores = 10 >>> >>> get_top_submissions(course_id, item_id, item_type, number_of_top_scores) [{ 'score': 20, 'content': "Platypus" },{ 'score': 16, 'content': "Frog" }] """ if number_of_top_scores < 1 or number_of_top_scores > MAX_TOP_SUBMISSIONS: error_msg = ( u"Number of top scores must be a number between 1 and {}.".format(MAX_TOP_SUBMISSIONS) ) logger.exception(error_msg) raise SubmissionRequestError(msg=error_msg) # First check the cache (unless caching is disabled) cache_key = "submissions.top_submissions.{course}.{item}.{type}.{number}".format( course=course_id, item=item_id, type=item_type, number=number_of_top_scores ) top_submissions = cache.get(cache_key) if use_cache else None # If we can't find it in the cache (or caching is disabled), check the database # By default, prefer the read-replica. if top_submissions is None: try: query = ScoreSummary.objects.filter( student_item__course_id=course_id, student_item__item_id=item_id, student_item__item_type=item_type, latest__points_earned__gt=0 ).select_related('latest', 'latest__submission').order_by("-latest__points_earned") if read_replica: query = _use_read_replica(query) score_summaries = query[:number_of_top_scores] except DatabaseError: msg = u"Could not fetch top score summaries for course {}, item {} of type {}".format( course_id, item_id, item_type ) logger.exception(msg) raise SubmissionInternalError(msg) # Retrieve the submission content for each top score top_submissions = [ { "score": score_summary.latest.points_earned, "content": SubmissionSerializer(score_summary.latest.submission).data['answer'] } for score_summary in score_summaries ] # Always store the retrieved list in the cache cache.set(cache_key, top_submissions, TOP_SUBMISSIONS_CACHE_TIMEOUT) return top_submissions def get_score(student_item): """Get the score for a particular student item Each student item should have a unique score. This function will return the score if it is available. A score is only calculated for a student item if it has completed the workflow for a particular assessment module. Args: student_item (dict): The dictionary representation of a student item. Function returns the score related to this student item. Returns: score (dict): The score associated with this student item. None if there is no score found. Raises: SubmissionInternalError: Raised if a score cannot be retrieved because of an internal server error. Examples: >>> student_item = { >>> "student_id":"Tim", >>> "course_id":"TestCourse", >>> "item_id":"u_67", >>> "item_type":"openassessment" >>> } >>> >>> get_score(student_item) [{ 'student_item': 2, 'submission': 2, 'points_earned': 8, 'points_possible': 20, 'created_at': datetime.datetime(2014, 2, 7, 18, 30, 1, 807911, tzinfo=<UTC>) }] """ try: student_item_model = StudentItem.objects.get(**student_item) score = ScoreSummary.objects.get(student_item=student_item_model).latest except (ScoreSummary.DoesNotExist, StudentItem.DoesNotExist): return None # By convention, scores are hidden if "points possible" is set to 0. # This can occur when an instructor has reset scores for a student. if score.is_hidden(): return None else: return ScoreSerializer(score).data def get_latest_score_for_submission(submission_uuid, read_replica=False): """ Retrieve the latest score for a particular submission. Args: submission_uuid (str): The UUID of the submission to retrieve. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: dict: The serialized score model, or None if no score is available. """ try: # Ensure that submission_uuid is valid before fetching score submission_model = _get_submission_model(submission_uuid, read_replica) score_qs = Score.objects.filter( submission__uuid=submission_model.uuid ).order_by("-id").select_related("submission") if read_replica: score_qs = _use_read_replica(score_qs) score = score_qs[0] if score.is_hidden(): return None except (IndexError, Submission.DoesNotExist): return None return ScoreSerializer(score).data def reset_score(student_id, course_id, item_id, clear_state=False, emit_signal=True): """ Reset scores for a specific student on a specific problem. Note: this does *not* delete `Score` models from the database, since these are immutable. It simply creates a new score with the "reset" flag set to True. Args: student_id (unicode): The ID of the student for whom to reset scores. course_id (unicode): The ID of the course containing the item to reset. item_id (unicode): The ID of the item for which to reset scores. clear_state (bool): If True, will appear to delete any submissions associated with the specified StudentItem Returns: None Raises: SubmissionInternalError: An unexpected error occurred while resetting scores. """ # Retrieve the student item try: student_item = StudentItem.objects.get( student_id=student_id, course_id=course_id, item_id=item_id ) except StudentItem.DoesNotExist: # If there is no student item, then there is no score to reset, # so we can return immediately. return # Create a "reset" score try: score = Score.create_reset_score(student_item) if emit_signal: # Send a signal out to any listeners who are waiting for scoring events. score_reset.send( sender=None, anonymous_user_id=student_id, course_id=course_id, item_id=item_id, created_at=score.created_at, ) if clear_state: for sub in student_item.submission_set.all(): # soft-delete the Submission sub.status = Submission.DELETED sub.save(update_fields=["status"]) # Also clear out cached values cache_key = Submission.get_cache_key(sub.uuid) cache.delete(cache_key) except DatabaseError: msg = ( u"Error occurred while reseting scores for" u" item {item_id} in course {course_id} for student {student_id}" ).format(item_id=item_id, course_id=course_id, student_id=student_id) logger.exception(msg) raise SubmissionInternalError(msg) else: msg = u"Score reset for item {item_id} in course {course_id} for student {student_id}".format( item_id=item_id, course_id=course_id, student_id=student_id ) logger.info(msg) def set_score(submission_uuid, points_earned, points_possible, annotation_creator=None, annotation_type=None, annotation_reason=None): """Set a score for a particular submission. Sets the score for a particular submission. This score is calculated externally to the API. Args: submission_uuid (str): UUID for the submission (must exist). points_earned (int): The earned points for this submission. points_possible (int): The total points possible for this particular student item. annotation_creator (str): An optional field for recording who gave this particular score annotation_type (str): An optional field for recording what type of annotation should be created, e.g. "staff_override". annotation_reason (str): An optional field for recording why this score was set to its value. Returns: None Raises: SubmissionInternalError: Thrown if there was an internal error while attempting to save the score. SubmissionRequestError: Thrown if the given student item or submission are not found. Examples: >>> set_score("a778b933-9fb3-11e3-9c0f-040ccee02800", 11, 12) { 'student_item': 2, 'submission': 1, 'points_earned': 11, 'points_possible': 12, 'created_at': datetime.datetime(2014, 2, 7, 20, 6, 42, 331156, tzinfo=<UTC>) } """ try: submission_model = _get_submission_model(submission_uuid) except Submission.DoesNotExist: raise SubmissionNotFoundError( u"No submission matching uuid {}".format(submission_uuid) ) except DatabaseError: error_msg = u"Could not retrieve submission {}.".format( submission_uuid ) logger.exception(error_msg) raise SubmissionRequestError(msg=error_msg) score = ScoreSerializer( data={ "student_item": submission_model.student_item.pk, "submission": submission_model.pk, "points_earned": points_earned, "points_possible": points_possible, } ) if not score.is_valid(): logger.exception(score.errors) raise SubmissionInternalError(score.errors) # When we save the score, a score summary will be created if # it does not already exist. # When the database's isolation level is set to repeatable-read, # it's possible for a score summary to exist for this student item, # even though we cannot retrieve it. # In this case, we assume that someone else has already created # a score summary and ignore the error. # TODO: once we're using Django 1.8, use transactions to ensure that these # two models are saved at the same time. try: score_model = score.save() _log_score(score_model) if annotation_creator is not None: score_annotation = ScoreAnnotation( score=score_model, creator=annotation_creator, annotation_type=annotation_type, reason=annotation_reason ) score_annotation.save() # Send a signal out to any listeners who are waiting for scoring events. score_set.send( sender=None, points_possible=points_possible, points_earned=points_earned, anonymous_user_id=submission_model.student_item.student_id, course_id=submission_model.student_item.course_id, item_id=submission_model.student_item.item_id, created_at=score_model.created_at, ) except IntegrityError: pass def _log_submission(submission, student_item): """ Log the creation of a submission. Args: submission (dict): The serialized submission model. student_item (dict): The serialized student item model. Returns: None """ logger.info( u"Created submission uuid={submission_uuid} for " u"(course_id={course_id}, item_id={item_id}, " u"anonymous_student_id={anonymous_student_id})" .format( submission_uuid=submission["uuid"], course_id=student_item["course_id"], item_id=student_item["item_id"], anonymous_student_id=student_item["student_id"] ) ) def _log_score(score): """ Log the creation of a score. Args: score (Score): The score model. Returns: None """ logger.info( "Score of ({}/{}) set for submission {}" .format(score.points_earned, score.points_possible, score.submission.uuid) ) def _get_or_create_student_item(student_item_dict): """Gets or creates a Student Item that matches the values specified. Attempts to get the specified Student Item. If it does not exist, the specified parameters are validated, and a new Student Item is created. Args: student_item_dict (dict): The dict containing the student_id, item_id, course_id, and item_type that uniquely defines a student item. Returns: StudentItem: The student item that was retrieved or created. Raises: SubmissionInternalError: Thrown if there was an internal error while attempting to create or retrieve the specified student item. SubmissionRequestError: Thrown if the given student item parameters fail validation. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> _get_or_create_student_item(student_item_dict) {'item_id': 'item_1', 'item_type': 'type_one', 'course_id': 'course_1', 'student_id': 'Tim'} """ try: try: return StudentItem.objects.get(**student_item_dict) except StudentItem.DoesNotExist: student_item_serializer = StudentItemSerializer( data=student_item_dict ) if not student_item_serializer.is_valid(): logger.error( u"Invalid StudentItemSerializer: errors:{} data:{}".format( student_item_serializer.errors, student_item_dict ) ) raise SubmissionRequestError(field_errors=student_item_serializer.errors) return student_item_serializer.save() except DatabaseError: error_message = u"An error occurred creating student item: {}".format( student_item_dict ) logger.exception(error_message) raise SubmissionInternalError(error_message) def _use_read_replica(queryset): """ Use the read replica if it's available. Args: queryset (QuerySet) Returns: QuerySet """ return ( queryset.using("read_replica") if "read_replica" in settings.DATABASES else queryset )
edx/edx-submissions
submissions/api.py
reset_score
python
def reset_score(student_id, course_id, item_id, clear_state=False, emit_signal=True): # Retrieve the student item try: student_item = StudentItem.objects.get( student_id=student_id, course_id=course_id, item_id=item_id ) except StudentItem.DoesNotExist: # If there is no student item, then there is no score to reset, # so we can return immediately. return # Create a "reset" score try: score = Score.create_reset_score(student_item) if emit_signal: # Send a signal out to any listeners who are waiting for scoring events. score_reset.send( sender=None, anonymous_user_id=student_id, course_id=course_id, item_id=item_id, created_at=score.created_at, ) if clear_state: for sub in student_item.submission_set.all(): # soft-delete the Submission sub.status = Submission.DELETED sub.save(update_fields=["status"]) # Also clear out cached values cache_key = Submission.get_cache_key(sub.uuid) cache.delete(cache_key) except DatabaseError: msg = ( u"Error occurred while reseting scores for" u" item {item_id} in course {course_id} for student {student_id}" ).format(item_id=item_id, course_id=course_id, student_id=student_id) logger.exception(msg) raise SubmissionInternalError(msg) else: msg = u"Score reset for item {item_id} in course {course_id} for student {student_id}".format( item_id=item_id, course_id=course_id, student_id=student_id ) logger.info(msg)
Reset scores for a specific student on a specific problem. Note: this does *not* delete `Score` models from the database, since these are immutable. It simply creates a new score with the "reset" flag set to True. Args: student_id (unicode): The ID of the student for whom to reset scores. course_id (unicode): The ID of the course containing the item to reset. item_id (unicode): The ID of the item for which to reset scores. clear_state (bool): If True, will appear to delete any submissions associated with the specified StudentItem Returns: None Raises: SubmissionInternalError: An unexpected error occurred while resetting scores.
train
https://github.com/edx/edx-submissions/blob/8d531ca25f7c2886dfcb1bb8febe0910e1433ca2/submissions/api.py#L759-L824
[ "def get_cache_key(sub_uuid):\n return u\"submissions.submission.{}\".format(sub_uuid)\n", "def create_reset_score(cls, student_item):\n \"\"\"\n Create a \"reset\" score (a score with a null submission).\n\n Only scores created after the most recent \"reset\" score\n should be used to determine a student's effective score.\n\n Args:\n student_item (StudentItem): The student item model.\n\n Returns:\n Score: The newly created \"reset\" score.\n\n Raises:\n DatabaseError: An error occurred while creating the score\n\n \"\"\"\n # By setting the \"reset\" flag, we ensure that the \"highest\"\n # score in the score summary will point to this score.\n # By setting points earned and points possible to 0,\n # we ensure that this score will be hidden from the user.\n return cls.objects.create(\n student_item=student_item,\n submission=None,\n points_earned=0,\n points_possible=0,\n reset=True,\n )\n" ]
""" Public interface for the submissions app. """ from __future__ import absolute_import import copy import itertools import logging import operator import json from uuid import UUID from django.conf import settings from django.core.cache import cache from django.db import IntegrityError, DatabaseError from submissions.serializers import ( SubmissionSerializer, StudentItemSerializer, ScoreSerializer, UnannotatedScoreSerializer ) from submissions.models import Submission, StudentItem, Score, ScoreSummary, ScoreAnnotation, score_set, score_reset import six logger = logging.getLogger("submissions.api") # By default, limit the number of top submissions # Anything above this limit will result in a request error MAX_TOP_SUBMISSIONS = 100 # Set a relatively low cache timeout for top submissions. TOP_SUBMISSIONS_CACHE_TIMEOUT = 300 class SubmissionError(Exception): """An error that occurs during submission actions. This error is raised when the submission API cannot perform a requested action. """ pass class SubmissionInternalError(SubmissionError): """An error internal to the Submission API has occurred. This error is raised when an error occurs that is not caused by incorrect use of the API, but rather internal implementation of the underlying services. """ pass class SubmissionNotFoundError(SubmissionError): """This error is raised when no submission is found for the request. If a state is specified in a call to the API that results in no matching Submissions, this error may be raised. """ pass class SubmissionRequestError(SubmissionError): """This error is raised when there was a request-specific error This error is reserved for problems specific to the use of the API. """ def __init__(self, msg="", field_errors=None): """ Configure the submission request error. Keyword Args: msg (unicode): The error message. field_errors (dict): A dictionary of errors (list of unicode) specific to a fields provided in the request. Example usage: >>> raise SubmissionRequestError( >>> "An unexpected error occurred" >>> {"answer": ["Maximum answer length exceeded."]} >>> ) """ super(SubmissionRequestError, self).__init__(msg) self.field_errors = ( copy.deepcopy(field_errors) if field_errors is not None else {} ) self.args += (self.field_errors,) def __repr__(self): """ Show the field errors upon output. """ return '{}(msg="{}", field_errors={})'.format( self.__class__.__name__, self.message, self.field_errors ) def create_submission(student_item_dict, answer, submitted_at=None, attempt_number=None): """Creates a submission for assessment. Generic means by which to submit an answer for assessment. Args: student_item_dict (dict): The student_item this submission is associated with. This is used to determine which course, student, and location this submission belongs to. answer (JSON-serializable): The answer given by the student to be assessed. submitted_at (datetime): The date in which this submission was submitted. If not specified, defaults to the current date. attempt_number (int): A student may be able to submit multiple attempts per question. This allows the designated attempt to be overridden. If the attempt is not specified, it will take the most recent submission, as specified by the submitted_at time, and use its attempt_number plus one. Returns: dict: A representation of the created Submission. The submission contains five attributes: student_item, attempt_number, submitted_at, created_at, and answer. 'student_item' is the ID of the related student item for the submission. 'attempt_number' is the attempt this submission represents for this question. 'submitted_at' represents the time this submission was submitted, which can be configured, versus the 'created_at' date, which is when the submission is first created. Raises: SubmissionRequestError: Raised when there are validation errors for the student item or submission. This can be caused by the student item missing required values, the submission being too long, the attempt_number is negative, or the given submitted_at time is invalid. SubmissionInternalError: Raised when submission access causes an internal error. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> create_submission(student_item_dict, "The answer is 42.", datetime.utcnow, 1) { 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 649284 tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' } """ student_item_model = _get_or_create_student_item(student_item_dict) if attempt_number is None: try: submissions = Submission.objects.filter( student_item=student_item_model)[:1] except DatabaseError: error_message = u"An error occurred while filtering submissions for student item: {}".format( student_item_dict) logger.exception(error_message) raise SubmissionInternalError(error_message) attempt_number = submissions[0].attempt_number + 1 if submissions else 1 model_kwargs = { "student_item": student_item_model.pk, "answer": answer, "attempt_number": attempt_number, } if submitted_at: model_kwargs["submitted_at"] = submitted_at try: submission_serializer = SubmissionSerializer(data=model_kwargs) if not submission_serializer.is_valid(): raise SubmissionRequestError(field_errors=submission_serializer.errors) submission_serializer.save() sub_data = submission_serializer.data _log_submission(sub_data, student_item_dict) return sub_data except DatabaseError: error_message = u"An error occurred while creating submission {} for student item: {}".format( model_kwargs, student_item_dict ) logger.exception(error_message) raise SubmissionInternalError(error_message) def _get_submission_model(uuid, read_replica=False): """ Helper to retrieve a given Submission object from the database. Helper is needed to centralize logic that fixes EDUCATOR-1090, because uuids are stored both with and without hyphens. """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) try: submission = submission_qs.get(uuid=uuid) except Submission.DoesNotExist: try: hyphenated_value = six.text_type(UUID(uuid)) query = """ SELECT `submissions_submission`.`id`, `submissions_submission`.`uuid`, `submissions_submission`.`student_item_id`, `submissions_submission`.`attempt_number`, `submissions_submission`.`submitted_at`, `submissions_submission`.`created_at`, `submissions_submission`.`raw_answer`, `submissions_submission`.`status` FROM `submissions_submission` WHERE ( NOT (`submissions_submission`.`status` = 'D') AND `submissions_submission`.`uuid` = '{}' ) """ query = query.replace("{}", hyphenated_value) # We can use Submission.objects instead of the SoftDeletedManager, we'll include that logic manually submission = Submission.objects.raw(query)[0] except IndexError: raise Submission.DoesNotExist() # Avoid the extra hit next time submission.save(update_fields=['uuid']) return submission def get_submission(submission_uuid, read_replica=False): """Retrieves a single submission by uuid. Args: submission_uuid (str): Identifier for the submission. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Raises: SubmissionNotFoundError: Raised if the submission does not exist. SubmissionRequestError: Raised if the search parameter is not a string. SubmissionInternalError: Raised for unknown errors. Examples: >>> get_submission("20b78e0f32df805d21064fc912f40e9ae5ab260d") { 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' } """ if not isinstance(submission_uuid, six.string_types): if isinstance(submission_uuid, UUID): submission_uuid = six.text_type(submission_uuid) else: raise SubmissionRequestError( msg="submission_uuid ({!r}) must be serializable".format(submission_uuid) ) cache_key = Submission.get_cache_key(submission_uuid) try: cached_submission_data = cache.get(cache_key) except Exception: # The cache backend could raise an exception # (for example, memcache keys that contain spaces) logger.exception("Error occurred while retrieving submission from the cache") cached_submission_data = None if cached_submission_data: logger.info("Get submission {} (cached)".format(submission_uuid)) return cached_submission_data try: submission = _get_submission_model(submission_uuid, read_replica) submission_data = SubmissionSerializer(submission).data cache.set(cache_key, submission_data) except Submission.DoesNotExist: logger.error("Submission {} not found.".format(submission_uuid)) raise SubmissionNotFoundError( u"No submission matching uuid {}".format(submission_uuid) ) except Exception as exc: # Something very unexpected has just happened (like DB misconfig) err_msg = "Could not get submission due to error: {}".format(exc) logger.exception(err_msg) raise SubmissionInternalError(err_msg) logger.info("Get submission {}".format(submission_uuid)) return submission_data def get_submission_and_student(uuid, read_replica=False): """ Retrieve a submission by its unique identifier, including the associated student item. Args: uuid (str): the unique identifier of the submission. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: Serialized Submission model (dict) containing a serialized StudentItem model Raises: SubmissionNotFoundError: Raised if the submission does not exist. SubmissionRequestError: Raised if the search parameter is not a string. SubmissionInternalError: Raised for unknown errors. """ # This may raise API exceptions submission = get_submission(uuid, read_replica=read_replica) # Retrieve the student item from the cache cache_key = "submissions.student_item.{}".format(submission['student_item']) try: cached_student_item = cache.get(cache_key) except Exception: # The cache backend could raise an exception # (for example, memcache keys that contain spaces) logger.exception("Error occurred while retrieving student item from the cache") cached_student_item = None if cached_student_item is not None: submission['student_item'] = cached_student_item else: # There is probably a more idiomatic way to do this using the Django REST framework try: student_item_qs = StudentItem.objects if read_replica: student_item_qs = _use_read_replica(student_item_qs) student_item = student_item_qs.get(id=submission['student_item']) submission['student_item'] = StudentItemSerializer(student_item).data cache.set(cache_key, submission['student_item']) except Exception as ex: err_msg = "Could not get submission due to error: {}".format(ex) logger.exception(err_msg) raise SubmissionInternalError(err_msg) return submission def get_submissions(student_item_dict, limit=None): """Retrieves the submissions for the specified student item, ordered by most recent submitted date. Returns the submissions relative to the specified student item. Exception thrown if no submission is found relative to this location. Args: student_item_dict (dict): The location of the problem this submission is associated with, as defined by a course, student, and item. limit (int): Optional parameter for limiting the returned number of submissions associated with this student item. If not specified, all associated submissions are returned. Returns: List dict: A list of dicts for the associated student item. The submission contains five attributes: student_item, attempt_number, submitted_at, created_at, and answer. 'student_item' is the ID of the related student item for the submission. 'attempt_number' is the attempt this submission represents for this question. 'submitted_at' represents the time this submission was submitted, which can be configured, versus the 'created_at' date, which is when the submission is first created. Raises: SubmissionRequestError: Raised when the associated student item fails validation. SubmissionNotFoundError: Raised when a submission cannot be found for the associated student item. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> get_submissions(student_item_dict, 3) [{ 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' }] """ student_item_model = _get_or_create_student_item(student_item_dict) try: submission_models = Submission.objects.filter( student_item=student_item_model) except DatabaseError: error_message = ( u"Error getting submission request for student item {}" .format(student_item_dict) ) logger.exception(error_message) raise SubmissionNotFoundError(error_message) if limit: submission_models = submission_models[:limit] return SubmissionSerializer(submission_models, many=True).data def get_all_submissions(course_id, item_id, item_type, read_replica=True): """For the given item, get the most recent submission for every student who has submitted. This may return a very large result set! It is implemented as a generator for efficiency. Args: course_id, item_id, item_type (string): The values of the respective student_item fields to filter the submissions by. read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Yields: Dicts representing the submissions with the following fields: student_item student_id attempt_number submitted_at created_at answer Raises: Cannot fail unless there's a database error, but may return an empty iterable. """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) # We cannot use SELECT DISTINCT ON because it's PostgreSQL only, so unfortunately # our results will contain every entry of each student, not just the most recent. # We sort by student_id and primary key, so the reults will be grouped be grouped by # student, with the most recent submission being the first one in each group. query = submission_qs.select_related('student_item').filter( student_item__course_id=course_id, student_item__item_id=item_id, student_item__item_type=item_type, ).order_by('student_item__student_id', '-submitted_at', '-id').iterator() for unused_student_id, row_iter in itertools.groupby(query, operator.attrgetter('student_item.student_id')): submission = next(row_iter) data = SubmissionSerializer(submission).data data['student_id'] = submission.student_item.student_id yield data def get_all_course_submission_information(course_id, item_type, read_replica=True): """ For the given course, get all student items of the given item type, all the submissions for those itemes, and the latest scores for each item. If a submission was given a score that is not the latest score for the relevant student item, it will still be included but without score. Args: course_id (str): The course that we are getting submissions from. item_type (str): The type of items that we are getting submissions for. read_replica (bool): Try to use the database's read replica if it's available. Yields: A tuple of three dictionaries representing: (1) a student item with the following fields: student_id course_id student_item item_type (2) a submission with the following fields: student_item attempt_number submitted_at created_at answer (3) a score with the following fields, if one exists and it is the latest score: (if both conditions are not met, an empty dict is returned here) student_item submission points_earned points_possible created_at submission_uuid """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) query = submission_qs.select_related('student_item__scoresummary__latest__submission').filter( student_item__course_id=course_id, student_item__item_type=item_type, ).iterator() for submission in query: student_item = submission.student_item serialized_score = {} if hasattr(student_item, 'scoresummary'): latest_score = student_item.scoresummary.latest # Only include the score if it is not a reset score (is_hidden), and if the current submission is the same # as the student_item's latest score's submission. This matches the behavior of the API's get_score method. if (not latest_score.is_hidden()) and latest_score.submission.uuid == submission.uuid: serialized_score = ScoreSerializer(latest_score).data yield ( StudentItemSerializer(student_item).data, SubmissionSerializer(submission).data, serialized_score ) def get_top_submissions(course_id, item_id, item_type, number_of_top_scores, use_cache=True, read_replica=True): """Get a number of top scores for an assessment based on a particular student item This function will return top scores for the piece of assessment. It will consider only the latest and greater than 0 score for a piece of assessment. A score is only calculated for a student item if it has completed the workflow for a particular assessment module. In general, users of top submissions can tolerate some latency in the search results, so by default this call uses a cache and the read replica (if available). Args: course_id (str): The course to retrieve for the top scores item_id (str): The item within the course to retrieve for the top scores item_type (str): The type of item to retrieve number_of_top_scores (int): The number of scores to return, greater than 0 and no more than 100. Kwargs: use_cache (bool): If true, check the cache before retrieving querying the database. read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: topscores (dict): The top scores for the assessment for the student item. An empty array if there are no scores or all scores are 0. Raises: SubmissionNotFoundError: Raised when a submission cannot be found for the associated student item. SubmissionRequestError: Raised when the number of top scores is higher than the MAX_TOP_SUBMISSIONS constant. Examples: >>> course_id = "TestCourse" >>> item_id = "u_67" >>> item_type = "openassessment" >>> number_of_top_scores = 10 >>> >>> get_top_submissions(course_id, item_id, item_type, number_of_top_scores) [{ 'score': 20, 'content': "Platypus" },{ 'score': 16, 'content': "Frog" }] """ if number_of_top_scores < 1 or number_of_top_scores > MAX_TOP_SUBMISSIONS: error_msg = ( u"Number of top scores must be a number between 1 and {}.".format(MAX_TOP_SUBMISSIONS) ) logger.exception(error_msg) raise SubmissionRequestError(msg=error_msg) # First check the cache (unless caching is disabled) cache_key = "submissions.top_submissions.{course}.{item}.{type}.{number}".format( course=course_id, item=item_id, type=item_type, number=number_of_top_scores ) top_submissions = cache.get(cache_key) if use_cache else None # If we can't find it in the cache (or caching is disabled), check the database # By default, prefer the read-replica. if top_submissions is None: try: query = ScoreSummary.objects.filter( student_item__course_id=course_id, student_item__item_id=item_id, student_item__item_type=item_type, latest__points_earned__gt=0 ).select_related('latest', 'latest__submission').order_by("-latest__points_earned") if read_replica: query = _use_read_replica(query) score_summaries = query[:number_of_top_scores] except DatabaseError: msg = u"Could not fetch top score summaries for course {}, item {} of type {}".format( course_id, item_id, item_type ) logger.exception(msg) raise SubmissionInternalError(msg) # Retrieve the submission content for each top score top_submissions = [ { "score": score_summary.latest.points_earned, "content": SubmissionSerializer(score_summary.latest.submission).data['answer'] } for score_summary in score_summaries ] # Always store the retrieved list in the cache cache.set(cache_key, top_submissions, TOP_SUBMISSIONS_CACHE_TIMEOUT) return top_submissions def get_score(student_item): """Get the score for a particular student item Each student item should have a unique score. This function will return the score if it is available. A score is only calculated for a student item if it has completed the workflow for a particular assessment module. Args: student_item (dict): The dictionary representation of a student item. Function returns the score related to this student item. Returns: score (dict): The score associated with this student item. None if there is no score found. Raises: SubmissionInternalError: Raised if a score cannot be retrieved because of an internal server error. Examples: >>> student_item = { >>> "student_id":"Tim", >>> "course_id":"TestCourse", >>> "item_id":"u_67", >>> "item_type":"openassessment" >>> } >>> >>> get_score(student_item) [{ 'student_item': 2, 'submission': 2, 'points_earned': 8, 'points_possible': 20, 'created_at': datetime.datetime(2014, 2, 7, 18, 30, 1, 807911, tzinfo=<UTC>) }] """ try: student_item_model = StudentItem.objects.get(**student_item) score = ScoreSummary.objects.get(student_item=student_item_model).latest except (ScoreSummary.DoesNotExist, StudentItem.DoesNotExist): return None # By convention, scores are hidden if "points possible" is set to 0. # This can occur when an instructor has reset scores for a student. if score.is_hidden(): return None else: return ScoreSerializer(score).data def get_scores(course_id, student_id): """Return a dict mapping item_ids to scores. Scores are represented by serialized Score objects in JSON-like dict format. This method would be used by an LMS to find all the scores for a given student in a given course. Scores that are "hidden" (because they have points earned set to zero) are excluded from the results. Args: course_id (str): Course ID, used to do a lookup on the `StudentItem`. student_id (str): Student ID, used to do a lookup on the `StudentItem`. Returns: dict: The keys are `item_id`s (`str`) and the values are tuples of `(points_earned, points_possible)`. All points are integer values and represent the raw, unweighted scores. Submissions does not have any concept of weights. If there are no entries matching the `course_id` or `student_id`, we simply return an empty dictionary. This is not considered an error because there might be many queries for the progress page of a person who has never submitted anything. Raises: SubmissionInternalError: An unexpected error occurred while resetting scores. """ try: score_summaries = ScoreSummary.objects.filter( student_item__course_id=course_id, student_item__student_id=student_id, ).select_related('latest', 'latest__submission', 'student_item') except DatabaseError: msg = u"Could not fetch scores for course {}, student {}".format( course_id, student_id ) logger.exception(msg) raise SubmissionInternalError(msg) scores = { summary.student_item.item_id: UnannotatedScoreSerializer(summary.latest).data for summary in score_summaries if not summary.latest.is_hidden() } return scores def get_latest_score_for_submission(submission_uuid, read_replica=False): """ Retrieve the latest score for a particular submission. Args: submission_uuid (str): The UUID of the submission to retrieve. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: dict: The serialized score model, or None if no score is available. """ try: # Ensure that submission_uuid is valid before fetching score submission_model = _get_submission_model(submission_uuid, read_replica) score_qs = Score.objects.filter( submission__uuid=submission_model.uuid ).order_by("-id").select_related("submission") if read_replica: score_qs = _use_read_replica(score_qs) score = score_qs[0] if score.is_hidden(): return None except (IndexError, Submission.DoesNotExist): return None return ScoreSerializer(score).data def set_score(submission_uuid, points_earned, points_possible, annotation_creator=None, annotation_type=None, annotation_reason=None): """Set a score for a particular submission. Sets the score for a particular submission. This score is calculated externally to the API. Args: submission_uuid (str): UUID for the submission (must exist). points_earned (int): The earned points for this submission. points_possible (int): The total points possible for this particular student item. annotation_creator (str): An optional field for recording who gave this particular score annotation_type (str): An optional field for recording what type of annotation should be created, e.g. "staff_override". annotation_reason (str): An optional field for recording why this score was set to its value. Returns: None Raises: SubmissionInternalError: Thrown if there was an internal error while attempting to save the score. SubmissionRequestError: Thrown if the given student item or submission are not found. Examples: >>> set_score("a778b933-9fb3-11e3-9c0f-040ccee02800", 11, 12) { 'student_item': 2, 'submission': 1, 'points_earned': 11, 'points_possible': 12, 'created_at': datetime.datetime(2014, 2, 7, 20, 6, 42, 331156, tzinfo=<UTC>) } """ try: submission_model = _get_submission_model(submission_uuid) except Submission.DoesNotExist: raise SubmissionNotFoundError( u"No submission matching uuid {}".format(submission_uuid) ) except DatabaseError: error_msg = u"Could not retrieve submission {}.".format( submission_uuid ) logger.exception(error_msg) raise SubmissionRequestError(msg=error_msg) score = ScoreSerializer( data={ "student_item": submission_model.student_item.pk, "submission": submission_model.pk, "points_earned": points_earned, "points_possible": points_possible, } ) if not score.is_valid(): logger.exception(score.errors) raise SubmissionInternalError(score.errors) # When we save the score, a score summary will be created if # it does not already exist. # When the database's isolation level is set to repeatable-read, # it's possible for a score summary to exist for this student item, # even though we cannot retrieve it. # In this case, we assume that someone else has already created # a score summary and ignore the error. # TODO: once we're using Django 1.8, use transactions to ensure that these # two models are saved at the same time. try: score_model = score.save() _log_score(score_model) if annotation_creator is not None: score_annotation = ScoreAnnotation( score=score_model, creator=annotation_creator, annotation_type=annotation_type, reason=annotation_reason ) score_annotation.save() # Send a signal out to any listeners who are waiting for scoring events. score_set.send( sender=None, points_possible=points_possible, points_earned=points_earned, anonymous_user_id=submission_model.student_item.student_id, course_id=submission_model.student_item.course_id, item_id=submission_model.student_item.item_id, created_at=score_model.created_at, ) except IntegrityError: pass def _log_submission(submission, student_item): """ Log the creation of a submission. Args: submission (dict): The serialized submission model. student_item (dict): The serialized student item model. Returns: None """ logger.info( u"Created submission uuid={submission_uuid} for " u"(course_id={course_id}, item_id={item_id}, " u"anonymous_student_id={anonymous_student_id})" .format( submission_uuid=submission["uuid"], course_id=student_item["course_id"], item_id=student_item["item_id"], anonymous_student_id=student_item["student_id"] ) ) def _log_score(score): """ Log the creation of a score. Args: score (Score): The score model. Returns: None """ logger.info( "Score of ({}/{}) set for submission {}" .format(score.points_earned, score.points_possible, score.submission.uuid) ) def _get_or_create_student_item(student_item_dict): """Gets or creates a Student Item that matches the values specified. Attempts to get the specified Student Item. If it does not exist, the specified parameters are validated, and a new Student Item is created. Args: student_item_dict (dict): The dict containing the student_id, item_id, course_id, and item_type that uniquely defines a student item. Returns: StudentItem: The student item that was retrieved or created. Raises: SubmissionInternalError: Thrown if there was an internal error while attempting to create or retrieve the specified student item. SubmissionRequestError: Thrown if the given student item parameters fail validation. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> _get_or_create_student_item(student_item_dict) {'item_id': 'item_1', 'item_type': 'type_one', 'course_id': 'course_1', 'student_id': 'Tim'} """ try: try: return StudentItem.objects.get(**student_item_dict) except StudentItem.DoesNotExist: student_item_serializer = StudentItemSerializer( data=student_item_dict ) if not student_item_serializer.is_valid(): logger.error( u"Invalid StudentItemSerializer: errors:{} data:{}".format( student_item_serializer.errors, student_item_dict ) ) raise SubmissionRequestError(field_errors=student_item_serializer.errors) return student_item_serializer.save() except DatabaseError: error_message = u"An error occurred creating student item: {}".format( student_item_dict ) logger.exception(error_message) raise SubmissionInternalError(error_message) def _use_read_replica(queryset): """ Use the read replica if it's available. Args: queryset (QuerySet) Returns: QuerySet """ return ( queryset.using("read_replica") if "read_replica" in settings.DATABASES else queryset )
edx/edx-submissions
submissions/api.py
set_score
python
def set_score(submission_uuid, points_earned, points_possible, annotation_creator=None, annotation_type=None, annotation_reason=None): try: submission_model = _get_submission_model(submission_uuid) except Submission.DoesNotExist: raise SubmissionNotFoundError( u"No submission matching uuid {}".format(submission_uuid) ) except DatabaseError: error_msg = u"Could not retrieve submission {}.".format( submission_uuid ) logger.exception(error_msg) raise SubmissionRequestError(msg=error_msg) score = ScoreSerializer( data={ "student_item": submission_model.student_item.pk, "submission": submission_model.pk, "points_earned": points_earned, "points_possible": points_possible, } ) if not score.is_valid(): logger.exception(score.errors) raise SubmissionInternalError(score.errors) # When we save the score, a score summary will be created if # it does not already exist. # When the database's isolation level is set to repeatable-read, # it's possible for a score summary to exist for this student item, # even though we cannot retrieve it. # In this case, we assume that someone else has already created # a score summary and ignore the error. # TODO: once we're using Django 1.8, use transactions to ensure that these # two models are saved at the same time. try: score_model = score.save() _log_score(score_model) if annotation_creator is not None: score_annotation = ScoreAnnotation( score=score_model, creator=annotation_creator, annotation_type=annotation_type, reason=annotation_reason ) score_annotation.save() # Send a signal out to any listeners who are waiting for scoring events. score_set.send( sender=None, points_possible=points_possible, points_earned=points_earned, anonymous_user_id=submission_model.student_item.student_id, course_id=submission_model.student_item.course_id, item_id=submission_model.student_item.item_id, created_at=score_model.created_at, ) except IntegrityError: pass
Set a score for a particular submission. Sets the score for a particular submission. This score is calculated externally to the API. Args: submission_uuid (str): UUID for the submission (must exist). points_earned (int): The earned points for this submission. points_possible (int): The total points possible for this particular student item. annotation_creator (str): An optional field for recording who gave this particular score annotation_type (str): An optional field for recording what type of annotation should be created, e.g. "staff_override". annotation_reason (str): An optional field for recording why this score was set to its value. Returns: None Raises: SubmissionInternalError: Thrown if there was an internal error while attempting to save the score. SubmissionRequestError: Thrown if the given student item or submission are not found. Examples: >>> set_score("a778b933-9fb3-11e3-9c0f-040ccee02800", 11, 12) { 'student_item': 2, 'submission': 1, 'points_earned': 11, 'points_possible': 12, 'created_at': datetime.datetime(2014, 2, 7, 20, 6, 42, 331156, tzinfo=<UTC>) }
train
https://github.com/edx/edx-submissions/blob/8d531ca25f7c2886dfcb1bb8febe0910e1433ca2/submissions/api.py#L827-L920
[ "def _get_submission_model(uuid, read_replica=False):\n \"\"\"\n Helper to retrieve a given Submission object from the database. Helper is needed to centralize logic that fixes\n EDUCATOR-1090, because uuids are stored both with and without hyphens.\n \"\"\"\n submission_qs = Submission.objects\n if read_replica:\n submission_qs = _use_read_replica(submission_qs)\n try:\n submission = submission_qs.get(uuid=uuid)\n except Submission.DoesNotExist:\n try:\n hyphenated_value = six.text_type(UUID(uuid))\n query = \"\"\"\n SELECT\n `submissions_submission`.`id`,\n `submissions_submission`.`uuid`,\n `submissions_submission`.`student_item_id`,\n `submissions_submission`.`attempt_number`,\n `submissions_submission`.`submitted_at`,\n `submissions_submission`.`created_at`,\n `submissions_submission`.`raw_answer`,\n `submissions_submission`.`status`\n FROM\n `submissions_submission`\n WHERE (\n NOT (`submissions_submission`.`status` = 'D')\n AND `submissions_submission`.`uuid` = '{}'\n )\n \"\"\"\n query = query.replace(\"{}\", hyphenated_value)\n\n # We can use Submission.objects instead of the SoftDeletedManager, we'll include that logic manually\n submission = Submission.objects.raw(query)[0]\n except IndexError:\n raise Submission.DoesNotExist()\n # Avoid the extra hit next time\n submission.save(update_fields=['uuid'])\n return submission\n" ]
""" Public interface for the submissions app. """ from __future__ import absolute_import import copy import itertools import logging import operator import json from uuid import UUID from django.conf import settings from django.core.cache import cache from django.db import IntegrityError, DatabaseError from submissions.serializers import ( SubmissionSerializer, StudentItemSerializer, ScoreSerializer, UnannotatedScoreSerializer ) from submissions.models import Submission, StudentItem, Score, ScoreSummary, ScoreAnnotation, score_set, score_reset import six logger = logging.getLogger("submissions.api") # By default, limit the number of top submissions # Anything above this limit will result in a request error MAX_TOP_SUBMISSIONS = 100 # Set a relatively low cache timeout for top submissions. TOP_SUBMISSIONS_CACHE_TIMEOUT = 300 class SubmissionError(Exception): """An error that occurs during submission actions. This error is raised when the submission API cannot perform a requested action. """ pass class SubmissionInternalError(SubmissionError): """An error internal to the Submission API has occurred. This error is raised when an error occurs that is not caused by incorrect use of the API, but rather internal implementation of the underlying services. """ pass class SubmissionNotFoundError(SubmissionError): """This error is raised when no submission is found for the request. If a state is specified in a call to the API that results in no matching Submissions, this error may be raised. """ pass class SubmissionRequestError(SubmissionError): """This error is raised when there was a request-specific error This error is reserved for problems specific to the use of the API. """ def __init__(self, msg="", field_errors=None): """ Configure the submission request error. Keyword Args: msg (unicode): The error message. field_errors (dict): A dictionary of errors (list of unicode) specific to a fields provided in the request. Example usage: >>> raise SubmissionRequestError( >>> "An unexpected error occurred" >>> {"answer": ["Maximum answer length exceeded."]} >>> ) """ super(SubmissionRequestError, self).__init__(msg) self.field_errors = ( copy.deepcopy(field_errors) if field_errors is not None else {} ) self.args += (self.field_errors,) def __repr__(self): """ Show the field errors upon output. """ return '{}(msg="{}", field_errors={})'.format( self.__class__.__name__, self.message, self.field_errors ) def create_submission(student_item_dict, answer, submitted_at=None, attempt_number=None): """Creates a submission for assessment. Generic means by which to submit an answer for assessment. Args: student_item_dict (dict): The student_item this submission is associated with. This is used to determine which course, student, and location this submission belongs to. answer (JSON-serializable): The answer given by the student to be assessed. submitted_at (datetime): The date in which this submission was submitted. If not specified, defaults to the current date. attempt_number (int): A student may be able to submit multiple attempts per question. This allows the designated attempt to be overridden. If the attempt is not specified, it will take the most recent submission, as specified by the submitted_at time, and use its attempt_number plus one. Returns: dict: A representation of the created Submission. The submission contains five attributes: student_item, attempt_number, submitted_at, created_at, and answer. 'student_item' is the ID of the related student item for the submission. 'attempt_number' is the attempt this submission represents for this question. 'submitted_at' represents the time this submission was submitted, which can be configured, versus the 'created_at' date, which is when the submission is first created. Raises: SubmissionRequestError: Raised when there are validation errors for the student item or submission. This can be caused by the student item missing required values, the submission being too long, the attempt_number is negative, or the given submitted_at time is invalid. SubmissionInternalError: Raised when submission access causes an internal error. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> create_submission(student_item_dict, "The answer is 42.", datetime.utcnow, 1) { 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 649284 tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' } """ student_item_model = _get_or_create_student_item(student_item_dict) if attempt_number is None: try: submissions = Submission.objects.filter( student_item=student_item_model)[:1] except DatabaseError: error_message = u"An error occurred while filtering submissions for student item: {}".format( student_item_dict) logger.exception(error_message) raise SubmissionInternalError(error_message) attempt_number = submissions[0].attempt_number + 1 if submissions else 1 model_kwargs = { "student_item": student_item_model.pk, "answer": answer, "attempt_number": attempt_number, } if submitted_at: model_kwargs["submitted_at"] = submitted_at try: submission_serializer = SubmissionSerializer(data=model_kwargs) if not submission_serializer.is_valid(): raise SubmissionRequestError(field_errors=submission_serializer.errors) submission_serializer.save() sub_data = submission_serializer.data _log_submission(sub_data, student_item_dict) return sub_data except DatabaseError: error_message = u"An error occurred while creating submission {} for student item: {}".format( model_kwargs, student_item_dict ) logger.exception(error_message) raise SubmissionInternalError(error_message) def _get_submission_model(uuid, read_replica=False): """ Helper to retrieve a given Submission object from the database. Helper is needed to centralize logic that fixes EDUCATOR-1090, because uuids are stored both with and without hyphens. """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) try: submission = submission_qs.get(uuid=uuid) except Submission.DoesNotExist: try: hyphenated_value = six.text_type(UUID(uuid)) query = """ SELECT `submissions_submission`.`id`, `submissions_submission`.`uuid`, `submissions_submission`.`student_item_id`, `submissions_submission`.`attempt_number`, `submissions_submission`.`submitted_at`, `submissions_submission`.`created_at`, `submissions_submission`.`raw_answer`, `submissions_submission`.`status` FROM `submissions_submission` WHERE ( NOT (`submissions_submission`.`status` = 'D') AND `submissions_submission`.`uuid` = '{}' ) """ query = query.replace("{}", hyphenated_value) # We can use Submission.objects instead of the SoftDeletedManager, we'll include that logic manually submission = Submission.objects.raw(query)[0] except IndexError: raise Submission.DoesNotExist() # Avoid the extra hit next time submission.save(update_fields=['uuid']) return submission def get_submission(submission_uuid, read_replica=False): """Retrieves a single submission by uuid. Args: submission_uuid (str): Identifier for the submission. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Raises: SubmissionNotFoundError: Raised if the submission does not exist. SubmissionRequestError: Raised if the search parameter is not a string. SubmissionInternalError: Raised for unknown errors. Examples: >>> get_submission("20b78e0f32df805d21064fc912f40e9ae5ab260d") { 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' } """ if not isinstance(submission_uuid, six.string_types): if isinstance(submission_uuid, UUID): submission_uuid = six.text_type(submission_uuid) else: raise SubmissionRequestError( msg="submission_uuid ({!r}) must be serializable".format(submission_uuid) ) cache_key = Submission.get_cache_key(submission_uuid) try: cached_submission_data = cache.get(cache_key) except Exception: # The cache backend could raise an exception # (for example, memcache keys that contain spaces) logger.exception("Error occurred while retrieving submission from the cache") cached_submission_data = None if cached_submission_data: logger.info("Get submission {} (cached)".format(submission_uuid)) return cached_submission_data try: submission = _get_submission_model(submission_uuid, read_replica) submission_data = SubmissionSerializer(submission).data cache.set(cache_key, submission_data) except Submission.DoesNotExist: logger.error("Submission {} not found.".format(submission_uuid)) raise SubmissionNotFoundError( u"No submission matching uuid {}".format(submission_uuid) ) except Exception as exc: # Something very unexpected has just happened (like DB misconfig) err_msg = "Could not get submission due to error: {}".format(exc) logger.exception(err_msg) raise SubmissionInternalError(err_msg) logger.info("Get submission {}".format(submission_uuid)) return submission_data def get_submission_and_student(uuid, read_replica=False): """ Retrieve a submission by its unique identifier, including the associated student item. Args: uuid (str): the unique identifier of the submission. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: Serialized Submission model (dict) containing a serialized StudentItem model Raises: SubmissionNotFoundError: Raised if the submission does not exist. SubmissionRequestError: Raised if the search parameter is not a string. SubmissionInternalError: Raised for unknown errors. """ # This may raise API exceptions submission = get_submission(uuid, read_replica=read_replica) # Retrieve the student item from the cache cache_key = "submissions.student_item.{}".format(submission['student_item']) try: cached_student_item = cache.get(cache_key) except Exception: # The cache backend could raise an exception # (for example, memcache keys that contain spaces) logger.exception("Error occurred while retrieving student item from the cache") cached_student_item = None if cached_student_item is not None: submission['student_item'] = cached_student_item else: # There is probably a more idiomatic way to do this using the Django REST framework try: student_item_qs = StudentItem.objects if read_replica: student_item_qs = _use_read_replica(student_item_qs) student_item = student_item_qs.get(id=submission['student_item']) submission['student_item'] = StudentItemSerializer(student_item).data cache.set(cache_key, submission['student_item']) except Exception as ex: err_msg = "Could not get submission due to error: {}".format(ex) logger.exception(err_msg) raise SubmissionInternalError(err_msg) return submission def get_submissions(student_item_dict, limit=None): """Retrieves the submissions for the specified student item, ordered by most recent submitted date. Returns the submissions relative to the specified student item. Exception thrown if no submission is found relative to this location. Args: student_item_dict (dict): The location of the problem this submission is associated with, as defined by a course, student, and item. limit (int): Optional parameter for limiting the returned number of submissions associated with this student item. If not specified, all associated submissions are returned. Returns: List dict: A list of dicts for the associated student item. The submission contains five attributes: student_item, attempt_number, submitted_at, created_at, and answer. 'student_item' is the ID of the related student item for the submission. 'attempt_number' is the attempt this submission represents for this question. 'submitted_at' represents the time this submission was submitted, which can be configured, versus the 'created_at' date, which is when the submission is first created. Raises: SubmissionRequestError: Raised when the associated student item fails validation. SubmissionNotFoundError: Raised when a submission cannot be found for the associated student item. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> get_submissions(student_item_dict, 3) [{ 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' }] """ student_item_model = _get_or_create_student_item(student_item_dict) try: submission_models = Submission.objects.filter( student_item=student_item_model) except DatabaseError: error_message = ( u"Error getting submission request for student item {}" .format(student_item_dict) ) logger.exception(error_message) raise SubmissionNotFoundError(error_message) if limit: submission_models = submission_models[:limit] return SubmissionSerializer(submission_models, many=True).data def get_all_submissions(course_id, item_id, item_type, read_replica=True): """For the given item, get the most recent submission for every student who has submitted. This may return a very large result set! It is implemented as a generator for efficiency. Args: course_id, item_id, item_type (string): The values of the respective student_item fields to filter the submissions by. read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Yields: Dicts representing the submissions with the following fields: student_item student_id attempt_number submitted_at created_at answer Raises: Cannot fail unless there's a database error, but may return an empty iterable. """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) # We cannot use SELECT DISTINCT ON because it's PostgreSQL only, so unfortunately # our results will contain every entry of each student, not just the most recent. # We sort by student_id and primary key, so the reults will be grouped be grouped by # student, with the most recent submission being the first one in each group. query = submission_qs.select_related('student_item').filter( student_item__course_id=course_id, student_item__item_id=item_id, student_item__item_type=item_type, ).order_by('student_item__student_id', '-submitted_at', '-id').iterator() for unused_student_id, row_iter in itertools.groupby(query, operator.attrgetter('student_item.student_id')): submission = next(row_iter) data = SubmissionSerializer(submission).data data['student_id'] = submission.student_item.student_id yield data def get_all_course_submission_information(course_id, item_type, read_replica=True): """ For the given course, get all student items of the given item type, all the submissions for those itemes, and the latest scores for each item. If a submission was given a score that is not the latest score for the relevant student item, it will still be included but without score. Args: course_id (str): The course that we are getting submissions from. item_type (str): The type of items that we are getting submissions for. read_replica (bool): Try to use the database's read replica if it's available. Yields: A tuple of three dictionaries representing: (1) a student item with the following fields: student_id course_id student_item item_type (2) a submission with the following fields: student_item attempt_number submitted_at created_at answer (3) a score with the following fields, if one exists and it is the latest score: (if both conditions are not met, an empty dict is returned here) student_item submission points_earned points_possible created_at submission_uuid """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) query = submission_qs.select_related('student_item__scoresummary__latest__submission').filter( student_item__course_id=course_id, student_item__item_type=item_type, ).iterator() for submission in query: student_item = submission.student_item serialized_score = {} if hasattr(student_item, 'scoresummary'): latest_score = student_item.scoresummary.latest # Only include the score if it is not a reset score (is_hidden), and if the current submission is the same # as the student_item's latest score's submission. This matches the behavior of the API's get_score method. if (not latest_score.is_hidden()) and latest_score.submission.uuid == submission.uuid: serialized_score = ScoreSerializer(latest_score).data yield ( StudentItemSerializer(student_item).data, SubmissionSerializer(submission).data, serialized_score ) def get_top_submissions(course_id, item_id, item_type, number_of_top_scores, use_cache=True, read_replica=True): """Get a number of top scores for an assessment based on a particular student item This function will return top scores for the piece of assessment. It will consider only the latest and greater than 0 score for a piece of assessment. A score is only calculated for a student item if it has completed the workflow for a particular assessment module. In general, users of top submissions can tolerate some latency in the search results, so by default this call uses a cache and the read replica (if available). Args: course_id (str): The course to retrieve for the top scores item_id (str): The item within the course to retrieve for the top scores item_type (str): The type of item to retrieve number_of_top_scores (int): The number of scores to return, greater than 0 and no more than 100. Kwargs: use_cache (bool): If true, check the cache before retrieving querying the database. read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: topscores (dict): The top scores for the assessment for the student item. An empty array if there are no scores or all scores are 0. Raises: SubmissionNotFoundError: Raised when a submission cannot be found for the associated student item. SubmissionRequestError: Raised when the number of top scores is higher than the MAX_TOP_SUBMISSIONS constant. Examples: >>> course_id = "TestCourse" >>> item_id = "u_67" >>> item_type = "openassessment" >>> number_of_top_scores = 10 >>> >>> get_top_submissions(course_id, item_id, item_type, number_of_top_scores) [{ 'score': 20, 'content': "Platypus" },{ 'score': 16, 'content': "Frog" }] """ if number_of_top_scores < 1 or number_of_top_scores > MAX_TOP_SUBMISSIONS: error_msg = ( u"Number of top scores must be a number between 1 and {}.".format(MAX_TOP_SUBMISSIONS) ) logger.exception(error_msg) raise SubmissionRequestError(msg=error_msg) # First check the cache (unless caching is disabled) cache_key = "submissions.top_submissions.{course}.{item}.{type}.{number}".format( course=course_id, item=item_id, type=item_type, number=number_of_top_scores ) top_submissions = cache.get(cache_key) if use_cache else None # If we can't find it in the cache (or caching is disabled), check the database # By default, prefer the read-replica. if top_submissions is None: try: query = ScoreSummary.objects.filter( student_item__course_id=course_id, student_item__item_id=item_id, student_item__item_type=item_type, latest__points_earned__gt=0 ).select_related('latest', 'latest__submission').order_by("-latest__points_earned") if read_replica: query = _use_read_replica(query) score_summaries = query[:number_of_top_scores] except DatabaseError: msg = u"Could not fetch top score summaries for course {}, item {} of type {}".format( course_id, item_id, item_type ) logger.exception(msg) raise SubmissionInternalError(msg) # Retrieve the submission content for each top score top_submissions = [ { "score": score_summary.latest.points_earned, "content": SubmissionSerializer(score_summary.latest.submission).data['answer'] } for score_summary in score_summaries ] # Always store the retrieved list in the cache cache.set(cache_key, top_submissions, TOP_SUBMISSIONS_CACHE_TIMEOUT) return top_submissions def get_score(student_item): """Get the score for a particular student item Each student item should have a unique score. This function will return the score if it is available. A score is only calculated for a student item if it has completed the workflow for a particular assessment module. Args: student_item (dict): The dictionary representation of a student item. Function returns the score related to this student item. Returns: score (dict): The score associated with this student item. None if there is no score found. Raises: SubmissionInternalError: Raised if a score cannot be retrieved because of an internal server error. Examples: >>> student_item = { >>> "student_id":"Tim", >>> "course_id":"TestCourse", >>> "item_id":"u_67", >>> "item_type":"openassessment" >>> } >>> >>> get_score(student_item) [{ 'student_item': 2, 'submission': 2, 'points_earned': 8, 'points_possible': 20, 'created_at': datetime.datetime(2014, 2, 7, 18, 30, 1, 807911, tzinfo=<UTC>) }] """ try: student_item_model = StudentItem.objects.get(**student_item) score = ScoreSummary.objects.get(student_item=student_item_model).latest except (ScoreSummary.DoesNotExist, StudentItem.DoesNotExist): return None # By convention, scores are hidden if "points possible" is set to 0. # This can occur when an instructor has reset scores for a student. if score.is_hidden(): return None else: return ScoreSerializer(score).data def get_scores(course_id, student_id): """Return a dict mapping item_ids to scores. Scores are represented by serialized Score objects in JSON-like dict format. This method would be used by an LMS to find all the scores for a given student in a given course. Scores that are "hidden" (because they have points earned set to zero) are excluded from the results. Args: course_id (str): Course ID, used to do a lookup on the `StudentItem`. student_id (str): Student ID, used to do a lookup on the `StudentItem`. Returns: dict: The keys are `item_id`s (`str`) and the values are tuples of `(points_earned, points_possible)`. All points are integer values and represent the raw, unweighted scores. Submissions does not have any concept of weights. If there are no entries matching the `course_id` or `student_id`, we simply return an empty dictionary. This is not considered an error because there might be many queries for the progress page of a person who has never submitted anything. Raises: SubmissionInternalError: An unexpected error occurred while resetting scores. """ try: score_summaries = ScoreSummary.objects.filter( student_item__course_id=course_id, student_item__student_id=student_id, ).select_related('latest', 'latest__submission', 'student_item') except DatabaseError: msg = u"Could not fetch scores for course {}, student {}".format( course_id, student_id ) logger.exception(msg) raise SubmissionInternalError(msg) scores = { summary.student_item.item_id: UnannotatedScoreSerializer(summary.latest).data for summary in score_summaries if not summary.latest.is_hidden() } return scores def get_latest_score_for_submission(submission_uuid, read_replica=False): """ Retrieve the latest score for a particular submission. Args: submission_uuid (str): The UUID of the submission to retrieve. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: dict: The serialized score model, or None if no score is available. """ try: # Ensure that submission_uuid is valid before fetching score submission_model = _get_submission_model(submission_uuid, read_replica) score_qs = Score.objects.filter( submission__uuid=submission_model.uuid ).order_by("-id").select_related("submission") if read_replica: score_qs = _use_read_replica(score_qs) score = score_qs[0] if score.is_hidden(): return None except (IndexError, Submission.DoesNotExist): return None return ScoreSerializer(score).data def reset_score(student_id, course_id, item_id, clear_state=False, emit_signal=True): """ Reset scores for a specific student on a specific problem. Note: this does *not* delete `Score` models from the database, since these are immutable. It simply creates a new score with the "reset" flag set to True. Args: student_id (unicode): The ID of the student for whom to reset scores. course_id (unicode): The ID of the course containing the item to reset. item_id (unicode): The ID of the item for which to reset scores. clear_state (bool): If True, will appear to delete any submissions associated with the specified StudentItem Returns: None Raises: SubmissionInternalError: An unexpected error occurred while resetting scores. """ # Retrieve the student item try: student_item = StudentItem.objects.get( student_id=student_id, course_id=course_id, item_id=item_id ) except StudentItem.DoesNotExist: # If there is no student item, then there is no score to reset, # so we can return immediately. return # Create a "reset" score try: score = Score.create_reset_score(student_item) if emit_signal: # Send a signal out to any listeners who are waiting for scoring events. score_reset.send( sender=None, anonymous_user_id=student_id, course_id=course_id, item_id=item_id, created_at=score.created_at, ) if clear_state: for sub in student_item.submission_set.all(): # soft-delete the Submission sub.status = Submission.DELETED sub.save(update_fields=["status"]) # Also clear out cached values cache_key = Submission.get_cache_key(sub.uuid) cache.delete(cache_key) except DatabaseError: msg = ( u"Error occurred while reseting scores for" u" item {item_id} in course {course_id} for student {student_id}" ).format(item_id=item_id, course_id=course_id, student_id=student_id) logger.exception(msg) raise SubmissionInternalError(msg) else: msg = u"Score reset for item {item_id} in course {course_id} for student {student_id}".format( item_id=item_id, course_id=course_id, student_id=student_id ) logger.info(msg) def _log_submission(submission, student_item): """ Log the creation of a submission. Args: submission (dict): The serialized submission model. student_item (dict): The serialized student item model. Returns: None """ logger.info( u"Created submission uuid={submission_uuid} for " u"(course_id={course_id}, item_id={item_id}, " u"anonymous_student_id={anonymous_student_id})" .format( submission_uuid=submission["uuid"], course_id=student_item["course_id"], item_id=student_item["item_id"], anonymous_student_id=student_item["student_id"] ) ) def _log_score(score): """ Log the creation of a score. Args: score (Score): The score model. Returns: None """ logger.info( "Score of ({}/{}) set for submission {}" .format(score.points_earned, score.points_possible, score.submission.uuid) ) def _get_or_create_student_item(student_item_dict): """Gets or creates a Student Item that matches the values specified. Attempts to get the specified Student Item. If it does not exist, the specified parameters are validated, and a new Student Item is created. Args: student_item_dict (dict): The dict containing the student_id, item_id, course_id, and item_type that uniquely defines a student item. Returns: StudentItem: The student item that was retrieved or created. Raises: SubmissionInternalError: Thrown if there was an internal error while attempting to create or retrieve the specified student item. SubmissionRequestError: Thrown if the given student item parameters fail validation. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> _get_or_create_student_item(student_item_dict) {'item_id': 'item_1', 'item_type': 'type_one', 'course_id': 'course_1', 'student_id': 'Tim'} """ try: try: return StudentItem.objects.get(**student_item_dict) except StudentItem.DoesNotExist: student_item_serializer = StudentItemSerializer( data=student_item_dict ) if not student_item_serializer.is_valid(): logger.error( u"Invalid StudentItemSerializer: errors:{} data:{}".format( student_item_serializer.errors, student_item_dict ) ) raise SubmissionRequestError(field_errors=student_item_serializer.errors) return student_item_serializer.save() except DatabaseError: error_message = u"An error occurred creating student item: {}".format( student_item_dict ) logger.exception(error_message) raise SubmissionInternalError(error_message) def _use_read_replica(queryset): """ Use the read replica if it's available. Args: queryset (QuerySet) Returns: QuerySet """ return ( queryset.using("read_replica") if "read_replica" in settings.DATABASES else queryset )
edx/edx-submissions
submissions/api.py
_log_submission
python
def _log_submission(submission, student_item): logger.info( u"Created submission uuid={submission_uuid} for " u"(course_id={course_id}, item_id={item_id}, " u"anonymous_student_id={anonymous_student_id})" .format( submission_uuid=submission["uuid"], course_id=student_item["course_id"], item_id=student_item["item_id"], anonymous_student_id=student_item["student_id"] ) )
Log the creation of a submission. Args: submission (dict): The serialized submission model. student_item (dict): The serialized student item model. Returns: None
train
https://github.com/edx/edx-submissions/blob/8d531ca25f7c2886dfcb1bb8febe0910e1433ca2/submissions/api.py#L923-L944
null
""" Public interface for the submissions app. """ from __future__ import absolute_import import copy import itertools import logging import operator import json from uuid import UUID from django.conf import settings from django.core.cache import cache from django.db import IntegrityError, DatabaseError from submissions.serializers import ( SubmissionSerializer, StudentItemSerializer, ScoreSerializer, UnannotatedScoreSerializer ) from submissions.models import Submission, StudentItem, Score, ScoreSummary, ScoreAnnotation, score_set, score_reset import six logger = logging.getLogger("submissions.api") # By default, limit the number of top submissions # Anything above this limit will result in a request error MAX_TOP_SUBMISSIONS = 100 # Set a relatively low cache timeout for top submissions. TOP_SUBMISSIONS_CACHE_TIMEOUT = 300 class SubmissionError(Exception): """An error that occurs during submission actions. This error is raised when the submission API cannot perform a requested action. """ pass class SubmissionInternalError(SubmissionError): """An error internal to the Submission API has occurred. This error is raised when an error occurs that is not caused by incorrect use of the API, but rather internal implementation of the underlying services. """ pass class SubmissionNotFoundError(SubmissionError): """This error is raised when no submission is found for the request. If a state is specified in a call to the API that results in no matching Submissions, this error may be raised. """ pass class SubmissionRequestError(SubmissionError): """This error is raised when there was a request-specific error This error is reserved for problems specific to the use of the API. """ def __init__(self, msg="", field_errors=None): """ Configure the submission request error. Keyword Args: msg (unicode): The error message. field_errors (dict): A dictionary of errors (list of unicode) specific to a fields provided in the request. Example usage: >>> raise SubmissionRequestError( >>> "An unexpected error occurred" >>> {"answer": ["Maximum answer length exceeded."]} >>> ) """ super(SubmissionRequestError, self).__init__(msg) self.field_errors = ( copy.deepcopy(field_errors) if field_errors is not None else {} ) self.args += (self.field_errors,) def __repr__(self): """ Show the field errors upon output. """ return '{}(msg="{}", field_errors={})'.format( self.__class__.__name__, self.message, self.field_errors ) def create_submission(student_item_dict, answer, submitted_at=None, attempt_number=None): """Creates a submission for assessment. Generic means by which to submit an answer for assessment. Args: student_item_dict (dict): The student_item this submission is associated with. This is used to determine which course, student, and location this submission belongs to. answer (JSON-serializable): The answer given by the student to be assessed. submitted_at (datetime): The date in which this submission was submitted. If not specified, defaults to the current date. attempt_number (int): A student may be able to submit multiple attempts per question. This allows the designated attempt to be overridden. If the attempt is not specified, it will take the most recent submission, as specified by the submitted_at time, and use its attempt_number plus one. Returns: dict: A representation of the created Submission. The submission contains five attributes: student_item, attempt_number, submitted_at, created_at, and answer. 'student_item' is the ID of the related student item for the submission. 'attempt_number' is the attempt this submission represents for this question. 'submitted_at' represents the time this submission was submitted, which can be configured, versus the 'created_at' date, which is when the submission is first created. Raises: SubmissionRequestError: Raised when there are validation errors for the student item or submission. This can be caused by the student item missing required values, the submission being too long, the attempt_number is negative, or the given submitted_at time is invalid. SubmissionInternalError: Raised when submission access causes an internal error. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> create_submission(student_item_dict, "The answer is 42.", datetime.utcnow, 1) { 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 649284 tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' } """ student_item_model = _get_or_create_student_item(student_item_dict) if attempt_number is None: try: submissions = Submission.objects.filter( student_item=student_item_model)[:1] except DatabaseError: error_message = u"An error occurred while filtering submissions for student item: {}".format( student_item_dict) logger.exception(error_message) raise SubmissionInternalError(error_message) attempt_number = submissions[0].attempt_number + 1 if submissions else 1 model_kwargs = { "student_item": student_item_model.pk, "answer": answer, "attempt_number": attempt_number, } if submitted_at: model_kwargs["submitted_at"] = submitted_at try: submission_serializer = SubmissionSerializer(data=model_kwargs) if not submission_serializer.is_valid(): raise SubmissionRequestError(field_errors=submission_serializer.errors) submission_serializer.save() sub_data = submission_serializer.data _log_submission(sub_data, student_item_dict) return sub_data except DatabaseError: error_message = u"An error occurred while creating submission {} for student item: {}".format( model_kwargs, student_item_dict ) logger.exception(error_message) raise SubmissionInternalError(error_message) def _get_submission_model(uuid, read_replica=False): """ Helper to retrieve a given Submission object from the database. Helper is needed to centralize logic that fixes EDUCATOR-1090, because uuids are stored both with and without hyphens. """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) try: submission = submission_qs.get(uuid=uuid) except Submission.DoesNotExist: try: hyphenated_value = six.text_type(UUID(uuid)) query = """ SELECT `submissions_submission`.`id`, `submissions_submission`.`uuid`, `submissions_submission`.`student_item_id`, `submissions_submission`.`attempt_number`, `submissions_submission`.`submitted_at`, `submissions_submission`.`created_at`, `submissions_submission`.`raw_answer`, `submissions_submission`.`status` FROM `submissions_submission` WHERE ( NOT (`submissions_submission`.`status` = 'D') AND `submissions_submission`.`uuid` = '{}' ) """ query = query.replace("{}", hyphenated_value) # We can use Submission.objects instead of the SoftDeletedManager, we'll include that logic manually submission = Submission.objects.raw(query)[0] except IndexError: raise Submission.DoesNotExist() # Avoid the extra hit next time submission.save(update_fields=['uuid']) return submission def get_submission(submission_uuid, read_replica=False): """Retrieves a single submission by uuid. Args: submission_uuid (str): Identifier for the submission. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Raises: SubmissionNotFoundError: Raised if the submission does not exist. SubmissionRequestError: Raised if the search parameter is not a string. SubmissionInternalError: Raised for unknown errors. Examples: >>> get_submission("20b78e0f32df805d21064fc912f40e9ae5ab260d") { 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' } """ if not isinstance(submission_uuid, six.string_types): if isinstance(submission_uuid, UUID): submission_uuid = six.text_type(submission_uuid) else: raise SubmissionRequestError( msg="submission_uuid ({!r}) must be serializable".format(submission_uuid) ) cache_key = Submission.get_cache_key(submission_uuid) try: cached_submission_data = cache.get(cache_key) except Exception: # The cache backend could raise an exception # (for example, memcache keys that contain spaces) logger.exception("Error occurred while retrieving submission from the cache") cached_submission_data = None if cached_submission_data: logger.info("Get submission {} (cached)".format(submission_uuid)) return cached_submission_data try: submission = _get_submission_model(submission_uuid, read_replica) submission_data = SubmissionSerializer(submission).data cache.set(cache_key, submission_data) except Submission.DoesNotExist: logger.error("Submission {} not found.".format(submission_uuid)) raise SubmissionNotFoundError( u"No submission matching uuid {}".format(submission_uuid) ) except Exception as exc: # Something very unexpected has just happened (like DB misconfig) err_msg = "Could not get submission due to error: {}".format(exc) logger.exception(err_msg) raise SubmissionInternalError(err_msg) logger.info("Get submission {}".format(submission_uuid)) return submission_data def get_submission_and_student(uuid, read_replica=False): """ Retrieve a submission by its unique identifier, including the associated student item. Args: uuid (str): the unique identifier of the submission. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: Serialized Submission model (dict) containing a serialized StudentItem model Raises: SubmissionNotFoundError: Raised if the submission does not exist. SubmissionRequestError: Raised if the search parameter is not a string. SubmissionInternalError: Raised for unknown errors. """ # This may raise API exceptions submission = get_submission(uuid, read_replica=read_replica) # Retrieve the student item from the cache cache_key = "submissions.student_item.{}".format(submission['student_item']) try: cached_student_item = cache.get(cache_key) except Exception: # The cache backend could raise an exception # (for example, memcache keys that contain spaces) logger.exception("Error occurred while retrieving student item from the cache") cached_student_item = None if cached_student_item is not None: submission['student_item'] = cached_student_item else: # There is probably a more idiomatic way to do this using the Django REST framework try: student_item_qs = StudentItem.objects if read_replica: student_item_qs = _use_read_replica(student_item_qs) student_item = student_item_qs.get(id=submission['student_item']) submission['student_item'] = StudentItemSerializer(student_item).data cache.set(cache_key, submission['student_item']) except Exception as ex: err_msg = "Could not get submission due to error: {}".format(ex) logger.exception(err_msg) raise SubmissionInternalError(err_msg) return submission def get_submissions(student_item_dict, limit=None): """Retrieves the submissions for the specified student item, ordered by most recent submitted date. Returns the submissions relative to the specified student item. Exception thrown if no submission is found relative to this location. Args: student_item_dict (dict): The location of the problem this submission is associated with, as defined by a course, student, and item. limit (int): Optional parameter for limiting the returned number of submissions associated with this student item. If not specified, all associated submissions are returned. Returns: List dict: A list of dicts for the associated student item. The submission contains five attributes: student_item, attempt_number, submitted_at, created_at, and answer. 'student_item' is the ID of the related student item for the submission. 'attempt_number' is the attempt this submission represents for this question. 'submitted_at' represents the time this submission was submitted, which can be configured, versus the 'created_at' date, which is when the submission is first created. Raises: SubmissionRequestError: Raised when the associated student item fails validation. SubmissionNotFoundError: Raised when a submission cannot be found for the associated student item. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> get_submissions(student_item_dict, 3) [{ 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' }] """ student_item_model = _get_or_create_student_item(student_item_dict) try: submission_models = Submission.objects.filter( student_item=student_item_model) except DatabaseError: error_message = ( u"Error getting submission request for student item {}" .format(student_item_dict) ) logger.exception(error_message) raise SubmissionNotFoundError(error_message) if limit: submission_models = submission_models[:limit] return SubmissionSerializer(submission_models, many=True).data def get_all_submissions(course_id, item_id, item_type, read_replica=True): """For the given item, get the most recent submission for every student who has submitted. This may return a very large result set! It is implemented as a generator for efficiency. Args: course_id, item_id, item_type (string): The values of the respective student_item fields to filter the submissions by. read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Yields: Dicts representing the submissions with the following fields: student_item student_id attempt_number submitted_at created_at answer Raises: Cannot fail unless there's a database error, but may return an empty iterable. """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) # We cannot use SELECT DISTINCT ON because it's PostgreSQL only, so unfortunately # our results will contain every entry of each student, not just the most recent. # We sort by student_id and primary key, so the reults will be grouped be grouped by # student, with the most recent submission being the first one in each group. query = submission_qs.select_related('student_item').filter( student_item__course_id=course_id, student_item__item_id=item_id, student_item__item_type=item_type, ).order_by('student_item__student_id', '-submitted_at', '-id').iterator() for unused_student_id, row_iter in itertools.groupby(query, operator.attrgetter('student_item.student_id')): submission = next(row_iter) data = SubmissionSerializer(submission).data data['student_id'] = submission.student_item.student_id yield data def get_all_course_submission_information(course_id, item_type, read_replica=True): """ For the given course, get all student items of the given item type, all the submissions for those itemes, and the latest scores for each item. If a submission was given a score that is not the latest score for the relevant student item, it will still be included but without score. Args: course_id (str): The course that we are getting submissions from. item_type (str): The type of items that we are getting submissions for. read_replica (bool): Try to use the database's read replica if it's available. Yields: A tuple of three dictionaries representing: (1) a student item with the following fields: student_id course_id student_item item_type (2) a submission with the following fields: student_item attempt_number submitted_at created_at answer (3) a score with the following fields, if one exists and it is the latest score: (if both conditions are not met, an empty dict is returned here) student_item submission points_earned points_possible created_at submission_uuid """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) query = submission_qs.select_related('student_item__scoresummary__latest__submission').filter( student_item__course_id=course_id, student_item__item_type=item_type, ).iterator() for submission in query: student_item = submission.student_item serialized_score = {} if hasattr(student_item, 'scoresummary'): latest_score = student_item.scoresummary.latest # Only include the score if it is not a reset score (is_hidden), and if the current submission is the same # as the student_item's latest score's submission. This matches the behavior of the API's get_score method. if (not latest_score.is_hidden()) and latest_score.submission.uuid == submission.uuid: serialized_score = ScoreSerializer(latest_score).data yield ( StudentItemSerializer(student_item).data, SubmissionSerializer(submission).data, serialized_score ) def get_top_submissions(course_id, item_id, item_type, number_of_top_scores, use_cache=True, read_replica=True): """Get a number of top scores for an assessment based on a particular student item This function will return top scores for the piece of assessment. It will consider only the latest and greater than 0 score for a piece of assessment. A score is only calculated for a student item if it has completed the workflow for a particular assessment module. In general, users of top submissions can tolerate some latency in the search results, so by default this call uses a cache and the read replica (if available). Args: course_id (str): The course to retrieve for the top scores item_id (str): The item within the course to retrieve for the top scores item_type (str): The type of item to retrieve number_of_top_scores (int): The number of scores to return, greater than 0 and no more than 100. Kwargs: use_cache (bool): If true, check the cache before retrieving querying the database. read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: topscores (dict): The top scores for the assessment for the student item. An empty array if there are no scores or all scores are 0. Raises: SubmissionNotFoundError: Raised when a submission cannot be found for the associated student item. SubmissionRequestError: Raised when the number of top scores is higher than the MAX_TOP_SUBMISSIONS constant. Examples: >>> course_id = "TestCourse" >>> item_id = "u_67" >>> item_type = "openassessment" >>> number_of_top_scores = 10 >>> >>> get_top_submissions(course_id, item_id, item_type, number_of_top_scores) [{ 'score': 20, 'content': "Platypus" },{ 'score': 16, 'content': "Frog" }] """ if number_of_top_scores < 1 or number_of_top_scores > MAX_TOP_SUBMISSIONS: error_msg = ( u"Number of top scores must be a number between 1 and {}.".format(MAX_TOP_SUBMISSIONS) ) logger.exception(error_msg) raise SubmissionRequestError(msg=error_msg) # First check the cache (unless caching is disabled) cache_key = "submissions.top_submissions.{course}.{item}.{type}.{number}".format( course=course_id, item=item_id, type=item_type, number=number_of_top_scores ) top_submissions = cache.get(cache_key) if use_cache else None # If we can't find it in the cache (or caching is disabled), check the database # By default, prefer the read-replica. if top_submissions is None: try: query = ScoreSummary.objects.filter( student_item__course_id=course_id, student_item__item_id=item_id, student_item__item_type=item_type, latest__points_earned__gt=0 ).select_related('latest', 'latest__submission').order_by("-latest__points_earned") if read_replica: query = _use_read_replica(query) score_summaries = query[:number_of_top_scores] except DatabaseError: msg = u"Could not fetch top score summaries for course {}, item {} of type {}".format( course_id, item_id, item_type ) logger.exception(msg) raise SubmissionInternalError(msg) # Retrieve the submission content for each top score top_submissions = [ { "score": score_summary.latest.points_earned, "content": SubmissionSerializer(score_summary.latest.submission).data['answer'] } for score_summary in score_summaries ] # Always store the retrieved list in the cache cache.set(cache_key, top_submissions, TOP_SUBMISSIONS_CACHE_TIMEOUT) return top_submissions def get_score(student_item): """Get the score for a particular student item Each student item should have a unique score. This function will return the score if it is available. A score is only calculated for a student item if it has completed the workflow for a particular assessment module. Args: student_item (dict): The dictionary representation of a student item. Function returns the score related to this student item. Returns: score (dict): The score associated with this student item. None if there is no score found. Raises: SubmissionInternalError: Raised if a score cannot be retrieved because of an internal server error. Examples: >>> student_item = { >>> "student_id":"Tim", >>> "course_id":"TestCourse", >>> "item_id":"u_67", >>> "item_type":"openassessment" >>> } >>> >>> get_score(student_item) [{ 'student_item': 2, 'submission': 2, 'points_earned': 8, 'points_possible': 20, 'created_at': datetime.datetime(2014, 2, 7, 18, 30, 1, 807911, tzinfo=<UTC>) }] """ try: student_item_model = StudentItem.objects.get(**student_item) score = ScoreSummary.objects.get(student_item=student_item_model).latest except (ScoreSummary.DoesNotExist, StudentItem.DoesNotExist): return None # By convention, scores are hidden if "points possible" is set to 0. # This can occur when an instructor has reset scores for a student. if score.is_hidden(): return None else: return ScoreSerializer(score).data def get_scores(course_id, student_id): """Return a dict mapping item_ids to scores. Scores are represented by serialized Score objects in JSON-like dict format. This method would be used by an LMS to find all the scores for a given student in a given course. Scores that are "hidden" (because they have points earned set to zero) are excluded from the results. Args: course_id (str): Course ID, used to do a lookup on the `StudentItem`. student_id (str): Student ID, used to do a lookup on the `StudentItem`. Returns: dict: The keys are `item_id`s (`str`) and the values are tuples of `(points_earned, points_possible)`. All points are integer values and represent the raw, unweighted scores. Submissions does not have any concept of weights. If there are no entries matching the `course_id` or `student_id`, we simply return an empty dictionary. This is not considered an error because there might be many queries for the progress page of a person who has never submitted anything. Raises: SubmissionInternalError: An unexpected error occurred while resetting scores. """ try: score_summaries = ScoreSummary.objects.filter( student_item__course_id=course_id, student_item__student_id=student_id, ).select_related('latest', 'latest__submission', 'student_item') except DatabaseError: msg = u"Could not fetch scores for course {}, student {}".format( course_id, student_id ) logger.exception(msg) raise SubmissionInternalError(msg) scores = { summary.student_item.item_id: UnannotatedScoreSerializer(summary.latest).data for summary in score_summaries if not summary.latest.is_hidden() } return scores def get_latest_score_for_submission(submission_uuid, read_replica=False): """ Retrieve the latest score for a particular submission. Args: submission_uuid (str): The UUID of the submission to retrieve. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: dict: The serialized score model, or None if no score is available. """ try: # Ensure that submission_uuid is valid before fetching score submission_model = _get_submission_model(submission_uuid, read_replica) score_qs = Score.objects.filter( submission__uuid=submission_model.uuid ).order_by("-id").select_related("submission") if read_replica: score_qs = _use_read_replica(score_qs) score = score_qs[0] if score.is_hidden(): return None except (IndexError, Submission.DoesNotExist): return None return ScoreSerializer(score).data def reset_score(student_id, course_id, item_id, clear_state=False, emit_signal=True): """ Reset scores for a specific student on a specific problem. Note: this does *not* delete `Score` models from the database, since these are immutable. It simply creates a new score with the "reset" flag set to True. Args: student_id (unicode): The ID of the student for whom to reset scores. course_id (unicode): The ID of the course containing the item to reset. item_id (unicode): The ID of the item for which to reset scores. clear_state (bool): If True, will appear to delete any submissions associated with the specified StudentItem Returns: None Raises: SubmissionInternalError: An unexpected error occurred while resetting scores. """ # Retrieve the student item try: student_item = StudentItem.objects.get( student_id=student_id, course_id=course_id, item_id=item_id ) except StudentItem.DoesNotExist: # If there is no student item, then there is no score to reset, # so we can return immediately. return # Create a "reset" score try: score = Score.create_reset_score(student_item) if emit_signal: # Send a signal out to any listeners who are waiting for scoring events. score_reset.send( sender=None, anonymous_user_id=student_id, course_id=course_id, item_id=item_id, created_at=score.created_at, ) if clear_state: for sub in student_item.submission_set.all(): # soft-delete the Submission sub.status = Submission.DELETED sub.save(update_fields=["status"]) # Also clear out cached values cache_key = Submission.get_cache_key(sub.uuid) cache.delete(cache_key) except DatabaseError: msg = ( u"Error occurred while reseting scores for" u" item {item_id} in course {course_id} for student {student_id}" ).format(item_id=item_id, course_id=course_id, student_id=student_id) logger.exception(msg) raise SubmissionInternalError(msg) else: msg = u"Score reset for item {item_id} in course {course_id} for student {student_id}".format( item_id=item_id, course_id=course_id, student_id=student_id ) logger.info(msg) def set_score(submission_uuid, points_earned, points_possible, annotation_creator=None, annotation_type=None, annotation_reason=None): """Set a score for a particular submission. Sets the score for a particular submission. This score is calculated externally to the API. Args: submission_uuid (str): UUID for the submission (must exist). points_earned (int): The earned points for this submission. points_possible (int): The total points possible for this particular student item. annotation_creator (str): An optional field for recording who gave this particular score annotation_type (str): An optional field for recording what type of annotation should be created, e.g. "staff_override". annotation_reason (str): An optional field for recording why this score was set to its value. Returns: None Raises: SubmissionInternalError: Thrown if there was an internal error while attempting to save the score. SubmissionRequestError: Thrown if the given student item or submission are not found. Examples: >>> set_score("a778b933-9fb3-11e3-9c0f-040ccee02800", 11, 12) { 'student_item': 2, 'submission': 1, 'points_earned': 11, 'points_possible': 12, 'created_at': datetime.datetime(2014, 2, 7, 20, 6, 42, 331156, tzinfo=<UTC>) } """ try: submission_model = _get_submission_model(submission_uuid) except Submission.DoesNotExist: raise SubmissionNotFoundError( u"No submission matching uuid {}".format(submission_uuid) ) except DatabaseError: error_msg = u"Could not retrieve submission {}.".format( submission_uuid ) logger.exception(error_msg) raise SubmissionRequestError(msg=error_msg) score = ScoreSerializer( data={ "student_item": submission_model.student_item.pk, "submission": submission_model.pk, "points_earned": points_earned, "points_possible": points_possible, } ) if not score.is_valid(): logger.exception(score.errors) raise SubmissionInternalError(score.errors) # When we save the score, a score summary will be created if # it does not already exist. # When the database's isolation level is set to repeatable-read, # it's possible for a score summary to exist for this student item, # even though we cannot retrieve it. # In this case, we assume that someone else has already created # a score summary and ignore the error. # TODO: once we're using Django 1.8, use transactions to ensure that these # two models are saved at the same time. try: score_model = score.save() _log_score(score_model) if annotation_creator is not None: score_annotation = ScoreAnnotation( score=score_model, creator=annotation_creator, annotation_type=annotation_type, reason=annotation_reason ) score_annotation.save() # Send a signal out to any listeners who are waiting for scoring events. score_set.send( sender=None, points_possible=points_possible, points_earned=points_earned, anonymous_user_id=submission_model.student_item.student_id, course_id=submission_model.student_item.course_id, item_id=submission_model.student_item.item_id, created_at=score_model.created_at, ) except IntegrityError: pass def _log_score(score): """ Log the creation of a score. Args: score (Score): The score model. Returns: None """ logger.info( "Score of ({}/{}) set for submission {}" .format(score.points_earned, score.points_possible, score.submission.uuid) ) def _get_or_create_student_item(student_item_dict): """Gets or creates a Student Item that matches the values specified. Attempts to get the specified Student Item. If it does not exist, the specified parameters are validated, and a new Student Item is created. Args: student_item_dict (dict): The dict containing the student_id, item_id, course_id, and item_type that uniquely defines a student item. Returns: StudentItem: The student item that was retrieved or created. Raises: SubmissionInternalError: Thrown if there was an internal error while attempting to create or retrieve the specified student item. SubmissionRequestError: Thrown if the given student item parameters fail validation. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> _get_or_create_student_item(student_item_dict) {'item_id': 'item_1', 'item_type': 'type_one', 'course_id': 'course_1', 'student_id': 'Tim'} """ try: try: return StudentItem.objects.get(**student_item_dict) except StudentItem.DoesNotExist: student_item_serializer = StudentItemSerializer( data=student_item_dict ) if not student_item_serializer.is_valid(): logger.error( u"Invalid StudentItemSerializer: errors:{} data:{}".format( student_item_serializer.errors, student_item_dict ) ) raise SubmissionRequestError(field_errors=student_item_serializer.errors) return student_item_serializer.save() except DatabaseError: error_message = u"An error occurred creating student item: {}".format( student_item_dict ) logger.exception(error_message) raise SubmissionInternalError(error_message) def _use_read_replica(queryset): """ Use the read replica if it's available. Args: queryset (QuerySet) Returns: QuerySet """ return ( queryset.using("read_replica") if "read_replica" in settings.DATABASES else queryset )
edx/edx-submissions
submissions/api.py
_log_score
python
def _log_score(score): logger.info( "Score of ({}/{}) set for submission {}" .format(score.points_earned, score.points_possible, score.submission.uuid) )
Log the creation of a score. Args: score (Score): The score model. Returns: None
train
https://github.com/edx/edx-submissions/blob/8d531ca25f7c2886dfcb1bb8febe0910e1433ca2/submissions/api.py#L947-L960
null
""" Public interface for the submissions app. """ from __future__ import absolute_import import copy import itertools import logging import operator import json from uuid import UUID from django.conf import settings from django.core.cache import cache from django.db import IntegrityError, DatabaseError from submissions.serializers import ( SubmissionSerializer, StudentItemSerializer, ScoreSerializer, UnannotatedScoreSerializer ) from submissions.models import Submission, StudentItem, Score, ScoreSummary, ScoreAnnotation, score_set, score_reset import six logger = logging.getLogger("submissions.api") # By default, limit the number of top submissions # Anything above this limit will result in a request error MAX_TOP_SUBMISSIONS = 100 # Set a relatively low cache timeout for top submissions. TOP_SUBMISSIONS_CACHE_TIMEOUT = 300 class SubmissionError(Exception): """An error that occurs during submission actions. This error is raised when the submission API cannot perform a requested action. """ pass class SubmissionInternalError(SubmissionError): """An error internal to the Submission API has occurred. This error is raised when an error occurs that is not caused by incorrect use of the API, but rather internal implementation of the underlying services. """ pass class SubmissionNotFoundError(SubmissionError): """This error is raised when no submission is found for the request. If a state is specified in a call to the API that results in no matching Submissions, this error may be raised. """ pass class SubmissionRequestError(SubmissionError): """This error is raised when there was a request-specific error This error is reserved for problems specific to the use of the API. """ def __init__(self, msg="", field_errors=None): """ Configure the submission request error. Keyword Args: msg (unicode): The error message. field_errors (dict): A dictionary of errors (list of unicode) specific to a fields provided in the request. Example usage: >>> raise SubmissionRequestError( >>> "An unexpected error occurred" >>> {"answer": ["Maximum answer length exceeded."]} >>> ) """ super(SubmissionRequestError, self).__init__(msg) self.field_errors = ( copy.deepcopy(field_errors) if field_errors is not None else {} ) self.args += (self.field_errors,) def __repr__(self): """ Show the field errors upon output. """ return '{}(msg="{}", field_errors={})'.format( self.__class__.__name__, self.message, self.field_errors ) def create_submission(student_item_dict, answer, submitted_at=None, attempt_number=None): """Creates a submission for assessment. Generic means by which to submit an answer for assessment. Args: student_item_dict (dict): The student_item this submission is associated with. This is used to determine which course, student, and location this submission belongs to. answer (JSON-serializable): The answer given by the student to be assessed. submitted_at (datetime): The date in which this submission was submitted. If not specified, defaults to the current date. attempt_number (int): A student may be able to submit multiple attempts per question. This allows the designated attempt to be overridden. If the attempt is not specified, it will take the most recent submission, as specified by the submitted_at time, and use its attempt_number plus one. Returns: dict: A representation of the created Submission. The submission contains five attributes: student_item, attempt_number, submitted_at, created_at, and answer. 'student_item' is the ID of the related student item for the submission. 'attempt_number' is the attempt this submission represents for this question. 'submitted_at' represents the time this submission was submitted, which can be configured, versus the 'created_at' date, which is when the submission is first created. Raises: SubmissionRequestError: Raised when there are validation errors for the student item or submission. This can be caused by the student item missing required values, the submission being too long, the attempt_number is negative, or the given submitted_at time is invalid. SubmissionInternalError: Raised when submission access causes an internal error. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> create_submission(student_item_dict, "The answer is 42.", datetime.utcnow, 1) { 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 649284 tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' } """ student_item_model = _get_or_create_student_item(student_item_dict) if attempt_number is None: try: submissions = Submission.objects.filter( student_item=student_item_model)[:1] except DatabaseError: error_message = u"An error occurred while filtering submissions for student item: {}".format( student_item_dict) logger.exception(error_message) raise SubmissionInternalError(error_message) attempt_number = submissions[0].attempt_number + 1 if submissions else 1 model_kwargs = { "student_item": student_item_model.pk, "answer": answer, "attempt_number": attempt_number, } if submitted_at: model_kwargs["submitted_at"] = submitted_at try: submission_serializer = SubmissionSerializer(data=model_kwargs) if not submission_serializer.is_valid(): raise SubmissionRequestError(field_errors=submission_serializer.errors) submission_serializer.save() sub_data = submission_serializer.data _log_submission(sub_data, student_item_dict) return sub_data except DatabaseError: error_message = u"An error occurred while creating submission {} for student item: {}".format( model_kwargs, student_item_dict ) logger.exception(error_message) raise SubmissionInternalError(error_message) def _get_submission_model(uuid, read_replica=False): """ Helper to retrieve a given Submission object from the database. Helper is needed to centralize logic that fixes EDUCATOR-1090, because uuids are stored both with and without hyphens. """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) try: submission = submission_qs.get(uuid=uuid) except Submission.DoesNotExist: try: hyphenated_value = six.text_type(UUID(uuid)) query = """ SELECT `submissions_submission`.`id`, `submissions_submission`.`uuid`, `submissions_submission`.`student_item_id`, `submissions_submission`.`attempt_number`, `submissions_submission`.`submitted_at`, `submissions_submission`.`created_at`, `submissions_submission`.`raw_answer`, `submissions_submission`.`status` FROM `submissions_submission` WHERE ( NOT (`submissions_submission`.`status` = 'D') AND `submissions_submission`.`uuid` = '{}' ) """ query = query.replace("{}", hyphenated_value) # We can use Submission.objects instead of the SoftDeletedManager, we'll include that logic manually submission = Submission.objects.raw(query)[0] except IndexError: raise Submission.DoesNotExist() # Avoid the extra hit next time submission.save(update_fields=['uuid']) return submission def get_submission(submission_uuid, read_replica=False): """Retrieves a single submission by uuid. Args: submission_uuid (str): Identifier for the submission. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Raises: SubmissionNotFoundError: Raised if the submission does not exist. SubmissionRequestError: Raised if the search parameter is not a string. SubmissionInternalError: Raised for unknown errors. Examples: >>> get_submission("20b78e0f32df805d21064fc912f40e9ae5ab260d") { 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' } """ if not isinstance(submission_uuid, six.string_types): if isinstance(submission_uuid, UUID): submission_uuid = six.text_type(submission_uuid) else: raise SubmissionRequestError( msg="submission_uuid ({!r}) must be serializable".format(submission_uuid) ) cache_key = Submission.get_cache_key(submission_uuid) try: cached_submission_data = cache.get(cache_key) except Exception: # The cache backend could raise an exception # (for example, memcache keys that contain spaces) logger.exception("Error occurred while retrieving submission from the cache") cached_submission_data = None if cached_submission_data: logger.info("Get submission {} (cached)".format(submission_uuid)) return cached_submission_data try: submission = _get_submission_model(submission_uuid, read_replica) submission_data = SubmissionSerializer(submission).data cache.set(cache_key, submission_data) except Submission.DoesNotExist: logger.error("Submission {} not found.".format(submission_uuid)) raise SubmissionNotFoundError( u"No submission matching uuid {}".format(submission_uuid) ) except Exception as exc: # Something very unexpected has just happened (like DB misconfig) err_msg = "Could not get submission due to error: {}".format(exc) logger.exception(err_msg) raise SubmissionInternalError(err_msg) logger.info("Get submission {}".format(submission_uuid)) return submission_data def get_submission_and_student(uuid, read_replica=False): """ Retrieve a submission by its unique identifier, including the associated student item. Args: uuid (str): the unique identifier of the submission. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: Serialized Submission model (dict) containing a serialized StudentItem model Raises: SubmissionNotFoundError: Raised if the submission does not exist. SubmissionRequestError: Raised if the search parameter is not a string. SubmissionInternalError: Raised for unknown errors. """ # This may raise API exceptions submission = get_submission(uuid, read_replica=read_replica) # Retrieve the student item from the cache cache_key = "submissions.student_item.{}".format(submission['student_item']) try: cached_student_item = cache.get(cache_key) except Exception: # The cache backend could raise an exception # (for example, memcache keys that contain spaces) logger.exception("Error occurred while retrieving student item from the cache") cached_student_item = None if cached_student_item is not None: submission['student_item'] = cached_student_item else: # There is probably a more idiomatic way to do this using the Django REST framework try: student_item_qs = StudentItem.objects if read_replica: student_item_qs = _use_read_replica(student_item_qs) student_item = student_item_qs.get(id=submission['student_item']) submission['student_item'] = StudentItemSerializer(student_item).data cache.set(cache_key, submission['student_item']) except Exception as ex: err_msg = "Could not get submission due to error: {}".format(ex) logger.exception(err_msg) raise SubmissionInternalError(err_msg) return submission def get_submissions(student_item_dict, limit=None): """Retrieves the submissions for the specified student item, ordered by most recent submitted date. Returns the submissions relative to the specified student item. Exception thrown if no submission is found relative to this location. Args: student_item_dict (dict): The location of the problem this submission is associated with, as defined by a course, student, and item. limit (int): Optional parameter for limiting the returned number of submissions associated with this student item. If not specified, all associated submissions are returned. Returns: List dict: A list of dicts for the associated student item. The submission contains five attributes: student_item, attempt_number, submitted_at, created_at, and answer. 'student_item' is the ID of the related student item for the submission. 'attempt_number' is the attempt this submission represents for this question. 'submitted_at' represents the time this submission was submitted, which can be configured, versus the 'created_at' date, which is when the submission is first created. Raises: SubmissionRequestError: Raised when the associated student item fails validation. SubmissionNotFoundError: Raised when a submission cannot be found for the associated student item. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> get_submissions(student_item_dict, 3) [{ 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' }] """ student_item_model = _get_or_create_student_item(student_item_dict) try: submission_models = Submission.objects.filter( student_item=student_item_model) except DatabaseError: error_message = ( u"Error getting submission request for student item {}" .format(student_item_dict) ) logger.exception(error_message) raise SubmissionNotFoundError(error_message) if limit: submission_models = submission_models[:limit] return SubmissionSerializer(submission_models, many=True).data def get_all_submissions(course_id, item_id, item_type, read_replica=True): """For the given item, get the most recent submission for every student who has submitted. This may return a very large result set! It is implemented as a generator for efficiency. Args: course_id, item_id, item_type (string): The values of the respective student_item fields to filter the submissions by. read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Yields: Dicts representing the submissions with the following fields: student_item student_id attempt_number submitted_at created_at answer Raises: Cannot fail unless there's a database error, but may return an empty iterable. """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) # We cannot use SELECT DISTINCT ON because it's PostgreSQL only, so unfortunately # our results will contain every entry of each student, not just the most recent. # We sort by student_id and primary key, so the reults will be grouped be grouped by # student, with the most recent submission being the first one in each group. query = submission_qs.select_related('student_item').filter( student_item__course_id=course_id, student_item__item_id=item_id, student_item__item_type=item_type, ).order_by('student_item__student_id', '-submitted_at', '-id').iterator() for unused_student_id, row_iter in itertools.groupby(query, operator.attrgetter('student_item.student_id')): submission = next(row_iter) data = SubmissionSerializer(submission).data data['student_id'] = submission.student_item.student_id yield data def get_all_course_submission_information(course_id, item_type, read_replica=True): """ For the given course, get all student items of the given item type, all the submissions for those itemes, and the latest scores for each item. If a submission was given a score that is not the latest score for the relevant student item, it will still be included but without score. Args: course_id (str): The course that we are getting submissions from. item_type (str): The type of items that we are getting submissions for. read_replica (bool): Try to use the database's read replica if it's available. Yields: A tuple of three dictionaries representing: (1) a student item with the following fields: student_id course_id student_item item_type (2) a submission with the following fields: student_item attempt_number submitted_at created_at answer (3) a score with the following fields, if one exists and it is the latest score: (if both conditions are not met, an empty dict is returned here) student_item submission points_earned points_possible created_at submission_uuid """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) query = submission_qs.select_related('student_item__scoresummary__latest__submission').filter( student_item__course_id=course_id, student_item__item_type=item_type, ).iterator() for submission in query: student_item = submission.student_item serialized_score = {} if hasattr(student_item, 'scoresummary'): latest_score = student_item.scoresummary.latest # Only include the score if it is not a reset score (is_hidden), and if the current submission is the same # as the student_item's latest score's submission. This matches the behavior of the API's get_score method. if (not latest_score.is_hidden()) and latest_score.submission.uuid == submission.uuid: serialized_score = ScoreSerializer(latest_score).data yield ( StudentItemSerializer(student_item).data, SubmissionSerializer(submission).data, serialized_score ) def get_top_submissions(course_id, item_id, item_type, number_of_top_scores, use_cache=True, read_replica=True): """Get a number of top scores for an assessment based on a particular student item This function will return top scores for the piece of assessment. It will consider only the latest and greater than 0 score for a piece of assessment. A score is only calculated for a student item if it has completed the workflow for a particular assessment module. In general, users of top submissions can tolerate some latency in the search results, so by default this call uses a cache and the read replica (if available). Args: course_id (str): The course to retrieve for the top scores item_id (str): The item within the course to retrieve for the top scores item_type (str): The type of item to retrieve number_of_top_scores (int): The number of scores to return, greater than 0 and no more than 100. Kwargs: use_cache (bool): If true, check the cache before retrieving querying the database. read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: topscores (dict): The top scores for the assessment for the student item. An empty array if there are no scores or all scores are 0. Raises: SubmissionNotFoundError: Raised when a submission cannot be found for the associated student item. SubmissionRequestError: Raised when the number of top scores is higher than the MAX_TOP_SUBMISSIONS constant. Examples: >>> course_id = "TestCourse" >>> item_id = "u_67" >>> item_type = "openassessment" >>> number_of_top_scores = 10 >>> >>> get_top_submissions(course_id, item_id, item_type, number_of_top_scores) [{ 'score': 20, 'content': "Platypus" },{ 'score': 16, 'content': "Frog" }] """ if number_of_top_scores < 1 or number_of_top_scores > MAX_TOP_SUBMISSIONS: error_msg = ( u"Number of top scores must be a number between 1 and {}.".format(MAX_TOP_SUBMISSIONS) ) logger.exception(error_msg) raise SubmissionRequestError(msg=error_msg) # First check the cache (unless caching is disabled) cache_key = "submissions.top_submissions.{course}.{item}.{type}.{number}".format( course=course_id, item=item_id, type=item_type, number=number_of_top_scores ) top_submissions = cache.get(cache_key) if use_cache else None # If we can't find it in the cache (or caching is disabled), check the database # By default, prefer the read-replica. if top_submissions is None: try: query = ScoreSummary.objects.filter( student_item__course_id=course_id, student_item__item_id=item_id, student_item__item_type=item_type, latest__points_earned__gt=0 ).select_related('latest', 'latest__submission').order_by("-latest__points_earned") if read_replica: query = _use_read_replica(query) score_summaries = query[:number_of_top_scores] except DatabaseError: msg = u"Could not fetch top score summaries for course {}, item {} of type {}".format( course_id, item_id, item_type ) logger.exception(msg) raise SubmissionInternalError(msg) # Retrieve the submission content for each top score top_submissions = [ { "score": score_summary.latest.points_earned, "content": SubmissionSerializer(score_summary.latest.submission).data['answer'] } for score_summary in score_summaries ] # Always store the retrieved list in the cache cache.set(cache_key, top_submissions, TOP_SUBMISSIONS_CACHE_TIMEOUT) return top_submissions def get_score(student_item): """Get the score for a particular student item Each student item should have a unique score. This function will return the score if it is available. A score is only calculated for a student item if it has completed the workflow for a particular assessment module. Args: student_item (dict): The dictionary representation of a student item. Function returns the score related to this student item. Returns: score (dict): The score associated with this student item. None if there is no score found. Raises: SubmissionInternalError: Raised if a score cannot be retrieved because of an internal server error. Examples: >>> student_item = { >>> "student_id":"Tim", >>> "course_id":"TestCourse", >>> "item_id":"u_67", >>> "item_type":"openassessment" >>> } >>> >>> get_score(student_item) [{ 'student_item': 2, 'submission': 2, 'points_earned': 8, 'points_possible': 20, 'created_at': datetime.datetime(2014, 2, 7, 18, 30, 1, 807911, tzinfo=<UTC>) }] """ try: student_item_model = StudentItem.objects.get(**student_item) score = ScoreSummary.objects.get(student_item=student_item_model).latest except (ScoreSummary.DoesNotExist, StudentItem.DoesNotExist): return None # By convention, scores are hidden if "points possible" is set to 0. # This can occur when an instructor has reset scores for a student. if score.is_hidden(): return None else: return ScoreSerializer(score).data def get_scores(course_id, student_id): """Return a dict mapping item_ids to scores. Scores are represented by serialized Score objects in JSON-like dict format. This method would be used by an LMS to find all the scores for a given student in a given course. Scores that are "hidden" (because they have points earned set to zero) are excluded from the results. Args: course_id (str): Course ID, used to do a lookup on the `StudentItem`. student_id (str): Student ID, used to do a lookup on the `StudentItem`. Returns: dict: The keys are `item_id`s (`str`) and the values are tuples of `(points_earned, points_possible)`. All points are integer values and represent the raw, unweighted scores. Submissions does not have any concept of weights. If there are no entries matching the `course_id` or `student_id`, we simply return an empty dictionary. This is not considered an error because there might be many queries for the progress page of a person who has never submitted anything. Raises: SubmissionInternalError: An unexpected error occurred while resetting scores. """ try: score_summaries = ScoreSummary.objects.filter( student_item__course_id=course_id, student_item__student_id=student_id, ).select_related('latest', 'latest__submission', 'student_item') except DatabaseError: msg = u"Could not fetch scores for course {}, student {}".format( course_id, student_id ) logger.exception(msg) raise SubmissionInternalError(msg) scores = { summary.student_item.item_id: UnannotatedScoreSerializer(summary.latest).data for summary in score_summaries if not summary.latest.is_hidden() } return scores def get_latest_score_for_submission(submission_uuid, read_replica=False): """ Retrieve the latest score for a particular submission. Args: submission_uuid (str): The UUID of the submission to retrieve. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: dict: The serialized score model, or None if no score is available. """ try: # Ensure that submission_uuid is valid before fetching score submission_model = _get_submission_model(submission_uuid, read_replica) score_qs = Score.objects.filter( submission__uuid=submission_model.uuid ).order_by("-id").select_related("submission") if read_replica: score_qs = _use_read_replica(score_qs) score = score_qs[0] if score.is_hidden(): return None except (IndexError, Submission.DoesNotExist): return None return ScoreSerializer(score).data def reset_score(student_id, course_id, item_id, clear_state=False, emit_signal=True): """ Reset scores for a specific student on a specific problem. Note: this does *not* delete `Score` models from the database, since these are immutable. It simply creates a new score with the "reset" flag set to True. Args: student_id (unicode): The ID of the student for whom to reset scores. course_id (unicode): The ID of the course containing the item to reset. item_id (unicode): The ID of the item for which to reset scores. clear_state (bool): If True, will appear to delete any submissions associated with the specified StudentItem Returns: None Raises: SubmissionInternalError: An unexpected error occurred while resetting scores. """ # Retrieve the student item try: student_item = StudentItem.objects.get( student_id=student_id, course_id=course_id, item_id=item_id ) except StudentItem.DoesNotExist: # If there is no student item, then there is no score to reset, # so we can return immediately. return # Create a "reset" score try: score = Score.create_reset_score(student_item) if emit_signal: # Send a signal out to any listeners who are waiting for scoring events. score_reset.send( sender=None, anonymous_user_id=student_id, course_id=course_id, item_id=item_id, created_at=score.created_at, ) if clear_state: for sub in student_item.submission_set.all(): # soft-delete the Submission sub.status = Submission.DELETED sub.save(update_fields=["status"]) # Also clear out cached values cache_key = Submission.get_cache_key(sub.uuid) cache.delete(cache_key) except DatabaseError: msg = ( u"Error occurred while reseting scores for" u" item {item_id} in course {course_id} for student {student_id}" ).format(item_id=item_id, course_id=course_id, student_id=student_id) logger.exception(msg) raise SubmissionInternalError(msg) else: msg = u"Score reset for item {item_id} in course {course_id} for student {student_id}".format( item_id=item_id, course_id=course_id, student_id=student_id ) logger.info(msg) def set_score(submission_uuid, points_earned, points_possible, annotation_creator=None, annotation_type=None, annotation_reason=None): """Set a score for a particular submission. Sets the score for a particular submission. This score is calculated externally to the API. Args: submission_uuid (str): UUID for the submission (must exist). points_earned (int): The earned points for this submission. points_possible (int): The total points possible for this particular student item. annotation_creator (str): An optional field for recording who gave this particular score annotation_type (str): An optional field for recording what type of annotation should be created, e.g. "staff_override". annotation_reason (str): An optional field for recording why this score was set to its value. Returns: None Raises: SubmissionInternalError: Thrown if there was an internal error while attempting to save the score. SubmissionRequestError: Thrown if the given student item or submission are not found. Examples: >>> set_score("a778b933-9fb3-11e3-9c0f-040ccee02800", 11, 12) { 'student_item': 2, 'submission': 1, 'points_earned': 11, 'points_possible': 12, 'created_at': datetime.datetime(2014, 2, 7, 20, 6, 42, 331156, tzinfo=<UTC>) } """ try: submission_model = _get_submission_model(submission_uuid) except Submission.DoesNotExist: raise SubmissionNotFoundError( u"No submission matching uuid {}".format(submission_uuid) ) except DatabaseError: error_msg = u"Could not retrieve submission {}.".format( submission_uuid ) logger.exception(error_msg) raise SubmissionRequestError(msg=error_msg) score = ScoreSerializer( data={ "student_item": submission_model.student_item.pk, "submission": submission_model.pk, "points_earned": points_earned, "points_possible": points_possible, } ) if not score.is_valid(): logger.exception(score.errors) raise SubmissionInternalError(score.errors) # When we save the score, a score summary will be created if # it does not already exist. # When the database's isolation level is set to repeatable-read, # it's possible for a score summary to exist for this student item, # even though we cannot retrieve it. # In this case, we assume that someone else has already created # a score summary and ignore the error. # TODO: once we're using Django 1.8, use transactions to ensure that these # two models are saved at the same time. try: score_model = score.save() _log_score(score_model) if annotation_creator is not None: score_annotation = ScoreAnnotation( score=score_model, creator=annotation_creator, annotation_type=annotation_type, reason=annotation_reason ) score_annotation.save() # Send a signal out to any listeners who are waiting for scoring events. score_set.send( sender=None, points_possible=points_possible, points_earned=points_earned, anonymous_user_id=submission_model.student_item.student_id, course_id=submission_model.student_item.course_id, item_id=submission_model.student_item.item_id, created_at=score_model.created_at, ) except IntegrityError: pass def _log_submission(submission, student_item): """ Log the creation of a submission. Args: submission (dict): The serialized submission model. student_item (dict): The serialized student item model. Returns: None """ logger.info( u"Created submission uuid={submission_uuid} for " u"(course_id={course_id}, item_id={item_id}, " u"anonymous_student_id={anonymous_student_id})" .format( submission_uuid=submission["uuid"], course_id=student_item["course_id"], item_id=student_item["item_id"], anonymous_student_id=student_item["student_id"] ) ) def _get_or_create_student_item(student_item_dict): """Gets or creates a Student Item that matches the values specified. Attempts to get the specified Student Item. If it does not exist, the specified parameters are validated, and a new Student Item is created. Args: student_item_dict (dict): The dict containing the student_id, item_id, course_id, and item_type that uniquely defines a student item. Returns: StudentItem: The student item that was retrieved or created. Raises: SubmissionInternalError: Thrown if there was an internal error while attempting to create or retrieve the specified student item. SubmissionRequestError: Thrown if the given student item parameters fail validation. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> _get_or_create_student_item(student_item_dict) {'item_id': 'item_1', 'item_type': 'type_one', 'course_id': 'course_1', 'student_id': 'Tim'} """ try: try: return StudentItem.objects.get(**student_item_dict) except StudentItem.DoesNotExist: student_item_serializer = StudentItemSerializer( data=student_item_dict ) if not student_item_serializer.is_valid(): logger.error( u"Invalid StudentItemSerializer: errors:{} data:{}".format( student_item_serializer.errors, student_item_dict ) ) raise SubmissionRequestError(field_errors=student_item_serializer.errors) return student_item_serializer.save() except DatabaseError: error_message = u"An error occurred creating student item: {}".format( student_item_dict ) logger.exception(error_message) raise SubmissionInternalError(error_message) def _use_read_replica(queryset): """ Use the read replica if it's available. Args: queryset (QuerySet) Returns: QuerySet """ return ( queryset.using("read_replica") if "read_replica" in settings.DATABASES else queryset )
edx/edx-submissions
submissions/api.py
_get_or_create_student_item
python
def _get_or_create_student_item(student_item_dict): try: try: return StudentItem.objects.get(**student_item_dict) except StudentItem.DoesNotExist: student_item_serializer = StudentItemSerializer( data=student_item_dict ) if not student_item_serializer.is_valid(): logger.error( u"Invalid StudentItemSerializer: errors:{} data:{}".format( student_item_serializer.errors, student_item_dict ) ) raise SubmissionRequestError(field_errors=student_item_serializer.errors) return student_item_serializer.save() except DatabaseError: error_message = u"An error occurred creating student item: {}".format( student_item_dict ) logger.exception(error_message) raise SubmissionInternalError(error_message)
Gets or creates a Student Item that matches the values specified. Attempts to get the specified Student Item. If it does not exist, the specified parameters are validated, and a new Student Item is created. Args: student_item_dict (dict): The dict containing the student_id, item_id, course_id, and item_type that uniquely defines a student item. Returns: StudentItem: The student item that was retrieved or created. Raises: SubmissionInternalError: Thrown if there was an internal error while attempting to create or retrieve the specified student item. SubmissionRequestError: Thrown if the given student item parameters fail validation. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> _get_or_create_student_item(student_item_dict) {'item_id': 'item_1', 'item_type': 'type_one', 'course_id': 'course_1', 'student_id': 'Tim'}
train
https://github.com/edx/edx-submissions/blob/8d531ca25f7c2886dfcb1bb8febe0910e1433ca2/submissions/api.py#L963-L1014
null
""" Public interface for the submissions app. """ from __future__ import absolute_import import copy import itertools import logging import operator import json from uuid import UUID from django.conf import settings from django.core.cache import cache from django.db import IntegrityError, DatabaseError from submissions.serializers import ( SubmissionSerializer, StudentItemSerializer, ScoreSerializer, UnannotatedScoreSerializer ) from submissions.models import Submission, StudentItem, Score, ScoreSummary, ScoreAnnotation, score_set, score_reset import six logger = logging.getLogger("submissions.api") # By default, limit the number of top submissions # Anything above this limit will result in a request error MAX_TOP_SUBMISSIONS = 100 # Set a relatively low cache timeout for top submissions. TOP_SUBMISSIONS_CACHE_TIMEOUT = 300 class SubmissionError(Exception): """An error that occurs during submission actions. This error is raised when the submission API cannot perform a requested action. """ pass class SubmissionInternalError(SubmissionError): """An error internal to the Submission API has occurred. This error is raised when an error occurs that is not caused by incorrect use of the API, but rather internal implementation of the underlying services. """ pass class SubmissionNotFoundError(SubmissionError): """This error is raised when no submission is found for the request. If a state is specified in a call to the API that results in no matching Submissions, this error may be raised. """ pass class SubmissionRequestError(SubmissionError): """This error is raised when there was a request-specific error This error is reserved for problems specific to the use of the API. """ def __init__(self, msg="", field_errors=None): """ Configure the submission request error. Keyword Args: msg (unicode): The error message. field_errors (dict): A dictionary of errors (list of unicode) specific to a fields provided in the request. Example usage: >>> raise SubmissionRequestError( >>> "An unexpected error occurred" >>> {"answer": ["Maximum answer length exceeded."]} >>> ) """ super(SubmissionRequestError, self).__init__(msg) self.field_errors = ( copy.deepcopy(field_errors) if field_errors is not None else {} ) self.args += (self.field_errors,) def __repr__(self): """ Show the field errors upon output. """ return '{}(msg="{}", field_errors={})'.format( self.__class__.__name__, self.message, self.field_errors ) def create_submission(student_item_dict, answer, submitted_at=None, attempt_number=None): """Creates a submission for assessment. Generic means by which to submit an answer for assessment. Args: student_item_dict (dict): The student_item this submission is associated with. This is used to determine which course, student, and location this submission belongs to. answer (JSON-serializable): The answer given by the student to be assessed. submitted_at (datetime): The date in which this submission was submitted. If not specified, defaults to the current date. attempt_number (int): A student may be able to submit multiple attempts per question. This allows the designated attempt to be overridden. If the attempt is not specified, it will take the most recent submission, as specified by the submitted_at time, and use its attempt_number plus one. Returns: dict: A representation of the created Submission. The submission contains five attributes: student_item, attempt_number, submitted_at, created_at, and answer. 'student_item' is the ID of the related student item for the submission. 'attempt_number' is the attempt this submission represents for this question. 'submitted_at' represents the time this submission was submitted, which can be configured, versus the 'created_at' date, which is when the submission is first created. Raises: SubmissionRequestError: Raised when there are validation errors for the student item or submission. This can be caused by the student item missing required values, the submission being too long, the attempt_number is negative, or the given submitted_at time is invalid. SubmissionInternalError: Raised when submission access causes an internal error. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> create_submission(student_item_dict, "The answer is 42.", datetime.utcnow, 1) { 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 649284 tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' } """ student_item_model = _get_or_create_student_item(student_item_dict) if attempt_number is None: try: submissions = Submission.objects.filter( student_item=student_item_model)[:1] except DatabaseError: error_message = u"An error occurred while filtering submissions for student item: {}".format( student_item_dict) logger.exception(error_message) raise SubmissionInternalError(error_message) attempt_number = submissions[0].attempt_number + 1 if submissions else 1 model_kwargs = { "student_item": student_item_model.pk, "answer": answer, "attempt_number": attempt_number, } if submitted_at: model_kwargs["submitted_at"] = submitted_at try: submission_serializer = SubmissionSerializer(data=model_kwargs) if not submission_serializer.is_valid(): raise SubmissionRequestError(field_errors=submission_serializer.errors) submission_serializer.save() sub_data = submission_serializer.data _log_submission(sub_data, student_item_dict) return sub_data except DatabaseError: error_message = u"An error occurred while creating submission {} for student item: {}".format( model_kwargs, student_item_dict ) logger.exception(error_message) raise SubmissionInternalError(error_message) def _get_submission_model(uuid, read_replica=False): """ Helper to retrieve a given Submission object from the database. Helper is needed to centralize logic that fixes EDUCATOR-1090, because uuids are stored both with and without hyphens. """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) try: submission = submission_qs.get(uuid=uuid) except Submission.DoesNotExist: try: hyphenated_value = six.text_type(UUID(uuid)) query = """ SELECT `submissions_submission`.`id`, `submissions_submission`.`uuid`, `submissions_submission`.`student_item_id`, `submissions_submission`.`attempt_number`, `submissions_submission`.`submitted_at`, `submissions_submission`.`created_at`, `submissions_submission`.`raw_answer`, `submissions_submission`.`status` FROM `submissions_submission` WHERE ( NOT (`submissions_submission`.`status` = 'D') AND `submissions_submission`.`uuid` = '{}' ) """ query = query.replace("{}", hyphenated_value) # We can use Submission.objects instead of the SoftDeletedManager, we'll include that logic manually submission = Submission.objects.raw(query)[0] except IndexError: raise Submission.DoesNotExist() # Avoid the extra hit next time submission.save(update_fields=['uuid']) return submission def get_submission(submission_uuid, read_replica=False): """Retrieves a single submission by uuid. Args: submission_uuid (str): Identifier for the submission. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Raises: SubmissionNotFoundError: Raised if the submission does not exist. SubmissionRequestError: Raised if the search parameter is not a string. SubmissionInternalError: Raised for unknown errors. Examples: >>> get_submission("20b78e0f32df805d21064fc912f40e9ae5ab260d") { 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' } """ if not isinstance(submission_uuid, six.string_types): if isinstance(submission_uuid, UUID): submission_uuid = six.text_type(submission_uuid) else: raise SubmissionRequestError( msg="submission_uuid ({!r}) must be serializable".format(submission_uuid) ) cache_key = Submission.get_cache_key(submission_uuid) try: cached_submission_data = cache.get(cache_key) except Exception: # The cache backend could raise an exception # (for example, memcache keys that contain spaces) logger.exception("Error occurred while retrieving submission from the cache") cached_submission_data = None if cached_submission_data: logger.info("Get submission {} (cached)".format(submission_uuid)) return cached_submission_data try: submission = _get_submission_model(submission_uuid, read_replica) submission_data = SubmissionSerializer(submission).data cache.set(cache_key, submission_data) except Submission.DoesNotExist: logger.error("Submission {} not found.".format(submission_uuid)) raise SubmissionNotFoundError( u"No submission matching uuid {}".format(submission_uuid) ) except Exception as exc: # Something very unexpected has just happened (like DB misconfig) err_msg = "Could not get submission due to error: {}".format(exc) logger.exception(err_msg) raise SubmissionInternalError(err_msg) logger.info("Get submission {}".format(submission_uuid)) return submission_data def get_submission_and_student(uuid, read_replica=False): """ Retrieve a submission by its unique identifier, including the associated student item. Args: uuid (str): the unique identifier of the submission. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: Serialized Submission model (dict) containing a serialized StudentItem model Raises: SubmissionNotFoundError: Raised if the submission does not exist. SubmissionRequestError: Raised if the search parameter is not a string. SubmissionInternalError: Raised for unknown errors. """ # This may raise API exceptions submission = get_submission(uuid, read_replica=read_replica) # Retrieve the student item from the cache cache_key = "submissions.student_item.{}".format(submission['student_item']) try: cached_student_item = cache.get(cache_key) except Exception: # The cache backend could raise an exception # (for example, memcache keys that contain spaces) logger.exception("Error occurred while retrieving student item from the cache") cached_student_item = None if cached_student_item is not None: submission['student_item'] = cached_student_item else: # There is probably a more idiomatic way to do this using the Django REST framework try: student_item_qs = StudentItem.objects if read_replica: student_item_qs = _use_read_replica(student_item_qs) student_item = student_item_qs.get(id=submission['student_item']) submission['student_item'] = StudentItemSerializer(student_item).data cache.set(cache_key, submission['student_item']) except Exception as ex: err_msg = "Could not get submission due to error: {}".format(ex) logger.exception(err_msg) raise SubmissionInternalError(err_msg) return submission def get_submissions(student_item_dict, limit=None): """Retrieves the submissions for the specified student item, ordered by most recent submitted date. Returns the submissions relative to the specified student item. Exception thrown if no submission is found relative to this location. Args: student_item_dict (dict): The location of the problem this submission is associated with, as defined by a course, student, and item. limit (int): Optional parameter for limiting the returned number of submissions associated with this student item. If not specified, all associated submissions are returned. Returns: List dict: A list of dicts for the associated student item. The submission contains five attributes: student_item, attempt_number, submitted_at, created_at, and answer. 'student_item' is the ID of the related student item for the submission. 'attempt_number' is the attempt this submission represents for this question. 'submitted_at' represents the time this submission was submitted, which can be configured, versus the 'created_at' date, which is when the submission is first created. Raises: SubmissionRequestError: Raised when the associated student item fails validation. SubmissionNotFoundError: Raised when a submission cannot be found for the associated student item. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> get_submissions(student_item_dict, 3) [{ 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' }] """ student_item_model = _get_or_create_student_item(student_item_dict) try: submission_models = Submission.objects.filter( student_item=student_item_model) except DatabaseError: error_message = ( u"Error getting submission request for student item {}" .format(student_item_dict) ) logger.exception(error_message) raise SubmissionNotFoundError(error_message) if limit: submission_models = submission_models[:limit] return SubmissionSerializer(submission_models, many=True).data def get_all_submissions(course_id, item_id, item_type, read_replica=True): """For the given item, get the most recent submission for every student who has submitted. This may return a very large result set! It is implemented as a generator for efficiency. Args: course_id, item_id, item_type (string): The values of the respective student_item fields to filter the submissions by. read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Yields: Dicts representing the submissions with the following fields: student_item student_id attempt_number submitted_at created_at answer Raises: Cannot fail unless there's a database error, but may return an empty iterable. """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) # We cannot use SELECT DISTINCT ON because it's PostgreSQL only, so unfortunately # our results will contain every entry of each student, not just the most recent. # We sort by student_id and primary key, so the reults will be grouped be grouped by # student, with the most recent submission being the first one in each group. query = submission_qs.select_related('student_item').filter( student_item__course_id=course_id, student_item__item_id=item_id, student_item__item_type=item_type, ).order_by('student_item__student_id', '-submitted_at', '-id').iterator() for unused_student_id, row_iter in itertools.groupby(query, operator.attrgetter('student_item.student_id')): submission = next(row_iter) data = SubmissionSerializer(submission).data data['student_id'] = submission.student_item.student_id yield data def get_all_course_submission_information(course_id, item_type, read_replica=True): """ For the given course, get all student items of the given item type, all the submissions for those itemes, and the latest scores for each item. If a submission was given a score that is not the latest score for the relevant student item, it will still be included but without score. Args: course_id (str): The course that we are getting submissions from. item_type (str): The type of items that we are getting submissions for. read_replica (bool): Try to use the database's read replica if it's available. Yields: A tuple of three dictionaries representing: (1) a student item with the following fields: student_id course_id student_item item_type (2) a submission with the following fields: student_item attempt_number submitted_at created_at answer (3) a score with the following fields, if one exists and it is the latest score: (if both conditions are not met, an empty dict is returned here) student_item submission points_earned points_possible created_at submission_uuid """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) query = submission_qs.select_related('student_item__scoresummary__latest__submission').filter( student_item__course_id=course_id, student_item__item_type=item_type, ).iterator() for submission in query: student_item = submission.student_item serialized_score = {} if hasattr(student_item, 'scoresummary'): latest_score = student_item.scoresummary.latest # Only include the score if it is not a reset score (is_hidden), and if the current submission is the same # as the student_item's latest score's submission. This matches the behavior of the API's get_score method. if (not latest_score.is_hidden()) and latest_score.submission.uuid == submission.uuid: serialized_score = ScoreSerializer(latest_score).data yield ( StudentItemSerializer(student_item).data, SubmissionSerializer(submission).data, serialized_score ) def get_top_submissions(course_id, item_id, item_type, number_of_top_scores, use_cache=True, read_replica=True): """Get a number of top scores for an assessment based on a particular student item This function will return top scores for the piece of assessment. It will consider only the latest and greater than 0 score for a piece of assessment. A score is only calculated for a student item if it has completed the workflow for a particular assessment module. In general, users of top submissions can tolerate some latency in the search results, so by default this call uses a cache and the read replica (if available). Args: course_id (str): The course to retrieve for the top scores item_id (str): The item within the course to retrieve for the top scores item_type (str): The type of item to retrieve number_of_top_scores (int): The number of scores to return, greater than 0 and no more than 100. Kwargs: use_cache (bool): If true, check the cache before retrieving querying the database. read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: topscores (dict): The top scores for the assessment for the student item. An empty array if there are no scores or all scores are 0. Raises: SubmissionNotFoundError: Raised when a submission cannot be found for the associated student item. SubmissionRequestError: Raised when the number of top scores is higher than the MAX_TOP_SUBMISSIONS constant. Examples: >>> course_id = "TestCourse" >>> item_id = "u_67" >>> item_type = "openassessment" >>> number_of_top_scores = 10 >>> >>> get_top_submissions(course_id, item_id, item_type, number_of_top_scores) [{ 'score': 20, 'content': "Platypus" },{ 'score': 16, 'content': "Frog" }] """ if number_of_top_scores < 1 or number_of_top_scores > MAX_TOP_SUBMISSIONS: error_msg = ( u"Number of top scores must be a number between 1 and {}.".format(MAX_TOP_SUBMISSIONS) ) logger.exception(error_msg) raise SubmissionRequestError(msg=error_msg) # First check the cache (unless caching is disabled) cache_key = "submissions.top_submissions.{course}.{item}.{type}.{number}".format( course=course_id, item=item_id, type=item_type, number=number_of_top_scores ) top_submissions = cache.get(cache_key) if use_cache else None # If we can't find it in the cache (or caching is disabled), check the database # By default, prefer the read-replica. if top_submissions is None: try: query = ScoreSummary.objects.filter( student_item__course_id=course_id, student_item__item_id=item_id, student_item__item_type=item_type, latest__points_earned__gt=0 ).select_related('latest', 'latest__submission').order_by("-latest__points_earned") if read_replica: query = _use_read_replica(query) score_summaries = query[:number_of_top_scores] except DatabaseError: msg = u"Could not fetch top score summaries for course {}, item {} of type {}".format( course_id, item_id, item_type ) logger.exception(msg) raise SubmissionInternalError(msg) # Retrieve the submission content for each top score top_submissions = [ { "score": score_summary.latest.points_earned, "content": SubmissionSerializer(score_summary.latest.submission).data['answer'] } for score_summary in score_summaries ] # Always store the retrieved list in the cache cache.set(cache_key, top_submissions, TOP_SUBMISSIONS_CACHE_TIMEOUT) return top_submissions def get_score(student_item): """Get the score for a particular student item Each student item should have a unique score. This function will return the score if it is available. A score is only calculated for a student item if it has completed the workflow for a particular assessment module. Args: student_item (dict): The dictionary representation of a student item. Function returns the score related to this student item. Returns: score (dict): The score associated with this student item. None if there is no score found. Raises: SubmissionInternalError: Raised if a score cannot be retrieved because of an internal server error. Examples: >>> student_item = { >>> "student_id":"Tim", >>> "course_id":"TestCourse", >>> "item_id":"u_67", >>> "item_type":"openassessment" >>> } >>> >>> get_score(student_item) [{ 'student_item': 2, 'submission': 2, 'points_earned': 8, 'points_possible': 20, 'created_at': datetime.datetime(2014, 2, 7, 18, 30, 1, 807911, tzinfo=<UTC>) }] """ try: student_item_model = StudentItem.objects.get(**student_item) score = ScoreSummary.objects.get(student_item=student_item_model).latest except (ScoreSummary.DoesNotExist, StudentItem.DoesNotExist): return None # By convention, scores are hidden if "points possible" is set to 0. # This can occur when an instructor has reset scores for a student. if score.is_hidden(): return None else: return ScoreSerializer(score).data def get_scores(course_id, student_id): """Return a dict mapping item_ids to scores. Scores are represented by serialized Score objects in JSON-like dict format. This method would be used by an LMS to find all the scores for a given student in a given course. Scores that are "hidden" (because they have points earned set to zero) are excluded from the results. Args: course_id (str): Course ID, used to do a lookup on the `StudentItem`. student_id (str): Student ID, used to do a lookup on the `StudentItem`. Returns: dict: The keys are `item_id`s (`str`) and the values are tuples of `(points_earned, points_possible)`. All points are integer values and represent the raw, unweighted scores. Submissions does not have any concept of weights. If there are no entries matching the `course_id` or `student_id`, we simply return an empty dictionary. This is not considered an error because there might be many queries for the progress page of a person who has never submitted anything. Raises: SubmissionInternalError: An unexpected error occurred while resetting scores. """ try: score_summaries = ScoreSummary.objects.filter( student_item__course_id=course_id, student_item__student_id=student_id, ).select_related('latest', 'latest__submission', 'student_item') except DatabaseError: msg = u"Could not fetch scores for course {}, student {}".format( course_id, student_id ) logger.exception(msg) raise SubmissionInternalError(msg) scores = { summary.student_item.item_id: UnannotatedScoreSerializer(summary.latest).data for summary in score_summaries if not summary.latest.is_hidden() } return scores def get_latest_score_for_submission(submission_uuid, read_replica=False): """ Retrieve the latest score for a particular submission. Args: submission_uuid (str): The UUID of the submission to retrieve. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: dict: The serialized score model, or None if no score is available. """ try: # Ensure that submission_uuid is valid before fetching score submission_model = _get_submission_model(submission_uuid, read_replica) score_qs = Score.objects.filter( submission__uuid=submission_model.uuid ).order_by("-id").select_related("submission") if read_replica: score_qs = _use_read_replica(score_qs) score = score_qs[0] if score.is_hidden(): return None except (IndexError, Submission.DoesNotExist): return None return ScoreSerializer(score).data def reset_score(student_id, course_id, item_id, clear_state=False, emit_signal=True): """ Reset scores for a specific student on a specific problem. Note: this does *not* delete `Score` models from the database, since these are immutable. It simply creates a new score with the "reset" flag set to True. Args: student_id (unicode): The ID of the student for whom to reset scores. course_id (unicode): The ID of the course containing the item to reset. item_id (unicode): The ID of the item for which to reset scores. clear_state (bool): If True, will appear to delete any submissions associated with the specified StudentItem Returns: None Raises: SubmissionInternalError: An unexpected error occurred while resetting scores. """ # Retrieve the student item try: student_item = StudentItem.objects.get( student_id=student_id, course_id=course_id, item_id=item_id ) except StudentItem.DoesNotExist: # If there is no student item, then there is no score to reset, # so we can return immediately. return # Create a "reset" score try: score = Score.create_reset_score(student_item) if emit_signal: # Send a signal out to any listeners who are waiting for scoring events. score_reset.send( sender=None, anonymous_user_id=student_id, course_id=course_id, item_id=item_id, created_at=score.created_at, ) if clear_state: for sub in student_item.submission_set.all(): # soft-delete the Submission sub.status = Submission.DELETED sub.save(update_fields=["status"]) # Also clear out cached values cache_key = Submission.get_cache_key(sub.uuid) cache.delete(cache_key) except DatabaseError: msg = ( u"Error occurred while reseting scores for" u" item {item_id} in course {course_id} for student {student_id}" ).format(item_id=item_id, course_id=course_id, student_id=student_id) logger.exception(msg) raise SubmissionInternalError(msg) else: msg = u"Score reset for item {item_id} in course {course_id} for student {student_id}".format( item_id=item_id, course_id=course_id, student_id=student_id ) logger.info(msg) def set_score(submission_uuid, points_earned, points_possible, annotation_creator=None, annotation_type=None, annotation_reason=None): """Set a score for a particular submission. Sets the score for a particular submission. This score is calculated externally to the API. Args: submission_uuid (str): UUID for the submission (must exist). points_earned (int): The earned points for this submission. points_possible (int): The total points possible for this particular student item. annotation_creator (str): An optional field for recording who gave this particular score annotation_type (str): An optional field for recording what type of annotation should be created, e.g. "staff_override". annotation_reason (str): An optional field for recording why this score was set to its value. Returns: None Raises: SubmissionInternalError: Thrown if there was an internal error while attempting to save the score. SubmissionRequestError: Thrown if the given student item or submission are not found. Examples: >>> set_score("a778b933-9fb3-11e3-9c0f-040ccee02800", 11, 12) { 'student_item': 2, 'submission': 1, 'points_earned': 11, 'points_possible': 12, 'created_at': datetime.datetime(2014, 2, 7, 20, 6, 42, 331156, tzinfo=<UTC>) } """ try: submission_model = _get_submission_model(submission_uuid) except Submission.DoesNotExist: raise SubmissionNotFoundError( u"No submission matching uuid {}".format(submission_uuid) ) except DatabaseError: error_msg = u"Could not retrieve submission {}.".format( submission_uuid ) logger.exception(error_msg) raise SubmissionRequestError(msg=error_msg) score = ScoreSerializer( data={ "student_item": submission_model.student_item.pk, "submission": submission_model.pk, "points_earned": points_earned, "points_possible": points_possible, } ) if not score.is_valid(): logger.exception(score.errors) raise SubmissionInternalError(score.errors) # When we save the score, a score summary will be created if # it does not already exist. # When the database's isolation level is set to repeatable-read, # it's possible for a score summary to exist for this student item, # even though we cannot retrieve it. # In this case, we assume that someone else has already created # a score summary and ignore the error. # TODO: once we're using Django 1.8, use transactions to ensure that these # two models are saved at the same time. try: score_model = score.save() _log_score(score_model) if annotation_creator is not None: score_annotation = ScoreAnnotation( score=score_model, creator=annotation_creator, annotation_type=annotation_type, reason=annotation_reason ) score_annotation.save() # Send a signal out to any listeners who are waiting for scoring events. score_set.send( sender=None, points_possible=points_possible, points_earned=points_earned, anonymous_user_id=submission_model.student_item.student_id, course_id=submission_model.student_item.course_id, item_id=submission_model.student_item.item_id, created_at=score_model.created_at, ) except IntegrityError: pass def _log_submission(submission, student_item): """ Log the creation of a submission. Args: submission (dict): The serialized submission model. student_item (dict): The serialized student item model. Returns: None """ logger.info( u"Created submission uuid={submission_uuid} for " u"(course_id={course_id}, item_id={item_id}, " u"anonymous_student_id={anonymous_student_id})" .format( submission_uuid=submission["uuid"], course_id=student_item["course_id"], item_id=student_item["item_id"], anonymous_student_id=student_item["student_id"] ) ) def _log_score(score): """ Log the creation of a score. Args: score (Score): The score model. Returns: None """ logger.info( "Score of ({}/{}) set for submission {}" .format(score.points_earned, score.points_possible, score.submission.uuid) ) def _use_read_replica(queryset): """ Use the read replica if it's available. Args: queryset (QuerySet) Returns: QuerySet """ return ( queryset.using("read_replica") if "read_replica" in settings.DATABASES else queryset )
puiterwijk/flask-oidc
flask_oidc/registration.py
check_redirect_uris
python
def check_redirect_uris(uris, client_type=None): if client_type not in [None, 'native', 'web']: raise ValueError('Invalid client type indicator used') if not isinstance(uris, list): raise ValueError('uris needs to be a list of strings') if len(uris) < 1: raise ValueError('At least one return URI needs to be provided') for uri in uris: if uri.startswith('https://'): if client_type == 'native': raise ValueError('https url with native client') client_type = 'web' elif uri.startswith('http://localhost'): if client_type == 'web': raise ValueError('http://localhost url with web client') client_type = 'native' else: if (uri.startswith('http://') and not uri.startswith('http://localhost')): raise ValueError('http:// url with non-localhost is illegal') else: raise ValueError('Invalid uri provided: %s' % uri) return client_type
This function checks all return uris provided and tries to deduce as what type of client we should register. :param uris: The redirect URIs to check. :type uris: list :param client_type: An indicator of which client type you are expecting to be used. If this does not match the deduced type, an error will be raised. :type client_type: str :returns: The deduced client type. :rtype: str :raises ValueError: An error occured while checking the redirect uris. .. versionadded:: 1.0
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/registration.py#L31-L73
null
# Copyright (c) 2016, Patrick Uiterwijk <patrick@puiterwijk.org> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import json import httplib2 from flask_oidc import _json_loads class RegistrationError(Exception): """ This class is used to pass errors reported by the OpenID Provider during dynamic registration. .. versionadded:: 1.0 """ errorcode = None errordescription = None def __init__(self, response): self.errorcode = response['error'] self.errordescription = response.get('error_description') # OpenID Connect Dynamic Client Registration 1.0 def register_client(provider_info, redirect_uris): """ This function registers a new client with the specified OpenID Provider, and then returns the regitered client ID and other information. :param provider_info: The contents of the discovery endpoint as specified by the OpenID Connect Discovery 1.0 specifications. :type provider_info: dict :param redirect_uris: The redirect URIs the application wants to register. :type redirect_uris: list :returns: An object containing the information needed to configure the actual client code to communicate with the OpenID Provider. :rtype: dict :raises ValueError: The same error as used by check_redirect_uris. :raises RegistrationError: Indicates an error was returned by the OpenID Provider during registration. .. versionadded:: 1.0 """ client_type = check_redirect_uris(redirect_uris) submit_info = {'redirect_uris': redirect_uris, 'application_type': client_type, 'token_endpoint_auth_method': 'client_secret_post'} headers = {'Content-type': 'application/json'} resp, content = httplib2.Http().request( provider_info['registration_endpoint'], 'POST', json.dumps(submit_info), headers=headers) if int(resp['status']) >= 400: raise Exception('Error: the server returned HTTP ' + resp['status']) client_info = _json_loads(content) if 'error' in client_info: raise Exception('Error occured during registration: %s (%s)' % (client_info['error'], client_info.get('error_description'))) json_file = {'web': { 'client_id': client_info['client_id'], 'client_secret': client_info['client_secret'], 'auth_uri': provider_info['authorization_endpoint'], 'token_uri': provider_info['token_endpoint'], 'userinfo_uri': provider_info['userinfo_endpoint'], 'redirect_uris': redirect_uris, 'issuer': provider_info['issuer'], }} return json_file
puiterwijk/flask-oidc
flask_oidc/registration.py
register_client
python
def register_client(provider_info, redirect_uris): client_type = check_redirect_uris(redirect_uris) submit_info = {'redirect_uris': redirect_uris, 'application_type': client_type, 'token_endpoint_auth_method': 'client_secret_post'} headers = {'Content-type': 'application/json'} resp, content = httplib2.Http().request( provider_info['registration_endpoint'], 'POST', json.dumps(submit_info), headers=headers) if int(resp['status']) >= 400: raise Exception('Error: the server returned HTTP ' + resp['status']) client_info = _json_loads(content) if 'error' in client_info: raise Exception('Error occured during registration: %s (%s)' % (client_info['error'], client_info.get('error_description'))) json_file = {'web': { 'client_id': client_info['client_id'], 'client_secret': client_info['client_secret'], 'auth_uri': provider_info['authorization_endpoint'], 'token_uri': provider_info['token_endpoint'], 'userinfo_uri': provider_info['userinfo_endpoint'], 'redirect_uris': redirect_uris, 'issuer': provider_info['issuer'], }} return json_file
This function registers a new client with the specified OpenID Provider, and then returns the regitered client ID and other information. :param provider_info: The contents of the discovery endpoint as specified by the OpenID Connect Discovery 1.0 specifications. :type provider_info: dict :param redirect_uris: The redirect URIs the application wants to register. :type redirect_uris: list :returns: An object containing the information needed to configure the actual client code to communicate with the OpenID Provider. :rtype: dict :raises ValueError: The same error as used by check_redirect_uris. :raises RegistrationError: Indicates an error was returned by the OpenID Provider during registration. .. versionadded:: 1.0
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/registration.py#L92-L144
[ "def check_redirect_uris(uris, client_type=None):\n \"\"\"\n This function checks all return uris provided and tries to deduce\n as what type of client we should register.\n\n :param uris: The redirect URIs to check.\n :type uris: list\n :param client_type: An indicator of which client type you are expecting\n to be used. If this does not match the deduced type, an error will\n be raised.\n :type client_type: str\n :returns: The deduced client type.\n :rtype: str\n :raises ValueError: An error occured while checking the redirect uris.\n\n .. versionadded:: 1.0\n \"\"\"\n if client_type not in [None, 'native', 'web']:\n raise ValueError('Invalid client type indicator used')\n\n if not isinstance(uris, list):\n raise ValueError('uris needs to be a list of strings')\n\n if len(uris) < 1:\n raise ValueError('At least one return URI needs to be provided')\n\n for uri in uris:\n if uri.startswith('https://'):\n if client_type == 'native':\n raise ValueError('https url with native client')\n client_type = 'web'\n elif uri.startswith('http://localhost'):\n if client_type == 'web':\n raise ValueError('http://localhost url with web client')\n client_type = 'native'\n else:\n if (uri.startswith('http://') and \n not uri.startswith('http://localhost')):\n raise ValueError('http:// url with non-localhost is illegal')\n else:\n raise ValueError('Invalid uri provided: %s' % uri)\n\n return client_type\n" ]
# Copyright (c) 2016, Patrick Uiterwijk <patrick@puiterwijk.org> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import json import httplib2 from flask_oidc import _json_loads def check_redirect_uris(uris, client_type=None): """ This function checks all return uris provided and tries to deduce as what type of client we should register. :param uris: The redirect URIs to check. :type uris: list :param client_type: An indicator of which client type you are expecting to be used. If this does not match the deduced type, an error will be raised. :type client_type: str :returns: The deduced client type. :rtype: str :raises ValueError: An error occured while checking the redirect uris. .. versionadded:: 1.0 """ if client_type not in [None, 'native', 'web']: raise ValueError('Invalid client type indicator used') if not isinstance(uris, list): raise ValueError('uris needs to be a list of strings') if len(uris) < 1: raise ValueError('At least one return URI needs to be provided') for uri in uris: if uri.startswith('https://'): if client_type == 'native': raise ValueError('https url with native client') client_type = 'web' elif uri.startswith('http://localhost'): if client_type == 'web': raise ValueError('http://localhost url with web client') client_type = 'native' else: if (uri.startswith('http://') and not uri.startswith('http://localhost')): raise ValueError('http:// url with non-localhost is illegal') else: raise ValueError('Invalid uri provided: %s' % uri) return client_type class RegistrationError(Exception): """ This class is used to pass errors reported by the OpenID Provider during dynamic registration. .. versionadded:: 1.0 """ errorcode = None errordescription = None def __init__(self, response): self.errorcode = response['error'] self.errordescription = response.get('error_description') # OpenID Connect Dynamic Client Registration 1.0
puiterwijk/flask-oidc
flask_oidc/discovery.py
discover_OP_information
python
def discover_OP_information(OP_uri): _, content = httplib2.Http().request( '%s/.well-known/openid-configuration' % OP_uri) return _json_loads(content)
Discovers information about the provided OpenID Provider. :param OP_uri: The base URI of the Provider information is requested for. :type OP_uri: str :returns: The contents of the Provider metadata document. :rtype: dict .. versionadded:: 1.0
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/discovery.py#L31-L44
[ "def _json_loads(content):\n if not isinstance(content, str):\n content = content.decode('utf-8')\n return json.loads(content)\n" ]
# Copyright (c) 2016, Patrick Uiterwijk <patrick@puiterwijk.org> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import httplib2 from flask_oidc import _json_loads # OpenID Connect Discovery 1.0
puiterwijk/flask-oidc
flask_oidc/__init__.py
OpenIDConnect.init_app
python
def init_app(self, app): secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass
Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L125-L188
[ "def load_secrets(self, app):\n # Load client_secrets.json to pre-initialize some configuration\n content = app.config['OIDC_CLIENT_SECRETS']\n if isinstance(content, dict):\n return content\n else:\n return _json_loads(open(content, 'r').read())\n" ]
class OpenIDConnect(object): """ The core OpenID Connect client object. """ def __init__(self, app=None, credentials_store=None, http=None, time=None, urandom=None): self.credentials_store = credentials_store\ if credentials_store is not None\ else MemoryCredentials() if http is not None: warn('HTTP argument is deprecated and unused', DeprecationWarning) if time is not None: warn('time argument is deprecated and unused', DeprecationWarning) if urandom is not None: warn('urandom argument is deprecated and unused', DeprecationWarning) # By default, we do not have a custom callback self._custom_callback = None # get stuff from the app's config, which may override stuff set above if app is not None: self.init_app(app) def load_secrets(self, app): # Load client_secrets.json to pre-initialize some configuration content = app.config['OIDC_CLIENT_SECRETS'] if isinstance(content, dict): return content else: return _json_loads(open(content, 'r').read()) @property def user_loggedin(self): """ Represents whether the user is currently logged in. Returns: bool: Whether the user is logged in with Flask-OIDC. .. versionadded:: 1.0 """ return g.oidc_id_token is not None def user_getfield(self, field, access_token=None): """ Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0 """ info = self.user_getinfo([field], access_token) return info.get(field) def user_getinfo(self, fields, access_token=None): """ Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0 """ if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def get_refresh_token(self): """Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info def get_cookie_id_token(self): """ .. deprecated:: 1.0 Use :func:`user_getinfo` instead. """ warn('You are using a deprecated function (get_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._get_cookie_id_token() def _get_cookie_id_token(self): try: id_token_cookie = request.cookies.get(current_app.config[ 'OIDC_ID_TOKEN_COOKIE_NAME']) if not id_token_cookie: # Do not error if we were unable to get the cookie. # The user can debug this themselves. return None return self.cookie_serializer.loads(id_token_cookie) except SignatureExpired: logger.debug("Invalid ID token cookie", exc_info=True) return None except BadSignature: logger.info("Signature invalid for ID token cookie", exc_info=True) return None def set_cookie_id_token(self, id_token): """ .. deprecated:: 1.0 """ warn('You are using a deprecated function (set_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._set_cookie_id_token(id_token) def _set_cookie_id_token(self, id_token): """ Cooperates with @after_request to set a new ID token cookie. """ g.oidc_id_token = id_token g.oidc_id_token_dirty = True def _after_request(self, response): """ Set a new ID token cookie if the ID token has changed. """ # This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response def _before_request(self): g.oidc_id_token = None self.authenticate_or_redirect() def authenticate_or_redirect(self): """ Helper function suitable for @app.before_request and @check. Sets g.oidc_id_token to the ID token if the user has successfully authenticated, else returns a redirect object so they can go try to authenticate. :returns: A redirect object, or None if the user is logged in. :rtype: Redirect .. deprecated:: 1.0 Use :func:`require_login` instead. """ # the auth callback and error pages don't need user to be authenticated if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']): return None # retrieve signed ID token cookie id_token = self._get_cookie_id_token() if id_token is None: return self.redirect_to_auth_server(request.url) # ID token expired # when Google is the IdP, this happens after one hour if time.time() >= id_token['exp']: # get credentials from store try: credentials = OAuth2Credentials.from_json( self.credentials_store[id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return self.redirect_to_auth_server(request.url) # refresh and store credentials try: credentials.refresh(httplib2.Http()) if credentials.id_token: id_token = credentials.id_token else: # It is not guaranteed that we will get a new ID Token on # refresh, so if we do not, let's just update the id token # expiry field and reuse the existing ID Token. if credentials.token_expiry is None: logger.debug('Expired ID token, no new expiry. Falling' ' back to assuming 1 hour') id_token['exp'] = time.time() + 3600 else: id_token['exp'] = calendar.timegm( credentials.token_expiry.timetuple()) self.credentials_store[id_token['sub']] = credentials.to_json() self._set_cookie_id_token(id_token) except AccessTokenRefreshError: # Can't refresh. Wipe credentials and redirect user to IdP # for re-authentication. logger.debug("Expired ID token, can't refresh credentials", exc_info=True) del self.credentials_store[id_token['sub']] return self.redirect_to_auth_server(request.url) # make ID token available to views g.oidc_id_token = id_token return None def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """ @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated # Backwards compatibility check = require_login """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ def require_keycloak_role(self, client, role): """ Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper def flow_for_request(self): """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ warn('You are using a deprecated function (flow_for_request). ' 'Please reconsider using this', DeprecationWarning) return self._flow_for_request() def _flow_for_request(self): """ Build a flow with the correct absolute callback URL for this request. :return: """ flow = copy(self.flow) redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI'] if not redirect_uri: flow.redirect_uri = url_for('_oidc_callback', _external=True) else: flow.redirect_uri = redirect_uri return flow def redirect_to_auth_server(self, destination=None, customstate=None): """ Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead. """ if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url) def _is_id_token_valid(self, id_token): """ Check if `id_token` is a current ID token for this application, was issued by the Apps domain we expected, and that the email address has been verified. @see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation """ if not id_token: return False # step 2: check issuer if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']: logger.error('id_token issued by non-trusted issuer: %s' % id_token['iss']) return False if isinstance(id_token['aud'], list): # step 3 for audience list if self.flow.client_id not in id_token['aud']: logger.error('We are not a valid audience') return False # step 4 if 'azp' not in id_token and len(id_token['aud']) > 1: logger.error('Multiple audiences and not authorized party') return False else: # step 3 for single audience if id_token['aud'] != self.flow.client_id: logger.error('We are not the audience') return False # step 5 if 'azp' in id_token and id_token['azp'] != self.flow.client_id: logger.error('Authorized Party is not us') return False # step 6-8: TLS checked # step 9: check exp if int(time.time()) >= int(id_token['exp']): logger.error('Token has expired') return False # step 10: check iat if id_token['iat'] < (time.time() - current_app.config['OIDC_CLOCK_SKEW']): logger.error('Token issued in the past') return False # (not required if using HTTPS?) step 11: check nonce # step 12-13: not requested acr or auth_time, so not needed to test # additional steps specific to our usage if current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] and \ id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: logger.error('Invalid google apps domain') return False if not id_token.get('email_verified', False) and \ current_app.config['OIDC_REQUIRE_VERIFIED_EMAIL']: logger.error('Email not verified') return False return True WRONG_GOOGLE_APPS_DOMAIN = 'WRONG_GOOGLE_APPS_DOMAIN' def custom_callback(self, view_func): """ Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. """ @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback('custom') if plainreturn: return data else: return view_func(data, *args, **kwargs) self._custom_callback = decorated return decorated def _oidc_callback(self): plainreturn, data = self._process_callback('destination') if plainreturn: return data else: return redirect(data) def _process_callback(self, statefield): """ Exchange the auth code for actual credentials, then redirect to the originally requested page. """ # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response def _oidc_error(self, message='Not Authorized', code=None): return (message, 401, { 'Content-Type': 'text/plain', }) def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout self._set_cookie_id_token(None) # Below here is for resource servers to validate tokens def validate_token(self, token, scopes_required=None): """ This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1 """ valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid) def _validate_token(self, token, scopes_required=None): """The actual implementation of validate_token.""" if scopes_required is None: scopes_required = [] scopes_required = set(scopes_required) token_info = None valid_token = False has_required_scopes = False if token: try: token_info = self._get_token_info(token) except Exception as ex: token_info = {'active': False} logger.error('ERROR: Unable to get token info') logger.error(str(ex)) valid_token = token_info.get('active', False) if 'aud' in token_info and \ current_app.config['OIDC_RESOURCE_CHECK_AUD']: valid_audience = False aud = token_info['aud'] clid = self.client_secrets['client_id'] if isinstance(aud, list): valid_audience = clid in aud else: valid_audience = clid == aud if not valid_audience: logger.error('Refused token because of invalid ' 'audience') valid_token = False if valid_token: token_scopes = token_info.get('scope', '').split(' ') else: token_scopes = [] has_required_scopes = scopes_required.issubset( set(token_scopes)) if not has_required_scopes: logger.debug('Token missed required scopes') if (valid_token and has_required_scopes): g.oidc_token_info = token_info return True if not valid_token: return 'Token required but invalid' elif not has_required_scopes: return 'Token does not have required scopes' else: return 'Something went wrong checking your token' def accept_token(self, require_token=False, scopes_required=None, render_errors=True): """ Use this to decorate view functions that should accept OAuth2 tokens, this will most likely apply to API functions. Tokens are accepted as part of the query URL (access_token value) or a POST form value (access_token). Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param require_token: Whether a token is required for the current function. If this is True, we will abort the request if there was no token provided. :type require_token: bool :param scopes_required: List of scopes that are required to be granted by the token before being allowed to call the protected function. :type scopes_required: list :param render_errors: Whether or not to eagerly render error objects as JSON API responses. Set to False to pass the error object back unmodified for later rendering. :type render_errors: callback(obj) or None .. versionadded:: 1.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): token = request.headers['Authorization'].split(None,1)[1].strip() if 'access_token' in request.form: token = request.form['access_token'] elif 'access_token' in request.args: token = request.args['access_token'] validity = self.validate_token(token, scopes_required) if (validity is True) or (not require_token): return view_func(*args, **kwargs) else: response_body = {'error': 'invalid_token', 'error_description': validity} if render_errors: response_body = json.dumps(response_body) return response_body, 401, {'WWW-Authenticate': 'Bearer'} return decorated return wrapper def _get_token_info(self, token): # We hardcode to use client_secret_post, because that's what the Google # oauth2client library defaults to request = {'token': token} headers = {'Content-type': 'application/x-www-form-urlencoded'} hint = current_app.config['OIDC_TOKEN_TYPE_HINT'] if hint != 'none': request['token_type_hint'] = hint auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] if (auth_method == 'client_secret_basic'): basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret']) basic_auth_bytes = bytearray(basic_auth_string, 'utf-8') headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8') elif (auth_method == 'bearer'): headers['Authorization'] = 'Bearer %s' % token elif (auth_method == 'client_secret_post'): request['client_id'] = self.client_secrets['client_id'] if self.client_secrets['client_secret'] is not None: request['client_secret'] = self.client_secrets['client_secret'] resp, content = httplib2.Http().request( self.client_secrets['token_introspection_uri'], 'POST', urlencode(request), headers=headers) # TODO: Cache this reply return _json_loads(content)
puiterwijk/flask-oidc
flask_oidc/__init__.py
OpenIDConnect.user_getfield
python
def user_getfield(self, field, access_token=None): info = self.user_getinfo([field], access_token) return info.get(field)
Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L210-L223
[ "def user_getinfo(self, fields, access_token=None):\n \"\"\"\n Request multiple fields of information about the user.\n\n :param fields: The names of the fields requested.\n :type fields: list\n :returns: The values of the current user for the fields requested.\n The keys are the field names, values are the values of the\n fields as indicated by the OpenID Provider. Note that fields\n that were not provided by the Provider are absent.\n :rtype: dict\n :raises Exception: If the user was not authenticated. Check this with\n user_loggedin.\n\n .. versionadded:: 1.0\n \"\"\"\n if g.oidc_id_token is None and access_token is None:\n raise Exception('User was not authenticated')\n info = {}\n all_info = None\n for field in fields:\n if access_token is None and field in g.oidc_id_token:\n info[field] = g.oidc_id_token[field]\n elif current_app.config['OIDC_USER_INFO_ENABLED']:\n # This was not in the id_token. Let's get user information\n if all_info is None:\n all_info = self._retrieve_userinfo(access_token)\n if all_info is None:\n # To make sure we don't retry for every field\n all_info = {}\n if field in all_info:\n info[field] = all_info[field]\n else:\n # We didn't get this information\n pass\n return info\n" ]
class OpenIDConnect(object): """ The core OpenID Connect client object. """ def __init__(self, app=None, credentials_store=None, http=None, time=None, urandom=None): self.credentials_store = credentials_store\ if credentials_store is not None\ else MemoryCredentials() if http is not None: warn('HTTP argument is deprecated and unused', DeprecationWarning) if time is not None: warn('time argument is deprecated and unused', DeprecationWarning) if urandom is not None: warn('urandom argument is deprecated and unused', DeprecationWarning) # By default, we do not have a custom callback self._custom_callback = None # get stuff from the app's config, which may override stuff set above if app is not None: self.init_app(app) def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass def load_secrets(self, app): # Load client_secrets.json to pre-initialize some configuration content = app.config['OIDC_CLIENT_SECRETS'] if isinstance(content, dict): return content else: return _json_loads(open(content, 'r').read()) @property def user_loggedin(self): """ Represents whether the user is currently logged in. Returns: bool: Whether the user is logged in with Flask-OIDC. .. versionadded:: 1.0 """ return g.oidc_id_token is not None def user_getinfo(self, fields, access_token=None): """ Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0 """ if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def get_refresh_token(self): """Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info def get_cookie_id_token(self): """ .. deprecated:: 1.0 Use :func:`user_getinfo` instead. """ warn('You are using a deprecated function (get_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._get_cookie_id_token() def _get_cookie_id_token(self): try: id_token_cookie = request.cookies.get(current_app.config[ 'OIDC_ID_TOKEN_COOKIE_NAME']) if not id_token_cookie: # Do not error if we were unable to get the cookie. # The user can debug this themselves. return None return self.cookie_serializer.loads(id_token_cookie) except SignatureExpired: logger.debug("Invalid ID token cookie", exc_info=True) return None except BadSignature: logger.info("Signature invalid for ID token cookie", exc_info=True) return None def set_cookie_id_token(self, id_token): """ .. deprecated:: 1.0 """ warn('You are using a deprecated function (set_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._set_cookie_id_token(id_token) def _set_cookie_id_token(self, id_token): """ Cooperates with @after_request to set a new ID token cookie. """ g.oidc_id_token = id_token g.oidc_id_token_dirty = True def _after_request(self, response): """ Set a new ID token cookie if the ID token has changed. """ # This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response def _before_request(self): g.oidc_id_token = None self.authenticate_or_redirect() def authenticate_or_redirect(self): """ Helper function suitable for @app.before_request and @check. Sets g.oidc_id_token to the ID token if the user has successfully authenticated, else returns a redirect object so they can go try to authenticate. :returns: A redirect object, or None if the user is logged in. :rtype: Redirect .. deprecated:: 1.0 Use :func:`require_login` instead. """ # the auth callback and error pages don't need user to be authenticated if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']): return None # retrieve signed ID token cookie id_token = self._get_cookie_id_token() if id_token is None: return self.redirect_to_auth_server(request.url) # ID token expired # when Google is the IdP, this happens after one hour if time.time() >= id_token['exp']: # get credentials from store try: credentials = OAuth2Credentials.from_json( self.credentials_store[id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return self.redirect_to_auth_server(request.url) # refresh and store credentials try: credentials.refresh(httplib2.Http()) if credentials.id_token: id_token = credentials.id_token else: # It is not guaranteed that we will get a new ID Token on # refresh, so if we do not, let's just update the id token # expiry field and reuse the existing ID Token. if credentials.token_expiry is None: logger.debug('Expired ID token, no new expiry. Falling' ' back to assuming 1 hour') id_token['exp'] = time.time() + 3600 else: id_token['exp'] = calendar.timegm( credentials.token_expiry.timetuple()) self.credentials_store[id_token['sub']] = credentials.to_json() self._set_cookie_id_token(id_token) except AccessTokenRefreshError: # Can't refresh. Wipe credentials and redirect user to IdP # for re-authentication. logger.debug("Expired ID token, can't refresh credentials", exc_info=True) del self.credentials_store[id_token['sub']] return self.redirect_to_auth_server(request.url) # make ID token available to views g.oidc_id_token = id_token return None def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """ @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated # Backwards compatibility check = require_login """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ def require_keycloak_role(self, client, role): """ Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper def flow_for_request(self): """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ warn('You are using a deprecated function (flow_for_request). ' 'Please reconsider using this', DeprecationWarning) return self._flow_for_request() def _flow_for_request(self): """ Build a flow with the correct absolute callback URL for this request. :return: """ flow = copy(self.flow) redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI'] if not redirect_uri: flow.redirect_uri = url_for('_oidc_callback', _external=True) else: flow.redirect_uri = redirect_uri return flow def redirect_to_auth_server(self, destination=None, customstate=None): """ Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead. """ if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url) def _is_id_token_valid(self, id_token): """ Check if `id_token` is a current ID token for this application, was issued by the Apps domain we expected, and that the email address has been verified. @see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation """ if not id_token: return False # step 2: check issuer if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']: logger.error('id_token issued by non-trusted issuer: %s' % id_token['iss']) return False if isinstance(id_token['aud'], list): # step 3 for audience list if self.flow.client_id not in id_token['aud']: logger.error('We are not a valid audience') return False # step 4 if 'azp' not in id_token and len(id_token['aud']) > 1: logger.error('Multiple audiences and not authorized party') return False else: # step 3 for single audience if id_token['aud'] != self.flow.client_id: logger.error('We are not the audience') return False # step 5 if 'azp' in id_token and id_token['azp'] != self.flow.client_id: logger.error('Authorized Party is not us') return False # step 6-8: TLS checked # step 9: check exp if int(time.time()) >= int(id_token['exp']): logger.error('Token has expired') return False # step 10: check iat if id_token['iat'] < (time.time() - current_app.config['OIDC_CLOCK_SKEW']): logger.error('Token issued in the past') return False # (not required if using HTTPS?) step 11: check nonce # step 12-13: not requested acr or auth_time, so not needed to test # additional steps specific to our usage if current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] and \ id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: logger.error('Invalid google apps domain') return False if not id_token.get('email_verified', False) and \ current_app.config['OIDC_REQUIRE_VERIFIED_EMAIL']: logger.error('Email not verified') return False return True WRONG_GOOGLE_APPS_DOMAIN = 'WRONG_GOOGLE_APPS_DOMAIN' def custom_callback(self, view_func): """ Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. """ @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback('custom') if plainreturn: return data else: return view_func(data, *args, **kwargs) self._custom_callback = decorated return decorated def _oidc_callback(self): plainreturn, data = self._process_callback('destination') if plainreturn: return data else: return redirect(data) def _process_callback(self, statefield): """ Exchange the auth code for actual credentials, then redirect to the originally requested page. """ # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response def _oidc_error(self, message='Not Authorized', code=None): return (message, 401, { 'Content-Type': 'text/plain', }) def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout self._set_cookie_id_token(None) # Below here is for resource servers to validate tokens def validate_token(self, token, scopes_required=None): """ This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1 """ valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid) def _validate_token(self, token, scopes_required=None): """The actual implementation of validate_token.""" if scopes_required is None: scopes_required = [] scopes_required = set(scopes_required) token_info = None valid_token = False has_required_scopes = False if token: try: token_info = self._get_token_info(token) except Exception as ex: token_info = {'active': False} logger.error('ERROR: Unable to get token info') logger.error(str(ex)) valid_token = token_info.get('active', False) if 'aud' in token_info and \ current_app.config['OIDC_RESOURCE_CHECK_AUD']: valid_audience = False aud = token_info['aud'] clid = self.client_secrets['client_id'] if isinstance(aud, list): valid_audience = clid in aud else: valid_audience = clid == aud if not valid_audience: logger.error('Refused token because of invalid ' 'audience') valid_token = False if valid_token: token_scopes = token_info.get('scope', '').split(' ') else: token_scopes = [] has_required_scopes = scopes_required.issubset( set(token_scopes)) if not has_required_scopes: logger.debug('Token missed required scopes') if (valid_token and has_required_scopes): g.oidc_token_info = token_info return True if not valid_token: return 'Token required but invalid' elif not has_required_scopes: return 'Token does not have required scopes' else: return 'Something went wrong checking your token' def accept_token(self, require_token=False, scopes_required=None, render_errors=True): """ Use this to decorate view functions that should accept OAuth2 tokens, this will most likely apply to API functions. Tokens are accepted as part of the query URL (access_token value) or a POST form value (access_token). Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param require_token: Whether a token is required for the current function. If this is True, we will abort the request if there was no token provided. :type require_token: bool :param scopes_required: List of scopes that are required to be granted by the token before being allowed to call the protected function. :type scopes_required: list :param render_errors: Whether or not to eagerly render error objects as JSON API responses. Set to False to pass the error object back unmodified for later rendering. :type render_errors: callback(obj) or None .. versionadded:: 1.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): token = request.headers['Authorization'].split(None,1)[1].strip() if 'access_token' in request.form: token = request.form['access_token'] elif 'access_token' in request.args: token = request.args['access_token'] validity = self.validate_token(token, scopes_required) if (validity is True) or (not require_token): return view_func(*args, **kwargs) else: response_body = {'error': 'invalid_token', 'error_description': validity} if render_errors: response_body = json.dumps(response_body) return response_body, 401, {'WWW-Authenticate': 'Bearer'} return decorated return wrapper def _get_token_info(self, token): # We hardcode to use client_secret_post, because that's what the Google # oauth2client library defaults to request = {'token': token} headers = {'Content-type': 'application/x-www-form-urlencoded'} hint = current_app.config['OIDC_TOKEN_TYPE_HINT'] if hint != 'none': request['token_type_hint'] = hint auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] if (auth_method == 'client_secret_basic'): basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret']) basic_auth_bytes = bytearray(basic_auth_string, 'utf-8') headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8') elif (auth_method == 'bearer'): headers['Authorization'] = 'Bearer %s' % token elif (auth_method == 'client_secret_post'): request['client_id'] = self.client_secrets['client_id'] if self.client_secrets['client_secret'] is not None: request['client_secret'] = self.client_secrets['client_secret'] resp, content = httplib2.Http().request( self.client_secrets['token_introspection_uri'], 'POST', urlencode(request), headers=headers) # TODO: Cache this reply return _json_loads(content)
puiterwijk/flask-oidc
flask_oidc/__init__.py
OpenIDConnect.user_getinfo
python
def user_getinfo(self, fields, access_token=None): if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info
Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L225-L260
[ "def _retrieve_userinfo(self, access_token=None):\n \"\"\"\n Requests extra user information from the Provider's UserInfo and\n returns the result.\n\n :returns: The contents of the UserInfo endpoint.\n :rtype: dict\n \"\"\"\n if 'userinfo_uri' not in self.client_secrets:\n logger.debug('Userinfo uri not specified')\n raise AssertionError('UserInfo URI not specified')\n\n # Cache the info from this request\n if '_oidc_userinfo' in g:\n return g._oidc_userinfo\n\n http = httplib2.Http()\n if access_token is None:\n try:\n credentials = OAuth2Credentials.from_json(\n self.credentials_store[g.oidc_id_token['sub']])\n except KeyError:\n logger.debug(\"Expired ID token, credentials missing\",\n exc_info=True)\n return None\n credentials.authorize(http)\n resp, content = http.request(self.client_secrets['userinfo_uri'])\n else:\n # We have been manually overriden with an access token\n resp, content = http.request(\n self.client_secrets['userinfo_uri'],\n \"POST\",\n body=urlencode({\"access_token\": access_token}),\n headers={'Content-Type': 'application/x-www-form-urlencoded'})\n\n logger.debug('Retrieved user info: %s' % content)\n info = _json_loads(content)\n\n g._oidc_userinfo = info\n\n return info\n" ]
class OpenIDConnect(object): """ The core OpenID Connect client object. """ def __init__(self, app=None, credentials_store=None, http=None, time=None, urandom=None): self.credentials_store = credentials_store\ if credentials_store is not None\ else MemoryCredentials() if http is not None: warn('HTTP argument is deprecated and unused', DeprecationWarning) if time is not None: warn('time argument is deprecated and unused', DeprecationWarning) if urandom is not None: warn('urandom argument is deprecated and unused', DeprecationWarning) # By default, we do not have a custom callback self._custom_callback = None # get stuff from the app's config, which may override stuff set above if app is not None: self.init_app(app) def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass def load_secrets(self, app): # Load client_secrets.json to pre-initialize some configuration content = app.config['OIDC_CLIENT_SECRETS'] if isinstance(content, dict): return content else: return _json_loads(open(content, 'r').read()) @property def user_loggedin(self): """ Represents whether the user is currently logged in. Returns: bool: Whether the user is logged in with Flask-OIDC. .. versionadded:: 1.0 """ return g.oidc_id_token is not None def user_getfield(self, field, access_token=None): """ Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0 """ info = self.user_getinfo([field], access_token) return info.get(field) def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def get_refresh_token(self): """Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info def get_cookie_id_token(self): """ .. deprecated:: 1.0 Use :func:`user_getinfo` instead. """ warn('You are using a deprecated function (get_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._get_cookie_id_token() def _get_cookie_id_token(self): try: id_token_cookie = request.cookies.get(current_app.config[ 'OIDC_ID_TOKEN_COOKIE_NAME']) if not id_token_cookie: # Do not error if we were unable to get the cookie. # The user can debug this themselves. return None return self.cookie_serializer.loads(id_token_cookie) except SignatureExpired: logger.debug("Invalid ID token cookie", exc_info=True) return None except BadSignature: logger.info("Signature invalid for ID token cookie", exc_info=True) return None def set_cookie_id_token(self, id_token): """ .. deprecated:: 1.0 """ warn('You are using a deprecated function (set_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._set_cookie_id_token(id_token) def _set_cookie_id_token(self, id_token): """ Cooperates with @after_request to set a new ID token cookie. """ g.oidc_id_token = id_token g.oidc_id_token_dirty = True def _after_request(self, response): """ Set a new ID token cookie if the ID token has changed. """ # This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response def _before_request(self): g.oidc_id_token = None self.authenticate_or_redirect() def authenticate_or_redirect(self): """ Helper function suitable for @app.before_request and @check. Sets g.oidc_id_token to the ID token if the user has successfully authenticated, else returns a redirect object so they can go try to authenticate. :returns: A redirect object, or None if the user is logged in. :rtype: Redirect .. deprecated:: 1.0 Use :func:`require_login` instead. """ # the auth callback and error pages don't need user to be authenticated if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']): return None # retrieve signed ID token cookie id_token = self._get_cookie_id_token() if id_token is None: return self.redirect_to_auth_server(request.url) # ID token expired # when Google is the IdP, this happens after one hour if time.time() >= id_token['exp']: # get credentials from store try: credentials = OAuth2Credentials.from_json( self.credentials_store[id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return self.redirect_to_auth_server(request.url) # refresh and store credentials try: credentials.refresh(httplib2.Http()) if credentials.id_token: id_token = credentials.id_token else: # It is not guaranteed that we will get a new ID Token on # refresh, so if we do not, let's just update the id token # expiry field and reuse the existing ID Token. if credentials.token_expiry is None: logger.debug('Expired ID token, no new expiry. Falling' ' back to assuming 1 hour') id_token['exp'] = time.time() + 3600 else: id_token['exp'] = calendar.timegm( credentials.token_expiry.timetuple()) self.credentials_store[id_token['sub']] = credentials.to_json() self._set_cookie_id_token(id_token) except AccessTokenRefreshError: # Can't refresh. Wipe credentials and redirect user to IdP # for re-authentication. logger.debug("Expired ID token, can't refresh credentials", exc_info=True) del self.credentials_store[id_token['sub']] return self.redirect_to_auth_server(request.url) # make ID token available to views g.oidc_id_token = id_token return None def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """ @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated # Backwards compatibility check = require_login """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ def require_keycloak_role(self, client, role): """ Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper def flow_for_request(self): """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ warn('You are using a deprecated function (flow_for_request). ' 'Please reconsider using this', DeprecationWarning) return self._flow_for_request() def _flow_for_request(self): """ Build a flow with the correct absolute callback URL for this request. :return: """ flow = copy(self.flow) redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI'] if not redirect_uri: flow.redirect_uri = url_for('_oidc_callback', _external=True) else: flow.redirect_uri = redirect_uri return flow def redirect_to_auth_server(self, destination=None, customstate=None): """ Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead. """ if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url) def _is_id_token_valid(self, id_token): """ Check if `id_token` is a current ID token for this application, was issued by the Apps domain we expected, and that the email address has been verified. @see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation """ if not id_token: return False # step 2: check issuer if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']: logger.error('id_token issued by non-trusted issuer: %s' % id_token['iss']) return False if isinstance(id_token['aud'], list): # step 3 for audience list if self.flow.client_id not in id_token['aud']: logger.error('We are not a valid audience') return False # step 4 if 'azp' not in id_token and len(id_token['aud']) > 1: logger.error('Multiple audiences and not authorized party') return False else: # step 3 for single audience if id_token['aud'] != self.flow.client_id: logger.error('We are not the audience') return False # step 5 if 'azp' in id_token and id_token['azp'] != self.flow.client_id: logger.error('Authorized Party is not us') return False # step 6-8: TLS checked # step 9: check exp if int(time.time()) >= int(id_token['exp']): logger.error('Token has expired') return False # step 10: check iat if id_token['iat'] < (time.time() - current_app.config['OIDC_CLOCK_SKEW']): logger.error('Token issued in the past') return False # (not required if using HTTPS?) step 11: check nonce # step 12-13: not requested acr or auth_time, so not needed to test # additional steps specific to our usage if current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] and \ id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: logger.error('Invalid google apps domain') return False if not id_token.get('email_verified', False) and \ current_app.config['OIDC_REQUIRE_VERIFIED_EMAIL']: logger.error('Email not verified') return False return True WRONG_GOOGLE_APPS_DOMAIN = 'WRONG_GOOGLE_APPS_DOMAIN' def custom_callback(self, view_func): """ Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. """ @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback('custom') if plainreturn: return data else: return view_func(data, *args, **kwargs) self._custom_callback = decorated return decorated def _oidc_callback(self): plainreturn, data = self._process_callback('destination') if plainreturn: return data else: return redirect(data) def _process_callback(self, statefield): """ Exchange the auth code for actual credentials, then redirect to the originally requested page. """ # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response def _oidc_error(self, message='Not Authorized', code=None): return (message, 401, { 'Content-Type': 'text/plain', }) def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout self._set_cookie_id_token(None) # Below here is for resource servers to validate tokens def validate_token(self, token, scopes_required=None): """ This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1 """ valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid) def _validate_token(self, token, scopes_required=None): """The actual implementation of validate_token.""" if scopes_required is None: scopes_required = [] scopes_required = set(scopes_required) token_info = None valid_token = False has_required_scopes = False if token: try: token_info = self._get_token_info(token) except Exception as ex: token_info = {'active': False} logger.error('ERROR: Unable to get token info') logger.error(str(ex)) valid_token = token_info.get('active', False) if 'aud' in token_info and \ current_app.config['OIDC_RESOURCE_CHECK_AUD']: valid_audience = False aud = token_info['aud'] clid = self.client_secrets['client_id'] if isinstance(aud, list): valid_audience = clid in aud else: valid_audience = clid == aud if not valid_audience: logger.error('Refused token because of invalid ' 'audience') valid_token = False if valid_token: token_scopes = token_info.get('scope', '').split(' ') else: token_scopes = [] has_required_scopes = scopes_required.issubset( set(token_scopes)) if not has_required_scopes: logger.debug('Token missed required scopes') if (valid_token and has_required_scopes): g.oidc_token_info = token_info return True if not valid_token: return 'Token required but invalid' elif not has_required_scopes: return 'Token does not have required scopes' else: return 'Something went wrong checking your token' def accept_token(self, require_token=False, scopes_required=None, render_errors=True): """ Use this to decorate view functions that should accept OAuth2 tokens, this will most likely apply to API functions. Tokens are accepted as part of the query URL (access_token value) or a POST form value (access_token). Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param require_token: Whether a token is required for the current function. If this is True, we will abort the request if there was no token provided. :type require_token: bool :param scopes_required: List of scopes that are required to be granted by the token before being allowed to call the protected function. :type scopes_required: list :param render_errors: Whether or not to eagerly render error objects as JSON API responses. Set to False to pass the error object back unmodified for later rendering. :type render_errors: callback(obj) or None .. versionadded:: 1.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): token = request.headers['Authorization'].split(None,1)[1].strip() if 'access_token' in request.form: token = request.form['access_token'] elif 'access_token' in request.args: token = request.args['access_token'] validity = self.validate_token(token, scopes_required) if (validity is True) or (not require_token): return view_func(*args, **kwargs) else: response_body = {'error': 'invalid_token', 'error_description': validity} if render_errors: response_body = json.dumps(response_body) return response_body, 401, {'WWW-Authenticate': 'Bearer'} return decorated return wrapper def _get_token_info(self, token): # We hardcode to use client_secret_post, because that's what the Google # oauth2client library defaults to request = {'token': token} headers = {'Content-type': 'application/x-www-form-urlencoded'} hint = current_app.config['OIDC_TOKEN_TYPE_HINT'] if hint != 'none': request['token_type_hint'] = hint auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] if (auth_method == 'client_secret_basic'): basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret']) basic_auth_bytes = bytearray(basic_auth_string, 'utf-8') headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8') elif (auth_method == 'bearer'): headers['Authorization'] = 'Bearer %s' % token elif (auth_method == 'client_secret_post'): request['client_id'] = self.client_secrets['client_id'] if self.client_secrets['client_secret'] is not None: request['client_secret'] = self.client_secrets['client_secret'] resp, content = httplib2.Http().request( self.client_secrets['token_introspection_uri'], 'POST', urlencode(request), headers=headers) # TODO: Cache this reply return _json_loads(content)
puiterwijk/flask-oidc
flask_oidc/__init__.py
OpenIDConnect.get_access_token
python
def get_access_token(self): try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None
Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L262-L277
null
class OpenIDConnect(object): """ The core OpenID Connect client object. """ def __init__(self, app=None, credentials_store=None, http=None, time=None, urandom=None): self.credentials_store = credentials_store\ if credentials_store is not None\ else MemoryCredentials() if http is not None: warn('HTTP argument is deprecated and unused', DeprecationWarning) if time is not None: warn('time argument is deprecated and unused', DeprecationWarning) if urandom is not None: warn('urandom argument is deprecated and unused', DeprecationWarning) # By default, we do not have a custom callback self._custom_callback = None # get stuff from the app's config, which may override stuff set above if app is not None: self.init_app(app) def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass def load_secrets(self, app): # Load client_secrets.json to pre-initialize some configuration content = app.config['OIDC_CLIENT_SECRETS'] if isinstance(content, dict): return content else: return _json_loads(open(content, 'r').read()) @property def user_loggedin(self): """ Represents whether the user is currently logged in. Returns: bool: Whether the user is logged in with Flask-OIDC. .. versionadded:: 1.0 """ return g.oidc_id_token is not None def user_getfield(self, field, access_token=None): """ Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0 """ info = self.user_getinfo([field], access_token) return info.get(field) def user_getinfo(self, fields, access_token=None): """ Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0 """ if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info def get_refresh_token(self): """Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info def get_cookie_id_token(self): """ .. deprecated:: 1.0 Use :func:`user_getinfo` instead. """ warn('You are using a deprecated function (get_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._get_cookie_id_token() def _get_cookie_id_token(self): try: id_token_cookie = request.cookies.get(current_app.config[ 'OIDC_ID_TOKEN_COOKIE_NAME']) if not id_token_cookie: # Do not error if we were unable to get the cookie. # The user can debug this themselves. return None return self.cookie_serializer.loads(id_token_cookie) except SignatureExpired: logger.debug("Invalid ID token cookie", exc_info=True) return None except BadSignature: logger.info("Signature invalid for ID token cookie", exc_info=True) return None def set_cookie_id_token(self, id_token): """ .. deprecated:: 1.0 """ warn('You are using a deprecated function (set_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._set_cookie_id_token(id_token) def _set_cookie_id_token(self, id_token): """ Cooperates with @after_request to set a new ID token cookie. """ g.oidc_id_token = id_token g.oidc_id_token_dirty = True def _after_request(self, response): """ Set a new ID token cookie if the ID token has changed. """ # This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response def _before_request(self): g.oidc_id_token = None self.authenticate_or_redirect() def authenticate_or_redirect(self): """ Helper function suitable for @app.before_request and @check. Sets g.oidc_id_token to the ID token if the user has successfully authenticated, else returns a redirect object so they can go try to authenticate. :returns: A redirect object, or None if the user is logged in. :rtype: Redirect .. deprecated:: 1.0 Use :func:`require_login` instead. """ # the auth callback and error pages don't need user to be authenticated if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']): return None # retrieve signed ID token cookie id_token = self._get_cookie_id_token() if id_token is None: return self.redirect_to_auth_server(request.url) # ID token expired # when Google is the IdP, this happens after one hour if time.time() >= id_token['exp']: # get credentials from store try: credentials = OAuth2Credentials.from_json( self.credentials_store[id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return self.redirect_to_auth_server(request.url) # refresh and store credentials try: credentials.refresh(httplib2.Http()) if credentials.id_token: id_token = credentials.id_token else: # It is not guaranteed that we will get a new ID Token on # refresh, so if we do not, let's just update the id token # expiry field and reuse the existing ID Token. if credentials.token_expiry is None: logger.debug('Expired ID token, no new expiry. Falling' ' back to assuming 1 hour') id_token['exp'] = time.time() + 3600 else: id_token['exp'] = calendar.timegm( credentials.token_expiry.timetuple()) self.credentials_store[id_token['sub']] = credentials.to_json() self._set_cookie_id_token(id_token) except AccessTokenRefreshError: # Can't refresh. Wipe credentials and redirect user to IdP # for re-authentication. logger.debug("Expired ID token, can't refresh credentials", exc_info=True) del self.credentials_store[id_token['sub']] return self.redirect_to_auth_server(request.url) # make ID token available to views g.oidc_id_token = id_token return None def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """ @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated # Backwards compatibility check = require_login """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ def require_keycloak_role(self, client, role): """ Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper def flow_for_request(self): """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ warn('You are using a deprecated function (flow_for_request). ' 'Please reconsider using this', DeprecationWarning) return self._flow_for_request() def _flow_for_request(self): """ Build a flow with the correct absolute callback URL for this request. :return: """ flow = copy(self.flow) redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI'] if not redirect_uri: flow.redirect_uri = url_for('_oidc_callback', _external=True) else: flow.redirect_uri = redirect_uri return flow def redirect_to_auth_server(self, destination=None, customstate=None): """ Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead. """ if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url) def _is_id_token_valid(self, id_token): """ Check if `id_token` is a current ID token for this application, was issued by the Apps domain we expected, and that the email address has been verified. @see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation """ if not id_token: return False # step 2: check issuer if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']: logger.error('id_token issued by non-trusted issuer: %s' % id_token['iss']) return False if isinstance(id_token['aud'], list): # step 3 for audience list if self.flow.client_id not in id_token['aud']: logger.error('We are not a valid audience') return False # step 4 if 'azp' not in id_token and len(id_token['aud']) > 1: logger.error('Multiple audiences and not authorized party') return False else: # step 3 for single audience if id_token['aud'] != self.flow.client_id: logger.error('We are not the audience') return False # step 5 if 'azp' in id_token and id_token['azp'] != self.flow.client_id: logger.error('Authorized Party is not us') return False # step 6-8: TLS checked # step 9: check exp if int(time.time()) >= int(id_token['exp']): logger.error('Token has expired') return False # step 10: check iat if id_token['iat'] < (time.time() - current_app.config['OIDC_CLOCK_SKEW']): logger.error('Token issued in the past') return False # (not required if using HTTPS?) step 11: check nonce # step 12-13: not requested acr or auth_time, so not needed to test # additional steps specific to our usage if current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] and \ id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: logger.error('Invalid google apps domain') return False if not id_token.get('email_verified', False) and \ current_app.config['OIDC_REQUIRE_VERIFIED_EMAIL']: logger.error('Email not verified') return False return True WRONG_GOOGLE_APPS_DOMAIN = 'WRONG_GOOGLE_APPS_DOMAIN' def custom_callback(self, view_func): """ Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. """ @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback('custom') if plainreturn: return data else: return view_func(data, *args, **kwargs) self._custom_callback = decorated return decorated def _oidc_callback(self): plainreturn, data = self._process_callback('destination') if plainreturn: return data else: return redirect(data) def _process_callback(self, statefield): """ Exchange the auth code for actual credentials, then redirect to the originally requested page. """ # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response def _oidc_error(self, message='Not Authorized', code=None): return (message, 401, { 'Content-Type': 'text/plain', }) def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout self._set_cookie_id_token(None) # Below here is for resource servers to validate tokens def validate_token(self, token, scopes_required=None): """ This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1 """ valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid) def _validate_token(self, token, scopes_required=None): """The actual implementation of validate_token.""" if scopes_required is None: scopes_required = [] scopes_required = set(scopes_required) token_info = None valid_token = False has_required_scopes = False if token: try: token_info = self._get_token_info(token) except Exception as ex: token_info = {'active': False} logger.error('ERROR: Unable to get token info') logger.error(str(ex)) valid_token = token_info.get('active', False) if 'aud' in token_info and \ current_app.config['OIDC_RESOURCE_CHECK_AUD']: valid_audience = False aud = token_info['aud'] clid = self.client_secrets['client_id'] if isinstance(aud, list): valid_audience = clid in aud else: valid_audience = clid == aud if not valid_audience: logger.error('Refused token because of invalid ' 'audience') valid_token = False if valid_token: token_scopes = token_info.get('scope', '').split(' ') else: token_scopes = [] has_required_scopes = scopes_required.issubset( set(token_scopes)) if not has_required_scopes: logger.debug('Token missed required scopes') if (valid_token and has_required_scopes): g.oidc_token_info = token_info return True if not valid_token: return 'Token required but invalid' elif not has_required_scopes: return 'Token does not have required scopes' else: return 'Something went wrong checking your token' def accept_token(self, require_token=False, scopes_required=None, render_errors=True): """ Use this to decorate view functions that should accept OAuth2 tokens, this will most likely apply to API functions. Tokens are accepted as part of the query URL (access_token value) or a POST form value (access_token). Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param require_token: Whether a token is required for the current function. If this is True, we will abort the request if there was no token provided. :type require_token: bool :param scopes_required: List of scopes that are required to be granted by the token before being allowed to call the protected function. :type scopes_required: list :param render_errors: Whether or not to eagerly render error objects as JSON API responses. Set to False to pass the error object back unmodified for later rendering. :type render_errors: callback(obj) or None .. versionadded:: 1.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): token = request.headers['Authorization'].split(None,1)[1].strip() if 'access_token' in request.form: token = request.form['access_token'] elif 'access_token' in request.args: token = request.args['access_token'] validity = self.validate_token(token, scopes_required) if (validity is True) or (not require_token): return view_func(*args, **kwargs) else: response_body = {'error': 'invalid_token', 'error_description': validity} if render_errors: response_body = json.dumps(response_body) return response_body, 401, {'WWW-Authenticate': 'Bearer'} return decorated return wrapper def _get_token_info(self, token): # We hardcode to use client_secret_post, because that's what the Google # oauth2client library defaults to request = {'token': token} headers = {'Content-type': 'application/x-www-form-urlencoded'} hint = current_app.config['OIDC_TOKEN_TYPE_HINT'] if hint != 'none': request['token_type_hint'] = hint auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] if (auth_method == 'client_secret_basic'): basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret']) basic_auth_bytes = bytearray(basic_auth_string, 'utf-8') headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8') elif (auth_method == 'bearer'): headers['Authorization'] = 'Bearer %s' % token elif (auth_method == 'client_secret_post'): request['client_id'] = self.client_secrets['client_id'] if self.client_secrets['client_secret'] is not None: request['client_secret'] = self.client_secrets['client_secret'] resp, content = httplib2.Http().request( self.client_secrets['token_introspection_uri'], 'POST', urlencode(request), headers=headers) # TODO: Cache this reply return _json_loads(content)
puiterwijk/flask-oidc
flask_oidc/__init__.py
OpenIDConnect.get_refresh_token
python
def get_refresh_token(self): try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None
Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L279-L294
null
class OpenIDConnect(object): """ The core OpenID Connect client object. """ def __init__(self, app=None, credentials_store=None, http=None, time=None, urandom=None): self.credentials_store = credentials_store\ if credentials_store is not None\ else MemoryCredentials() if http is not None: warn('HTTP argument is deprecated and unused', DeprecationWarning) if time is not None: warn('time argument is deprecated and unused', DeprecationWarning) if urandom is not None: warn('urandom argument is deprecated and unused', DeprecationWarning) # By default, we do not have a custom callback self._custom_callback = None # get stuff from the app's config, which may override stuff set above if app is not None: self.init_app(app) def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass def load_secrets(self, app): # Load client_secrets.json to pre-initialize some configuration content = app.config['OIDC_CLIENT_SECRETS'] if isinstance(content, dict): return content else: return _json_loads(open(content, 'r').read()) @property def user_loggedin(self): """ Represents whether the user is currently logged in. Returns: bool: Whether the user is logged in with Flask-OIDC. .. versionadded:: 1.0 """ return g.oidc_id_token is not None def user_getfield(self, field, access_token=None): """ Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0 """ info = self.user_getinfo([field], access_token) return info.get(field) def user_getinfo(self, fields, access_token=None): """ Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0 """ if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info def get_cookie_id_token(self): """ .. deprecated:: 1.0 Use :func:`user_getinfo` instead. """ warn('You are using a deprecated function (get_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._get_cookie_id_token() def _get_cookie_id_token(self): try: id_token_cookie = request.cookies.get(current_app.config[ 'OIDC_ID_TOKEN_COOKIE_NAME']) if not id_token_cookie: # Do not error if we were unable to get the cookie. # The user can debug this themselves. return None return self.cookie_serializer.loads(id_token_cookie) except SignatureExpired: logger.debug("Invalid ID token cookie", exc_info=True) return None except BadSignature: logger.info("Signature invalid for ID token cookie", exc_info=True) return None def set_cookie_id_token(self, id_token): """ .. deprecated:: 1.0 """ warn('You are using a deprecated function (set_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._set_cookie_id_token(id_token) def _set_cookie_id_token(self, id_token): """ Cooperates with @after_request to set a new ID token cookie. """ g.oidc_id_token = id_token g.oidc_id_token_dirty = True def _after_request(self, response): """ Set a new ID token cookie if the ID token has changed. """ # This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response def _before_request(self): g.oidc_id_token = None self.authenticate_or_redirect() def authenticate_or_redirect(self): """ Helper function suitable for @app.before_request and @check. Sets g.oidc_id_token to the ID token if the user has successfully authenticated, else returns a redirect object so they can go try to authenticate. :returns: A redirect object, or None if the user is logged in. :rtype: Redirect .. deprecated:: 1.0 Use :func:`require_login` instead. """ # the auth callback and error pages don't need user to be authenticated if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']): return None # retrieve signed ID token cookie id_token = self._get_cookie_id_token() if id_token is None: return self.redirect_to_auth_server(request.url) # ID token expired # when Google is the IdP, this happens after one hour if time.time() >= id_token['exp']: # get credentials from store try: credentials = OAuth2Credentials.from_json( self.credentials_store[id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return self.redirect_to_auth_server(request.url) # refresh and store credentials try: credentials.refresh(httplib2.Http()) if credentials.id_token: id_token = credentials.id_token else: # It is not guaranteed that we will get a new ID Token on # refresh, so if we do not, let's just update the id token # expiry field and reuse the existing ID Token. if credentials.token_expiry is None: logger.debug('Expired ID token, no new expiry. Falling' ' back to assuming 1 hour') id_token['exp'] = time.time() + 3600 else: id_token['exp'] = calendar.timegm( credentials.token_expiry.timetuple()) self.credentials_store[id_token['sub']] = credentials.to_json() self._set_cookie_id_token(id_token) except AccessTokenRefreshError: # Can't refresh. Wipe credentials and redirect user to IdP # for re-authentication. logger.debug("Expired ID token, can't refresh credentials", exc_info=True) del self.credentials_store[id_token['sub']] return self.redirect_to_auth_server(request.url) # make ID token available to views g.oidc_id_token = id_token return None def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """ @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated # Backwards compatibility check = require_login """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ def require_keycloak_role(self, client, role): """ Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper def flow_for_request(self): """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ warn('You are using a deprecated function (flow_for_request). ' 'Please reconsider using this', DeprecationWarning) return self._flow_for_request() def _flow_for_request(self): """ Build a flow with the correct absolute callback URL for this request. :return: """ flow = copy(self.flow) redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI'] if not redirect_uri: flow.redirect_uri = url_for('_oidc_callback', _external=True) else: flow.redirect_uri = redirect_uri return flow def redirect_to_auth_server(self, destination=None, customstate=None): """ Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead. """ if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url) def _is_id_token_valid(self, id_token): """ Check if `id_token` is a current ID token for this application, was issued by the Apps domain we expected, and that the email address has been verified. @see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation """ if not id_token: return False # step 2: check issuer if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']: logger.error('id_token issued by non-trusted issuer: %s' % id_token['iss']) return False if isinstance(id_token['aud'], list): # step 3 for audience list if self.flow.client_id not in id_token['aud']: logger.error('We are not a valid audience') return False # step 4 if 'azp' not in id_token and len(id_token['aud']) > 1: logger.error('Multiple audiences and not authorized party') return False else: # step 3 for single audience if id_token['aud'] != self.flow.client_id: logger.error('We are not the audience') return False # step 5 if 'azp' in id_token and id_token['azp'] != self.flow.client_id: logger.error('Authorized Party is not us') return False # step 6-8: TLS checked # step 9: check exp if int(time.time()) >= int(id_token['exp']): logger.error('Token has expired') return False # step 10: check iat if id_token['iat'] < (time.time() - current_app.config['OIDC_CLOCK_SKEW']): logger.error('Token issued in the past') return False # (not required if using HTTPS?) step 11: check nonce # step 12-13: not requested acr or auth_time, so not needed to test # additional steps specific to our usage if current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] and \ id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: logger.error('Invalid google apps domain') return False if not id_token.get('email_verified', False) and \ current_app.config['OIDC_REQUIRE_VERIFIED_EMAIL']: logger.error('Email not verified') return False return True WRONG_GOOGLE_APPS_DOMAIN = 'WRONG_GOOGLE_APPS_DOMAIN' def custom_callback(self, view_func): """ Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. """ @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback('custom') if plainreturn: return data else: return view_func(data, *args, **kwargs) self._custom_callback = decorated return decorated def _oidc_callback(self): plainreturn, data = self._process_callback('destination') if plainreturn: return data else: return redirect(data) def _process_callback(self, statefield): """ Exchange the auth code for actual credentials, then redirect to the originally requested page. """ # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response def _oidc_error(self, message='Not Authorized', code=None): return (message, 401, { 'Content-Type': 'text/plain', }) def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout self._set_cookie_id_token(None) # Below here is for resource servers to validate tokens def validate_token(self, token, scopes_required=None): """ This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1 """ valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid) def _validate_token(self, token, scopes_required=None): """The actual implementation of validate_token.""" if scopes_required is None: scopes_required = [] scopes_required = set(scopes_required) token_info = None valid_token = False has_required_scopes = False if token: try: token_info = self._get_token_info(token) except Exception as ex: token_info = {'active': False} logger.error('ERROR: Unable to get token info') logger.error(str(ex)) valid_token = token_info.get('active', False) if 'aud' in token_info and \ current_app.config['OIDC_RESOURCE_CHECK_AUD']: valid_audience = False aud = token_info['aud'] clid = self.client_secrets['client_id'] if isinstance(aud, list): valid_audience = clid in aud else: valid_audience = clid == aud if not valid_audience: logger.error('Refused token because of invalid ' 'audience') valid_token = False if valid_token: token_scopes = token_info.get('scope', '').split(' ') else: token_scopes = [] has_required_scopes = scopes_required.issubset( set(token_scopes)) if not has_required_scopes: logger.debug('Token missed required scopes') if (valid_token and has_required_scopes): g.oidc_token_info = token_info return True if not valid_token: return 'Token required but invalid' elif not has_required_scopes: return 'Token does not have required scopes' else: return 'Something went wrong checking your token' def accept_token(self, require_token=False, scopes_required=None, render_errors=True): """ Use this to decorate view functions that should accept OAuth2 tokens, this will most likely apply to API functions. Tokens are accepted as part of the query URL (access_token value) or a POST form value (access_token). Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param require_token: Whether a token is required for the current function. If this is True, we will abort the request if there was no token provided. :type require_token: bool :param scopes_required: List of scopes that are required to be granted by the token before being allowed to call the protected function. :type scopes_required: list :param render_errors: Whether or not to eagerly render error objects as JSON API responses. Set to False to pass the error object back unmodified for later rendering. :type render_errors: callback(obj) or None .. versionadded:: 1.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): token = request.headers['Authorization'].split(None,1)[1].strip() if 'access_token' in request.form: token = request.form['access_token'] elif 'access_token' in request.args: token = request.args['access_token'] validity = self.validate_token(token, scopes_required) if (validity is True) or (not require_token): return view_func(*args, **kwargs) else: response_body = {'error': 'invalid_token', 'error_description': validity} if render_errors: response_body = json.dumps(response_body) return response_body, 401, {'WWW-Authenticate': 'Bearer'} return decorated return wrapper def _get_token_info(self, token): # We hardcode to use client_secret_post, because that's what the Google # oauth2client library defaults to request = {'token': token} headers = {'Content-type': 'application/x-www-form-urlencoded'} hint = current_app.config['OIDC_TOKEN_TYPE_HINT'] if hint != 'none': request['token_type_hint'] = hint auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] if (auth_method == 'client_secret_basic'): basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret']) basic_auth_bytes = bytearray(basic_auth_string, 'utf-8') headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8') elif (auth_method == 'bearer'): headers['Authorization'] = 'Bearer %s' % token elif (auth_method == 'client_secret_post'): request['client_id'] = self.client_secrets['client_id'] if self.client_secrets['client_secret'] is not None: request['client_secret'] = self.client_secrets['client_secret'] resp, content = httplib2.Http().request( self.client_secrets['token_introspection_uri'], 'POST', urlencode(request), headers=headers) # TODO: Cache this reply return _json_loads(content)
puiterwijk/flask-oidc
flask_oidc/__init__.py
OpenIDConnect._retrieve_userinfo
python
def _retrieve_userinfo(self, access_token=None): if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info
Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L296-L336
[ "def _json_loads(content):\n if not isinstance(content, str):\n content = content.decode('utf-8')\n return json.loads(content)\n" ]
class OpenIDConnect(object): """ The core OpenID Connect client object. """ def __init__(self, app=None, credentials_store=None, http=None, time=None, urandom=None): self.credentials_store = credentials_store\ if credentials_store is not None\ else MemoryCredentials() if http is not None: warn('HTTP argument is deprecated and unused', DeprecationWarning) if time is not None: warn('time argument is deprecated and unused', DeprecationWarning) if urandom is not None: warn('urandom argument is deprecated and unused', DeprecationWarning) # By default, we do not have a custom callback self._custom_callback = None # get stuff from the app's config, which may override stuff set above if app is not None: self.init_app(app) def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass def load_secrets(self, app): # Load client_secrets.json to pre-initialize some configuration content = app.config['OIDC_CLIENT_SECRETS'] if isinstance(content, dict): return content else: return _json_loads(open(content, 'r').read()) @property def user_loggedin(self): """ Represents whether the user is currently logged in. Returns: bool: Whether the user is logged in with Flask-OIDC. .. versionadded:: 1.0 """ return g.oidc_id_token is not None def user_getfield(self, field, access_token=None): """ Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0 """ info = self.user_getinfo([field], access_token) return info.get(field) def user_getinfo(self, fields, access_token=None): """ Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0 """ if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def get_refresh_token(self): """Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def get_cookie_id_token(self): """ .. deprecated:: 1.0 Use :func:`user_getinfo` instead. """ warn('You are using a deprecated function (get_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._get_cookie_id_token() def _get_cookie_id_token(self): try: id_token_cookie = request.cookies.get(current_app.config[ 'OIDC_ID_TOKEN_COOKIE_NAME']) if not id_token_cookie: # Do not error if we were unable to get the cookie. # The user can debug this themselves. return None return self.cookie_serializer.loads(id_token_cookie) except SignatureExpired: logger.debug("Invalid ID token cookie", exc_info=True) return None except BadSignature: logger.info("Signature invalid for ID token cookie", exc_info=True) return None def set_cookie_id_token(self, id_token): """ .. deprecated:: 1.0 """ warn('You are using a deprecated function (set_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._set_cookie_id_token(id_token) def _set_cookie_id_token(self, id_token): """ Cooperates with @after_request to set a new ID token cookie. """ g.oidc_id_token = id_token g.oidc_id_token_dirty = True def _after_request(self, response): """ Set a new ID token cookie if the ID token has changed. """ # This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response def _before_request(self): g.oidc_id_token = None self.authenticate_or_redirect() def authenticate_or_redirect(self): """ Helper function suitable for @app.before_request and @check. Sets g.oidc_id_token to the ID token if the user has successfully authenticated, else returns a redirect object so they can go try to authenticate. :returns: A redirect object, or None if the user is logged in. :rtype: Redirect .. deprecated:: 1.0 Use :func:`require_login` instead. """ # the auth callback and error pages don't need user to be authenticated if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']): return None # retrieve signed ID token cookie id_token = self._get_cookie_id_token() if id_token is None: return self.redirect_to_auth_server(request.url) # ID token expired # when Google is the IdP, this happens after one hour if time.time() >= id_token['exp']: # get credentials from store try: credentials = OAuth2Credentials.from_json( self.credentials_store[id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return self.redirect_to_auth_server(request.url) # refresh and store credentials try: credentials.refresh(httplib2.Http()) if credentials.id_token: id_token = credentials.id_token else: # It is not guaranteed that we will get a new ID Token on # refresh, so if we do not, let's just update the id token # expiry field and reuse the existing ID Token. if credentials.token_expiry is None: logger.debug('Expired ID token, no new expiry. Falling' ' back to assuming 1 hour') id_token['exp'] = time.time() + 3600 else: id_token['exp'] = calendar.timegm( credentials.token_expiry.timetuple()) self.credentials_store[id_token['sub']] = credentials.to_json() self._set_cookie_id_token(id_token) except AccessTokenRefreshError: # Can't refresh. Wipe credentials and redirect user to IdP # for re-authentication. logger.debug("Expired ID token, can't refresh credentials", exc_info=True) del self.credentials_store[id_token['sub']] return self.redirect_to_auth_server(request.url) # make ID token available to views g.oidc_id_token = id_token return None def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """ @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated # Backwards compatibility check = require_login """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ def require_keycloak_role(self, client, role): """ Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper def flow_for_request(self): """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ warn('You are using a deprecated function (flow_for_request). ' 'Please reconsider using this', DeprecationWarning) return self._flow_for_request() def _flow_for_request(self): """ Build a flow with the correct absolute callback URL for this request. :return: """ flow = copy(self.flow) redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI'] if not redirect_uri: flow.redirect_uri = url_for('_oidc_callback', _external=True) else: flow.redirect_uri = redirect_uri return flow def redirect_to_auth_server(self, destination=None, customstate=None): """ Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead. """ if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url) def _is_id_token_valid(self, id_token): """ Check if `id_token` is a current ID token for this application, was issued by the Apps domain we expected, and that the email address has been verified. @see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation """ if not id_token: return False # step 2: check issuer if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']: logger.error('id_token issued by non-trusted issuer: %s' % id_token['iss']) return False if isinstance(id_token['aud'], list): # step 3 for audience list if self.flow.client_id not in id_token['aud']: logger.error('We are not a valid audience') return False # step 4 if 'azp' not in id_token and len(id_token['aud']) > 1: logger.error('Multiple audiences and not authorized party') return False else: # step 3 for single audience if id_token['aud'] != self.flow.client_id: logger.error('We are not the audience') return False # step 5 if 'azp' in id_token and id_token['azp'] != self.flow.client_id: logger.error('Authorized Party is not us') return False # step 6-8: TLS checked # step 9: check exp if int(time.time()) >= int(id_token['exp']): logger.error('Token has expired') return False # step 10: check iat if id_token['iat'] < (time.time() - current_app.config['OIDC_CLOCK_SKEW']): logger.error('Token issued in the past') return False # (not required if using HTTPS?) step 11: check nonce # step 12-13: not requested acr or auth_time, so not needed to test # additional steps specific to our usage if current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] and \ id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: logger.error('Invalid google apps domain') return False if not id_token.get('email_verified', False) and \ current_app.config['OIDC_REQUIRE_VERIFIED_EMAIL']: logger.error('Email not verified') return False return True WRONG_GOOGLE_APPS_DOMAIN = 'WRONG_GOOGLE_APPS_DOMAIN' def custom_callback(self, view_func): """ Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. """ @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback('custom') if plainreturn: return data else: return view_func(data, *args, **kwargs) self._custom_callback = decorated return decorated def _oidc_callback(self): plainreturn, data = self._process_callback('destination') if plainreturn: return data else: return redirect(data) def _process_callback(self, statefield): """ Exchange the auth code for actual credentials, then redirect to the originally requested page. """ # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response def _oidc_error(self, message='Not Authorized', code=None): return (message, 401, { 'Content-Type': 'text/plain', }) def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout self._set_cookie_id_token(None) # Below here is for resource servers to validate tokens def validate_token(self, token, scopes_required=None): """ This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1 """ valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid) def _validate_token(self, token, scopes_required=None): """The actual implementation of validate_token.""" if scopes_required is None: scopes_required = [] scopes_required = set(scopes_required) token_info = None valid_token = False has_required_scopes = False if token: try: token_info = self._get_token_info(token) except Exception as ex: token_info = {'active': False} logger.error('ERROR: Unable to get token info') logger.error(str(ex)) valid_token = token_info.get('active', False) if 'aud' in token_info and \ current_app.config['OIDC_RESOURCE_CHECK_AUD']: valid_audience = False aud = token_info['aud'] clid = self.client_secrets['client_id'] if isinstance(aud, list): valid_audience = clid in aud else: valid_audience = clid == aud if not valid_audience: logger.error('Refused token because of invalid ' 'audience') valid_token = False if valid_token: token_scopes = token_info.get('scope', '').split(' ') else: token_scopes = [] has_required_scopes = scopes_required.issubset( set(token_scopes)) if not has_required_scopes: logger.debug('Token missed required scopes') if (valid_token and has_required_scopes): g.oidc_token_info = token_info return True if not valid_token: return 'Token required but invalid' elif not has_required_scopes: return 'Token does not have required scopes' else: return 'Something went wrong checking your token' def accept_token(self, require_token=False, scopes_required=None, render_errors=True): """ Use this to decorate view functions that should accept OAuth2 tokens, this will most likely apply to API functions. Tokens are accepted as part of the query URL (access_token value) or a POST form value (access_token). Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param require_token: Whether a token is required for the current function. If this is True, we will abort the request if there was no token provided. :type require_token: bool :param scopes_required: List of scopes that are required to be granted by the token before being allowed to call the protected function. :type scopes_required: list :param render_errors: Whether or not to eagerly render error objects as JSON API responses. Set to False to pass the error object back unmodified for later rendering. :type render_errors: callback(obj) or None .. versionadded:: 1.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): token = request.headers['Authorization'].split(None,1)[1].strip() if 'access_token' in request.form: token = request.form['access_token'] elif 'access_token' in request.args: token = request.args['access_token'] validity = self.validate_token(token, scopes_required) if (validity is True) or (not require_token): return view_func(*args, **kwargs) else: response_body = {'error': 'invalid_token', 'error_description': validity} if render_errors: response_body = json.dumps(response_body) return response_body, 401, {'WWW-Authenticate': 'Bearer'} return decorated return wrapper def _get_token_info(self, token): # We hardcode to use client_secret_post, because that's what the Google # oauth2client library defaults to request = {'token': token} headers = {'Content-type': 'application/x-www-form-urlencoded'} hint = current_app.config['OIDC_TOKEN_TYPE_HINT'] if hint != 'none': request['token_type_hint'] = hint auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] if (auth_method == 'client_secret_basic'): basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret']) basic_auth_bytes = bytearray(basic_auth_string, 'utf-8') headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8') elif (auth_method == 'bearer'): headers['Authorization'] = 'Bearer %s' % token elif (auth_method == 'client_secret_post'): request['client_id'] = self.client_secrets['client_id'] if self.client_secrets['client_secret'] is not None: request['client_secret'] = self.client_secrets['client_secret'] resp, content = httplib2.Http().request( self.client_secrets['token_introspection_uri'], 'POST', urlencode(request), headers=headers) # TODO: Cache this reply return _json_loads(content)
puiterwijk/flask-oidc
flask_oidc/__init__.py
OpenIDConnect._after_request
python
def _after_request(self, response): # This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response
Set a new ID token cookie if the ID token has changed.
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L379-L409
null
class OpenIDConnect(object): """ The core OpenID Connect client object. """ def __init__(self, app=None, credentials_store=None, http=None, time=None, urandom=None): self.credentials_store = credentials_store\ if credentials_store is not None\ else MemoryCredentials() if http is not None: warn('HTTP argument is deprecated and unused', DeprecationWarning) if time is not None: warn('time argument is deprecated and unused', DeprecationWarning) if urandom is not None: warn('urandom argument is deprecated and unused', DeprecationWarning) # By default, we do not have a custom callback self._custom_callback = None # get stuff from the app's config, which may override stuff set above if app is not None: self.init_app(app) def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass def load_secrets(self, app): # Load client_secrets.json to pre-initialize some configuration content = app.config['OIDC_CLIENT_SECRETS'] if isinstance(content, dict): return content else: return _json_loads(open(content, 'r').read()) @property def user_loggedin(self): """ Represents whether the user is currently logged in. Returns: bool: Whether the user is logged in with Flask-OIDC. .. versionadded:: 1.0 """ return g.oidc_id_token is not None def user_getfield(self, field, access_token=None): """ Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0 """ info = self.user_getinfo([field], access_token) return info.get(field) def user_getinfo(self, fields, access_token=None): """ Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0 """ if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def get_refresh_token(self): """Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info def get_cookie_id_token(self): """ .. deprecated:: 1.0 Use :func:`user_getinfo` instead. """ warn('You are using a deprecated function (get_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._get_cookie_id_token() def _get_cookie_id_token(self): try: id_token_cookie = request.cookies.get(current_app.config[ 'OIDC_ID_TOKEN_COOKIE_NAME']) if not id_token_cookie: # Do not error if we were unable to get the cookie. # The user can debug this themselves. return None return self.cookie_serializer.loads(id_token_cookie) except SignatureExpired: logger.debug("Invalid ID token cookie", exc_info=True) return None except BadSignature: logger.info("Signature invalid for ID token cookie", exc_info=True) return None def set_cookie_id_token(self, id_token): """ .. deprecated:: 1.0 """ warn('You are using a deprecated function (set_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._set_cookie_id_token(id_token) def _set_cookie_id_token(self, id_token): """ Cooperates with @after_request to set a new ID token cookie. """ g.oidc_id_token = id_token g.oidc_id_token_dirty = True def _before_request(self): g.oidc_id_token = None self.authenticate_or_redirect() def authenticate_or_redirect(self): """ Helper function suitable for @app.before_request and @check. Sets g.oidc_id_token to the ID token if the user has successfully authenticated, else returns a redirect object so they can go try to authenticate. :returns: A redirect object, or None if the user is logged in. :rtype: Redirect .. deprecated:: 1.0 Use :func:`require_login` instead. """ # the auth callback and error pages don't need user to be authenticated if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']): return None # retrieve signed ID token cookie id_token = self._get_cookie_id_token() if id_token is None: return self.redirect_to_auth_server(request.url) # ID token expired # when Google is the IdP, this happens after one hour if time.time() >= id_token['exp']: # get credentials from store try: credentials = OAuth2Credentials.from_json( self.credentials_store[id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return self.redirect_to_auth_server(request.url) # refresh and store credentials try: credentials.refresh(httplib2.Http()) if credentials.id_token: id_token = credentials.id_token else: # It is not guaranteed that we will get a new ID Token on # refresh, so if we do not, let's just update the id token # expiry field and reuse the existing ID Token. if credentials.token_expiry is None: logger.debug('Expired ID token, no new expiry. Falling' ' back to assuming 1 hour') id_token['exp'] = time.time() + 3600 else: id_token['exp'] = calendar.timegm( credentials.token_expiry.timetuple()) self.credentials_store[id_token['sub']] = credentials.to_json() self._set_cookie_id_token(id_token) except AccessTokenRefreshError: # Can't refresh. Wipe credentials and redirect user to IdP # for re-authentication. logger.debug("Expired ID token, can't refresh credentials", exc_info=True) del self.credentials_store[id_token['sub']] return self.redirect_to_auth_server(request.url) # make ID token available to views g.oidc_id_token = id_token return None def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """ @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated # Backwards compatibility check = require_login """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ def require_keycloak_role(self, client, role): """ Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper def flow_for_request(self): """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ warn('You are using a deprecated function (flow_for_request). ' 'Please reconsider using this', DeprecationWarning) return self._flow_for_request() def _flow_for_request(self): """ Build a flow with the correct absolute callback URL for this request. :return: """ flow = copy(self.flow) redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI'] if not redirect_uri: flow.redirect_uri = url_for('_oidc_callback', _external=True) else: flow.redirect_uri = redirect_uri return flow def redirect_to_auth_server(self, destination=None, customstate=None): """ Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead. """ if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url) def _is_id_token_valid(self, id_token): """ Check if `id_token` is a current ID token for this application, was issued by the Apps domain we expected, and that the email address has been verified. @see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation """ if not id_token: return False # step 2: check issuer if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']: logger.error('id_token issued by non-trusted issuer: %s' % id_token['iss']) return False if isinstance(id_token['aud'], list): # step 3 for audience list if self.flow.client_id not in id_token['aud']: logger.error('We are not a valid audience') return False # step 4 if 'azp' not in id_token and len(id_token['aud']) > 1: logger.error('Multiple audiences and not authorized party') return False else: # step 3 for single audience if id_token['aud'] != self.flow.client_id: logger.error('We are not the audience') return False # step 5 if 'azp' in id_token and id_token['azp'] != self.flow.client_id: logger.error('Authorized Party is not us') return False # step 6-8: TLS checked # step 9: check exp if int(time.time()) >= int(id_token['exp']): logger.error('Token has expired') return False # step 10: check iat if id_token['iat'] < (time.time() - current_app.config['OIDC_CLOCK_SKEW']): logger.error('Token issued in the past') return False # (not required if using HTTPS?) step 11: check nonce # step 12-13: not requested acr or auth_time, so not needed to test # additional steps specific to our usage if current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] and \ id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: logger.error('Invalid google apps domain') return False if not id_token.get('email_verified', False) and \ current_app.config['OIDC_REQUIRE_VERIFIED_EMAIL']: logger.error('Email not verified') return False return True WRONG_GOOGLE_APPS_DOMAIN = 'WRONG_GOOGLE_APPS_DOMAIN' def custom_callback(self, view_func): """ Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. """ @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback('custom') if plainreturn: return data else: return view_func(data, *args, **kwargs) self._custom_callback = decorated return decorated def _oidc_callback(self): plainreturn, data = self._process_callback('destination') if plainreturn: return data else: return redirect(data) def _process_callback(self, statefield): """ Exchange the auth code for actual credentials, then redirect to the originally requested page. """ # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response def _oidc_error(self, message='Not Authorized', code=None): return (message, 401, { 'Content-Type': 'text/plain', }) def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout self._set_cookie_id_token(None) # Below here is for resource servers to validate tokens def validate_token(self, token, scopes_required=None): """ This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1 """ valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid) def _validate_token(self, token, scopes_required=None): """The actual implementation of validate_token.""" if scopes_required is None: scopes_required = [] scopes_required = set(scopes_required) token_info = None valid_token = False has_required_scopes = False if token: try: token_info = self._get_token_info(token) except Exception as ex: token_info = {'active': False} logger.error('ERROR: Unable to get token info') logger.error(str(ex)) valid_token = token_info.get('active', False) if 'aud' in token_info and \ current_app.config['OIDC_RESOURCE_CHECK_AUD']: valid_audience = False aud = token_info['aud'] clid = self.client_secrets['client_id'] if isinstance(aud, list): valid_audience = clid in aud else: valid_audience = clid == aud if not valid_audience: logger.error('Refused token because of invalid ' 'audience') valid_token = False if valid_token: token_scopes = token_info.get('scope', '').split(' ') else: token_scopes = [] has_required_scopes = scopes_required.issubset( set(token_scopes)) if not has_required_scopes: logger.debug('Token missed required scopes') if (valid_token and has_required_scopes): g.oidc_token_info = token_info return True if not valid_token: return 'Token required but invalid' elif not has_required_scopes: return 'Token does not have required scopes' else: return 'Something went wrong checking your token' def accept_token(self, require_token=False, scopes_required=None, render_errors=True): """ Use this to decorate view functions that should accept OAuth2 tokens, this will most likely apply to API functions. Tokens are accepted as part of the query URL (access_token value) or a POST form value (access_token). Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param require_token: Whether a token is required for the current function. If this is True, we will abort the request if there was no token provided. :type require_token: bool :param scopes_required: List of scopes that are required to be granted by the token before being allowed to call the protected function. :type scopes_required: list :param render_errors: Whether or not to eagerly render error objects as JSON API responses. Set to False to pass the error object back unmodified for later rendering. :type render_errors: callback(obj) or None .. versionadded:: 1.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): token = request.headers['Authorization'].split(None,1)[1].strip() if 'access_token' in request.form: token = request.form['access_token'] elif 'access_token' in request.args: token = request.args['access_token'] validity = self.validate_token(token, scopes_required) if (validity is True) or (not require_token): return view_func(*args, **kwargs) else: response_body = {'error': 'invalid_token', 'error_description': validity} if render_errors: response_body = json.dumps(response_body) return response_body, 401, {'WWW-Authenticate': 'Bearer'} return decorated return wrapper def _get_token_info(self, token): # We hardcode to use client_secret_post, because that's what the Google # oauth2client library defaults to request = {'token': token} headers = {'Content-type': 'application/x-www-form-urlencoded'} hint = current_app.config['OIDC_TOKEN_TYPE_HINT'] if hint != 'none': request['token_type_hint'] = hint auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] if (auth_method == 'client_secret_basic'): basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret']) basic_auth_bytes = bytearray(basic_auth_string, 'utf-8') headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8') elif (auth_method == 'bearer'): headers['Authorization'] = 'Bearer %s' % token elif (auth_method == 'client_secret_post'): request['client_id'] = self.client_secrets['client_id'] if self.client_secrets['client_secret'] is not None: request['client_secret'] = self.client_secrets['client_secret'] resp, content = httplib2.Http().request( self.client_secrets['token_introspection_uri'], 'POST', urlencode(request), headers=headers) # TODO: Cache this reply return _json_loads(content)
puiterwijk/flask-oidc
flask_oidc/__init__.py
OpenIDConnect.authenticate_or_redirect
python
def authenticate_or_redirect(self): # the auth callback and error pages don't need user to be authenticated if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']): return None # retrieve signed ID token cookie id_token = self._get_cookie_id_token() if id_token is None: return self.redirect_to_auth_server(request.url) # ID token expired # when Google is the IdP, this happens after one hour if time.time() >= id_token['exp']: # get credentials from store try: credentials = OAuth2Credentials.from_json( self.credentials_store[id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return self.redirect_to_auth_server(request.url) # refresh and store credentials try: credentials.refresh(httplib2.Http()) if credentials.id_token: id_token = credentials.id_token else: # It is not guaranteed that we will get a new ID Token on # refresh, so if we do not, let's just update the id token # expiry field and reuse the existing ID Token. if credentials.token_expiry is None: logger.debug('Expired ID token, no new expiry. Falling' ' back to assuming 1 hour') id_token['exp'] = time.time() + 3600 else: id_token['exp'] = calendar.timegm( credentials.token_expiry.timetuple()) self.credentials_store[id_token['sub']] = credentials.to_json() self._set_cookie_id_token(id_token) except AccessTokenRefreshError: # Can't refresh. Wipe credentials and redirect user to IdP # for re-authentication. logger.debug("Expired ID token, can't refresh credentials", exc_info=True) del self.credentials_store[id_token['sub']] return self.redirect_to_auth_server(request.url) # make ID token available to views g.oidc_id_token = id_token return None
Helper function suitable for @app.before_request and @check. Sets g.oidc_id_token to the ID token if the user has successfully authenticated, else returns a redirect object so they can go try to authenticate. :returns: A redirect object, or None if the user is logged in. :rtype: Redirect .. deprecated:: 1.0 Use :func:`require_login` instead.
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L415-L478
[ "def _get_cookie_id_token(self):\n try:\n id_token_cookie = request.cookies.get(current_app.config[\n 'OIDC_ID_TOKEN_COOKIE_NAME'])\n if not id_token_cookie:\n # Do not error if we were unable to get the cookie.\n # The user can debug this themselves.\n return None\n return self.cookie_serializer.loads(id_token_cookie)\n except SignatureExpired:\n logger.debug(\"Invalid ID token cookie\", exc_info=True)\n return None\n except BadSignature:\n logger.info(\"Signature invalid for ID token cookie\", exc_info=True)\n return None\n", "def _set_cookie_id_token(self, id_token):\n \"\"\"\n Cooperates with @after_request to set a new ID token cookie.\n \"\"\"\n g.oidc_id_token = id_token\n g.oidc_id_token_dirty = True\n", "def redirect_to_auth_server(self, destination=None, customstate=None):\n \"\"\"\n Set a CSRF token in the session, and redirect to the IdP.\n\n :param destination: The page that the user was going to,\n before we noticed they weren't logged in.\n :type destination: Url to return the client to if a custom handler is\n not used. Not available with custom callback.\n :param customstate: The custom data passed via the ODIC state.\n Note that this only works with a custom_callback, and this will\n ignore destination.\n :type customstate: Anything that can be serialized\n :returns: A redirect response to start the login process.\n :rtype: Flask Response\n\n .. deprecated:: 1.0\n Use :func:`require_login` instead.\n \"\"\"\n if not self._custom_callback and customstate:\n raise ValueError('Custom State is only avilable with a custom '\n 'handler')\n if 'oidc_csrf_token' not in session:\n csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8')\n session['oidc_csrf_token'] = csrf_token\n state = {\n 'csrf_token': session['oidc_csrf_token'],\n }\n statefield = 'destination'\n statevalue = destination\n if customstate is not None:\n statefield = 'custom'\n statevalue = customstate\n state[statefield] = self.extra_data_serializer.dumps(\n statevalue).decode('utf-8')\n\n extra_params = {\n 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')),\n }\n extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS'])\n if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']:\n extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN']\n if current_app.config['OIDC_OPENID_REALM']:\n extra_params['openid.realm'] = current_app.config[\n 'OIDC_OPENID_REALM']\n\n flow = self._flow_for_request()\n auth_url = '{url}&{extra_params}'.format(\n url=flow.step1_get_authorize_url(),\n extra_params=urlencode(extra_params))\n # if the user has an ID token, it's invalid, or we wouldn't be here\n self._set_cookie_id_token(None)\n return redirect(auth_url)\n" ]
class OpenIDConnect(object): """ The core OpenID Connect client object. """ def __init__(self, app=None, credentials_store=None, http=None, time=None, urandom=None): self.credentials_store = credentials_store\ if credentials_store is not None\ else MemoryCredentials() if http is not None: warn('HTTP argument is deprecated and unused', DeprecationWarning) if time is not None: warn('time argument is deprecated and unused', DeprecationWarning) if urandom is not None: warn('urandom argument is deprecated and unused', DeprecationWarning) # By default, we do not have a custom callback self._custom_callback = None # get stuff from the app's config, which may override stuff set above if app is not None: self.init_app(app) def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass def load_secrets(self, app): # Load client_secrets.json to pre-initialize some configuration content = app.config['OIDC_CLIENT_SECRETS'] if isinstance(content, dict): return content else: return _json_loads(open(content, 'r').read()) @property def user_loggedin(self): """ Represents whether the user is currently logged in. Returns: bool: Whether the user is logged in with Flask-OIDC. .. versionadded:: 1.0 """ return g.oidc_id_token is not None def user_getfield(self, field, access_token=None): """ Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0 """ info = self.user_getinfo([field], access_token) return info.get(field) def user_getinfo(self, fields, access_token=None): """ Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0 """ if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def get_refresh_token(self): """Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info def get_cookie_id_token(self): """ .. deprecated:: 1.0 Use :func:`user_getinfo` instead. """ warn('You are using a deprecated function (get_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._get_cookie_id_token() def _get_cookie_id_token(self): try: id_token_cookie = request.cookies.get(current_app.config[ 'OIDC_ID_TOKEN_COOKIE_NAME']) if not id_token_cookie: # Do not error if we were unable to get the cookie. # The user can debug this themselves. return None return self.cookie_serializer.loads(id_token_cookie) except SignatureExpired: logger.debug("Invalid ID token cookie", exc_info=True) return None except BadSignature: logger.info("Signature invalid for ID token cookie", exc_info=True) return None def set_cookie_id_token(self, id_token): """ .. deprecated:: 1.0 """ warn('You are using a deprecated function (set_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._set_cookie_id_token(id_token) def _set_cookie_id_token(self, id_token): """ Cooperates with @after_request to set a new ID token cookie. """ g.oidc_id_token = id_token g.oidc_id_token_dirty = True def _after_request(self, response): """ Set a new ID token cookie if the ID token has changed. """ # This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response def _before_request(self): g.oidc_id_token = None self.authenticate_or_redirect() def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """ @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated # Backwards compatibility check = require_login """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ def require_keycloak_role(self, client, role): """ Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper def flow_for_request(self): """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ warn('You are using a deprecated function (flow_for_request). ' 'Please reconsider using this', DeprecationWarning) return self._flow_for_request() def _flow_for_request(self): """ Build a flow with the correct absolute callback URL for this request. :return: """ flow = copy(self.flow) redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI'] if not redirect_uri: flow.redirect_uri = url_for('_oidc_callback', _external=True) else: flow.redirect_uri = redirect_uri return flow def redirect_to_auth_server(self, destination=None, customstate=None): """ Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead. """ if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url) def _is_id_token_valid(self, id_token): """ Check if `id_token` is a current ID token for this application, was issued by the Apps domain we expected, and that the email address has been verified. @see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation """ if not id_token: return False # step 2: check issuer if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']: logger.error('id_token issued by non-trusted issuer: %s' % id_token['iss']) return False if isinstance(id_token['aud'], list): # step 3 for audience list if self.flow.client_id not in id_token['aud']: logger.error('We are not a valid audience') return False # step 4 if 'azp' not in id_token and len(id_token['aud']) > 1: logger.error('Multiple audiences and not authorized party') return False else: # step 3 for single audience if id_token['aud'] != self.flow.client_id: logger.error('We are not the audience') return False # step 5 if 'azp' in id_token and id_token['azp'] != self.flow.client_id: logger.error('Authorized Party is not us') return False # step 6-8: TLS checked # step 9: check exp if int(time.time()) >= int(id_token['exp']): logger.error('Token has expired') return False # step 10: check iat if id_token['iat'] < (time.time() - current_app.config['OIDC_CLOCK_SKEW']): logger.error('Token issued in the past') return False # (not required if using HTTPS?) step 11: check nonce # step 12-13: not requested acr or auth_time, so not needed to test # additional steps specific to our usage if current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] and \ id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: logger.error('Invalid google apps domain') return False if not id_token.get('email_verified', False) and \ current_app.config['OIDC_REQUIRE_VERIFIED_EMAIL']: logger.error('Email not verified') return False return True WRONG_GOOGLE_APPS_DOMAIN = 'WRONG_GOOGLE_APPS_DOMAIN' def custom_callback(self, view_func): """ Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. """ @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback('custom') if plainreturn: return data else: return view_func(data, *args, **kwargs) self._custom_callback = decorated return decorated def _oidc_callback(self): plainreturn, data = self._process_callback('destination') if plainreturn: return data else: return redirect(data) def _process_callback(self, statefield): """ Exchange the auth code for actual credentials, then redirect to the originally requested page. """ # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response def _oidc_error(self, message='Not Authorized', code=None): return (message, 401, { 'Content-Type': 'text/plain', }) def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout self._set_cookie_id_token(None) # Below here is for resource servers to validate tokens def validate_token(self, token, scopes_required=None): """ This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1 """ valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid) def _validate_token(self, token, scopes_required=None): """The actual implementation of validate_token.""" if scopes_required is None: scopes_required = [] scopes_required = set(scopes_required) token_info = None valid_token = False has_required_scopes = False if token: try: token_info = self._get_token_info(token) except Exception as ex: token_info = {'active': False} logger.error('ERROR: Unable to get token info') logger.error(str(ex)) valid_token = token_info.get('active', False) if 'aud' in token_info and \ current_app.config['OIDC_RESOURCE_CHECK_AUD']: valid_audience = False aud = token_info['aud'] clid = self.client_secrets['client_id'] if isinstance(aud, list): valid_audience = clid in aud else: valid_audience = clid == aud if not valid_audience: logger.error('Refused token because of invalid ' 'audience') valid_token = False if valid_token: token_scopes = token_info.get('scope', '').split(' ') else: token_scopes = [] has_required_scopes = scopes_required.issubset( set(token_scopes)) if not has_required_scopes: logger.debug('Token missed required scopes') if (valid_token and has_required_scopes): g.oidc_token_info = token_info return True if not valid_token: return 'Token required but invalid' elif not has_required_scopes: return 'Token does not have required scopes' else: return 'Something went wrong checking your token' def accept_token(self, require_token=False, scopes_required=None, render_errors=True): """ Use this to decorate view functions that should accept OAuth2 tokens, this will most likely apply to API functions. Tokens are accepted as part of the query URL (access_token value) or a POST form value (access_token). Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param require_token: Whether a token is required for the current function. If this is True, we will abort the request if there was no token provided. :type require_token: bool :param scopes_required: List of scopes that are required to be granted by the token before being allowed to call the protected function. :type scopes_required: list :param render_errors: Whether or not to eagerly render error objects as JSON API responses. Set to False to pass the error object back unmodified for later rendering. :type render_errors: callback(obj) or None .. versionadded:: 1.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): token = request.headers['Authorization'].split(None,1)[1].strip() if 'access_token' in request.form: token = request.form['access_token'] elif 'access_token' in request.args: token = request.args['access_token'] validity = self.validate_token(token, scopes_required) if (validity is True) or (not require_token): return view_func(*args, **kwargs) else: response_body = {'error': 'invalid_token', 'error_description': validity} if render_errors: response_body = json.dumps(response_body) return response_body, 401, {'WWW-Authenticate': 'Bearer'} return decorated return wrapper def _get_token_info(self, token): # We hardcode to use client_secret_post, because that's what the Google # oauth2client library defaults to request = {'token': token} headers = {'Content-type': 'application/x-www-form-urlencoded'} hint = current_app.config['OIDC_TOKEN_TYPE_HINT'] if hint != 'none': request['token_type_hint'] = hint auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] if (auth_method == 'client_secret_basic'): basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret']) basic_auth_bytes = bytearray(basic_auth_string, 'utf-8') headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8') elif (auth_method == 'bearer'): headers['Authorization'] = 'Bearer %s' % token elif (auth_method == 'client_secret_post'): request['client_id'] = self.client_secrets['client_id'] if self.client_secrets['client_secret'] is not None: request['client_secret'] = self.client_secrets['client_secret'] resp, content = httplib2.Http().request( self.client_secrets['token_introspection_uri'], 'POST', urlencode(request), headers=headers) # TODO: Cache this reply return _json_loads(content)
puiterwijk/flask-oidc
flask_oidc/__init__.py
OpenIDConnect.require_login
python
def require_login(self, view_func): @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated
Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before.
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L480-L494
null
class OpenIDConnect(object): """ The core OpenID Connect client object. """ def __init__(self, app=None, credentials_store=None, http=None, time=None, urandom=None): self.credentials_store = credentials_store\ if credentials_store is not None\ else MemoryCredentials() if http is not None: warn('HTTP argument is deprecated and unused', DeprecationWarning) if time is not None: warn('time argument is deprecated and unused', DeprecationWarning) if urandom is not None: warn('urandom argument is deprecated and unused', DeprecationWarning) # By default, we do not have a custom callback self._custom_callback = None # get stuff from the app's config, which may override stuff set above if app is not None: self.init_app(app) def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass def load_secrets(self, app): # Load client_secrets.json to pre-initialize some configuration content = app.config['OIDC_CLIENT_SECRETS'] if isinstance(content, dict): return content else: return _json_loads(open(content, 'r').read()) @property def user_loggedin(self): """ Represents whether the user is currently logged in. Returns: bool: Whether the user is logged in with Flask-OIDC. .. versionadded:: 1.0 """ return g.oidc_id_token is not None def user_getfield(self, field, access_token=None): """ Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0 """ info = self.user_getinfo([field], access_token) return info.get(field) def user_getinfo(self, fields, access_token=None): """ Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0 """ if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def get_refresh_token(self): """Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info def get_cookie_id_token(self): """ .. deprecated:: 1.0 Use :func:`user_getinfo` instead. """ warn('You are using a deprecated function (get_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._get_cookie_id_token() def _get_cookie_id_token(self): try: id_token_cookie = request.cookies.get(current_app.config[ 'OIDC_ID_TOKEN_COOKIE_NAME']) if not id_token_cookie: # Do not error if we were unable to get the cookie. # The user can debug this themselves. return None return self.cookie_serializer.loads(id_token_cookie) except SignatureExpired: logger.debug("Invalid ID token cookie", exc_info=True) return None except BadSignature: logger.info("Signature invalid for ID token cookie", exc_info=True) return None def set_cookie_id_token(self, id_token): """ .. deprecated:: 1.0 """ warn('You are using a deprecated function (set_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._set_cookie_id_token(id_token) def _set_cookie_id_token(self, id_token): """ Cooperates with @after_request to set a new ID token cookie. """ g.oidc_id_token = id_token g.oidc_id_token_dirty = True def _after_request(self, response): """ Set a new ID token cookie if the ID token has changed. """ # This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response def _before_request(self): g.oidc_id_token = None self.authenticate_or_redirect() def authenticate_or_redirect(self): """ Helper function suitable for @app.before_request and @check. Sets g.oidc_id_token to the ID token if the user has successfully authenticated, else returns a redirect object so they can go try to authenticate. :returns: A redirect object, or None if the user is logged in. :rtype: Redirect .. deprecated:: 1.0 Use :func:`require_login` instead. """ # the auth callback and error pages don't need user to be authenticated if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']): return None # retrieve signed ID token cookie id_token = self._get_cookie_id_token() if id_token is None: return self.redirect_to_auth_server(request.url) # ID token expired # when Google is the IdP, this happens after one hour if time.time() >= id_token['exp']: # get credentials from store try: credentials = OAuth2Credentials.from_json( self.credentials_store[id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return self.redirect_to_auth_server(request.url) # refresh and store credentials try: credentials.refresh(httplib2.Http()) if credentials.id_token: id_token = credentials.id_token else: # It is not guaranteed that we will get a new ID Token on # refresh, so if we do not, let's just update the id token # expiry field and reuse the existing ID Token. if credentials.token_expiry is None: logger.debug('Expired ID token, no new expiry. Falling' ' back to assuming 1 hour') id_token['exp'] = time.time() + 3600 else: id_token['exp'] = calendar.timegm( credentials.token_expiry.timetuple()) self.credentials_store[id_token['sub']] = credentials.to_json() self._set_cookie_id_token(id_token) except AccessTokenRefreshError: # Can't refresh. Wipe credentials and redirect user to IdP # for re-authentication. logger.debug("Expired ID token, can't refresh credentials", exc_info=True) del self.credentials_store[id_token['sub']] return self.redirect_to_auth_server(request.url) # make ID token available to views g.oidc_id_token = id_token return None # Backwards compatibility check = require_login """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ def require_keycloak_role(self, client, role): """ Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper def flow_for_request(self): """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ warn('You are using a deprecated function (flow_for_request). ' 'Please reconsider using this', DeprecationWarning) return self._flow_for_request() def _flow_for_request(self): """ Build a flow with the correct absolute callback URL for this request. :return: """ flow = copy(self.flow) redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI'] if not redirect_uri: flow.redirect_uri = url_for('_oidc_callback', _external=True) else: flow.redirect_uri = redirect_uri return flow def redirect_to_auth_server(self, destination=None, customstate=None): """ Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead. """ if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url) def _is_id_token_valid(self, id_token): """ Check if `id_token` is a current ID token for this application, was issued by the Apps domain we expected, and that the email address has been verified. @see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation """ if not id_token: return False # step 2: check issuer if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']: logger.error('id_token issued by non-trusted issuer: %s' % id_token['iss']) return False if isinstance(id_token['aud'], list): # step 3 for audience list if self.flow.client_id not in id_token['aud']: logger.error('We are not a valid audience') return False # step 4 if 'azp' not in id_token and len(id_token['aud']) > 1: logger.error('Multiple audiences and not authorized party') return False else: # step 3 for single audience if id_token['aud'] != self.flow.client_id: logger.error('We are not the audience') return False # step 5 if 'azp' in id_token and id_token['azp'] != self.flow.client_id: logger.error('Authorized Party is not us') return False # step 6-8: TLS checked # step 9: check exp if int(time.time()) >= int(id_token['exp']): logger.error('Token has expired') return False # step 10: check iat if id_token['iat'] < (time.time() - current_app.config['OIDC_CLOCK_SKEW']): logger.error('Token issued in the past') return False # (not required if using HTTPS?) step 11: check nonce # step 12-13: not requested acr or auth_time, so not needed to test # additional steps specific to our usage if current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] and \ id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: logger.error('Invalid google apps domain') return False if not id_token.get('email_verified', False) and \ current_app.config['OIDC_REQUIRE_VERIFIED_EMAIL']: logger.error('Email not verified') return False return True WRONG_GOOGLE_APPS_DOMAIN = 'WRONG_GOOGLE_APPS_DOMAIN' def custom_callback(self, view_func): """ Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. """ @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback('custom') if plainreturn: return data else: return view_func(data, *args, **kwargs) self._custom_callback = decorated return decorated def _oidc_callback(self): plainreturn, data = self._process_callback('destination') if plainreturn: return data else: return redirect(data) def _process_callback(self, statefield): """ Exchange the auth code for actual credentials, then redirect to the originally requested page. """ # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response def _oidc_error(self, message='Not Authorized', code=None): return (message, 401, { 'Content-Type': 'text/plain', }) def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout self._set_cookie_id_token(None) # Below here is for resource servers to validate tokens def validate_token(self, token, scopes_required=None): """ This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1 """ valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid) def _validate_token(self, token, scopes_required=None): """The actual implementation of validate_token.""" if scopes_required is None: scopes_required = [] scopes_required = set(scopes_required) token_info = None valid_token = False has_required_scopes = False if token: try: token_info = self._get_token_info(token) except Exception as ex: token_info = {'active': False} logger.error('ERROR: Unable to get token info') logger.error(str(ex)) valid_token = token_info.get('active', False) if 'aud' in token_info and \ current_app.config['OIDC_RESOURCE_CHECK_AUD']: valid_audience = False aud = token_info['aud'] clid = self.client_secrets['client_id'] if isinstance(aud, list): valid_audience = clid in aud else: valid_audience = clid == aud if not valid_audience: logger.error('Refused token because of invalid ' 'audience') valid_token = False if valid_token: token_scopes = token_info.get('scope', '').split(' ') else: token_scopes = [] has_required_scopes = scopes_required.issubset( set(token_scopes)) if not has_required_scopes: logger.debug('Token missed required scopes') if (valid_token and has_required_scopes): g.oidc_token_info = token_info return True if not valid_token: return 'Token required but invalid' elif not has_required_scopes: return 'Token does not have required scopes' else: return 'Something went wrong checking your token' def accept_token(self, require_token=False, scopes_required=None, render_errors=True): """ Use this to decorate view functions that should accept OAuth2 tokens, this will most likely apply to API functions. Tokens are accepted as part of the query URL (access_token value) or a POST form value (access_token). Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param require_token: Whether a token is required for the current function. If this is True, we will abort the request if there was no token provided. :type require_token: bool :param scopes_required: List of scopes that are required to be granted by the token before being allowed to call the protected function. :type scopes_required: list :param render_errors: Whether or not to eagerly render error objects as JSON API responses. Set to False to pass the error object back unmodified for later rendering. :type render_errors: callback(obj) or None .. versionadded:: 1.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): token = request.headers['Authorization'].split(None,1)[1].strip() if 'access_token' in request.form: token = request.form['access_token'] elif 'access_token' in request.args: token = request.args['access_token'] validity = self.validate_token(token, scopes_required) if (validity is True) or (not require_token): return view_func(*args, **kwargs) else: response_body = {'error': 'invalid_token', 'error_description': validity} if render_errors: response_body = json.dumps(response_body) return response_body, 401, {'WWW-Authenticate': 'Bearer'} return decorated return wrapper def _get_token_info(self, token): # We hardcode to use client_secret_post, because that's what the Google # oauth2client library defaults to request = {'token': token} headers = {'Content-type': 'application/x-www-form-urlencoded'} hint = current_app.config['OIDC_TOKEN_TYPE_HINT'] if hint != 'none': request['token_type_hint'] = hint auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] if (auth_method == 'client_secret_basic'): basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret']) basic_auth_bytes = bytearray(basic_auth_string, 'utf-8') headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8') elif (auth_method == 'bearer'): headers['Authorization'] = 'Bearer %s' % token elif (auth_method == 'client_secret_post'): request['client_id'] = self.client_secrets['client_id'] if self.client_secrets['client_secret'] is not None: request['client_secret'] = self.client_secrets['client_secret'] resp, content = httplib2.Http().request( self.client_secrets['token_introspection_uri'], 'POST', urlencode(request), headers=headers) # TODO: Cache this reply return _json_loads(content)
puiterwijk/flask-oidc
flask_oidc/__init__.py
OpenIDConnect.require_keycloak_role
python
def require_keycloak_role(self, client, role): def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper
Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L502-L522
null
class OpenIDConnect(object): """ The core OpenID Connect client object. """ def __init__(self, app=None, credentials_store=None, http=None, time=None, urandom=None): self.credentials_store = credentials_store\ if credentials_store is not None\ else MemoryCredentials() if http is not None: warn('HTTP argument is deprecated and unused', DeprecationWarning) if time is not None: warn('time argument is deprecated and unused', DeprecationWarning) if urandom is not None: warn('urandom argument is deprecated and unused', DeprecationWarning) # By default, we do not have a custom callback self._custom_callback = None # get stuff from the app's config, which may override stuff set above if app is not None: self.init_app(app) def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass def load_secrets(self, app): # Load client_secrets.json to pre-initialize some configuration content = app.config['OIDC_CLIENT_SECRETS'] if isinstance(content, dict): return content else: return _json_loads(open(content, 'r').read()) @property def user_loggedin(self): """ Represents whether the user is currently logged in. Returns: bool: Whether the user is logged in with Flask-OIDC. .. versionadded:: 1.0 """ return g.oidc_id_token is not None def user_getfield(self, field, access_token=None): """ Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0 """ info = self.user_getinfo([field], access_token) return info.get(field) def user_getinfo(self, fields, access_token=None): """ Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0 """ if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def get_refresh_token(self): """Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info def get_cookie_id_token(self): """ .. deprecated:: 1.0 Use :func:`user_getinfo` instead. """ warn('You are using a deprecated function (get_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._get_cookie_id_token() def _get_cookie_id_token(self): try: id_token_cookie = request.cookies.get(current_app.config[ 'OIDC_ID_TOKEN_COOKIE_NAME']) if not id_token_cookie: # Do not error if we were unable to get the cookie. # The user can debug this themselves. return None return self.cookie_serializer.loads(id_token_cookie) except SignatureExpired: logger.debug("Invalid ID token cookie", exc_info=True) return None except BadSignature: logger.info("Signature invalid for ID token cookie", exc_info=True) return None def set_cookie_id_token(self, id_token): """ .. deprecated:: 1.0 """ warn('You are using a deprecated function (set_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._set_cookie_id_token(id_token) def _set_cookie_id_token(self, id_token): """ Cooperates with @after_request to set a new ID token cookie. """ g.oidc_id_token = id_token g.oidc_id_token_dirty = True def _after_request(self, response): """ Set a new ID token cookie if the ID token has changed. """ # This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response def _before_request(self): g.oidc_id_token = None self.authenticate_or_redirect() def authenticate_or_redirect(self): """ Helper function suitable for @app.before_request and @check. Sets g.oidc_id_token to the ID token if the user has successfully authenticated, else returns a redirect object so they can go try to authenticate. :returns: A redirect object, or None if the user is logged in. :rtype: Redirect .. deprecated:: 1.0 Use :func:`require_login` instead. """ # the auth callback and error pages don't need user to be authenticated if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']): return None # retrieve signed ID token cookie id_token = self._get_cookie_id_token() if id_token is None: return self.redirect_to_auth_server(request.url) # ID token expired # when Google is the IdP, this happens after one hour if time.time() >= id_token['exp']: # get credentials from store try: credentials = OAuth2Credentials.from_json( self.credentials_store[id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return self.redirect_to_auth_server(request.url) # refresh and store credentials try: credentials.refresh(httplib2.Http()) if credentials.id_token: id_token = credentials.id_token else: # It is not guaranteed that we will get a new ID Token on # refresh, so if we do not, let's just update the id token # expiry field and reuse the existing ID Token. if credentials.token_expiry is None: logger.debug('Expired ID token, no new expiry. Falling' ' back to assuming 1 hour') id_token['exp'] = time.time() + 3600 else: id_token['exp'] = calendar.timegm( credentials.token_expiry.timetuple()) self.credentials_store[id_token['sub']] = credentials.to_json() self._set_cookie_id_token(id_token) except AccessTokenRefreshError: # Can't refresh. Wipe credentials and redirect user to IdP # for re-authentication. logger.debug("Expired ID token, can't refresh credentials", exc_info=True) del self.credentials_store[id_token['sub']] return self.redirect_to_auth_server(request.url) # make ID token available to views g.oidc_id_token = id_token return None def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """ @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated # Backwards compatibility check = require_login """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ def flow_for_request(self): """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ warn('You are using a deprecated function (flow_for_request). ' 'Please reconsider using this', DeprecationWarning) return self._flow_for_request() def _flow_for_request(self): """ Build a flow with the correct absolute callback URL for this request. :return: """ flow = copy(self.flow) redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI'] if not redirect_uri: flow.redirect_uri = url_for('_oidc_callback', _external=True) else: flow.redirect_uri = redirect_uri return flow def redirect_to_auth_server(self, destination=None, customstate=None): """ Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead. """ if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url) def _is_id_token_valid(self, id_token): """ Check if `id_token` is a current ID token for this application, was issued by the Apps domain we expected, and that the email address has been verified. @see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation """ if not id_token: return False # step 2: check issuer if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']: logger.error('id_token issued by non-trusted issuer: %s' % id_token['iss']) return False if isinstance(id_token['aud'], list): # step 3 for audience list if self.flow.client_id not in id_token['aud']: logger.error('We are not a valid audience') return False # step 4 if 'azp' not in id_token and len(id_token['aud']) > 1: logger.error('Multiple audiences and not authorized party') return False else: # step 3 for single audience if id_token['aud'] != self.flow.client_id: logger.error('We are not the audience') return False # step 5 if 'azp' in id_token and id_token['azp'] != self.flow.client_id: logger.error('Authorized Party is not us') return False # step 6-8: TLS checked # step 9: check exp if int(time.time()) >= int(id_token['exp']): logger.error('Token has expired') return False # step 10: check iat if id_token['iat'] < (time.time() - current_app.config['OIDC_CLOCK_SKEW']): logger.error('Token issued in the past') return False # (not required if using HTTPS?) step 11: check nonce # step 12-13: not requested acr or auth_time, so not needed to test # additional steps specific to our usage if current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] and \ id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: logger.error('Invalid google apps domain') return False if not id_token.get('email_verified', False) and \ current_app.config['OIDC_REQUIRE_VERIFIED_EMAIL']: logger.error('Email not verified') return False return True WRONG_GOOGLE_APPS_DOMAIN = 'WRONG_GOOGLE_APPS_DOMAIN' def custom_callback(self, view_func): """ Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. """ @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback('custom') if plainreturn: return data else: return view_func(data, *args, **kwargs) self._custom_callback = decorated return decorated def _oidc_callback(self): plainreturn, data = self._process_callback('destination') if plainreturn: return data else: return redirect(data) def _process_callback(self, statefield): """ Exchange the auth code for actual credentials, then redirect to the originally requested page. """ # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response def _oidc_error(self, message='Not Authorized', code=None): return (message, 401, { 'Content-Type': 'text/plain', }) def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout self._set_cookie_id_token(None) # Below here is for resource servers to validate tokens def validate_token(self, token, scopes_required=None): """ This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1 """ valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid) def _validate_token(self, token, scopes_required=None): """The actual implementation of validate_token.""" if scopes_required is None: scopes_required = [] scopes_required = set(scopes_required) token_info = None valid_token = False has_required_scopes = False if token: try: token_info = self._get_token_info(token) except Exception as ex: token_info = {'active': False} logger.error('ERROR: Unable to get token info') logger.error(str(ex)) valid_token = token_info.get('active', False) if 'aud' in token_info and \ current_app.config['OIDC_RESOURCE_CHECK_AUD']: valid_audience = False aud = token_info['aud'] clid = self.client_secrets['client_id'] if isinstance(aud, list): valid_audience = clid in aud else: valid_audience = clid == aud if not valid_audience: logger.error('Refused token because of invalid ' 'audience') valid_token = False if valid_token: token_scopes = token_info.get('scope', '').split(' ') else: token_scopes = [] has_required_scopes = scopes_required.issubset( set(token_scopes)) if not has_required_scopes: logger.debug('Token missed required scopes') if (valid_token and has_required_scopes): g.oidc_token_info = token_info return True if not valid_token: return 'Token required but invalid' elif not has_required_scopes: return 'Token does not have required scopes' else: return 'Something went wrong checking your token' def accept_token(self, require_token=False, scopes_required=None, render_errors=True): """ Use this to decorate view functions that should accept OAuth2 tokens, this will most likely apply to API functions. Tokens are accepted as part of the query URL (access_token value) or a POST form value (access_token). Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param require_token: Whether a token is required for the current function. If this is True, we will abort the request if there was no token provided. :type require_token: bool :param scopes_required: List of scopes that are required to be granted by the token before being allowed to call the protected function. :type scopes_required: list :param render_errors: Whether or not to eagerly render error objects as JSON API responses. Set to False to pass the error object back unmodified for later rendering. :type render_errors: callback(obj) or None .. versionadded:: 1.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): token = request.headers['Authorization'].split(None,1)[1].strip() if 'access_token' in request.form: token = request.form['access_token'] elif 'access_token' in request.args: token = request.args['access_token'] validity = self.validate_token(token, scopes_required) if (validity is True) or (not require_token): return view_func(*args, **kwargs) else: response_body = {'error': 'invalid_token', 'error_description': validity} if render_errors: response_body = json.dumps(response_body) return response_body, 401, {'WWW-Authenticate': 'Bearer'} return decorated return wrapper def _get_token_info(self, token): # We hardcode to use client_secret_post, because that's what the Google # oauth2client library defaults to request = {'token': token} headers = {'Content-type': 'application/x-www-form-urlencoded'} hint = current_app.config['OIDC_TOKEN_TYPE_HINT'] if hint != 'none': request['token_type_hint'] = hint auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] if (auth_method == 'client_secret_basic'): basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret']) basic_auth_bytes = bytearray(basic_auth_string, 'utf-8') headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8') elif (auth_method == 'bearer'): headers['Authorization'] = 'Bearer %s' % token elif (auth_method == 'client_secret_post'): request['client_id'] = self.client_secrets['client_id'] if self.client_secrets['client_secret'] is not None: request['client_secret'] = self.client_secrets['client_secret'] resp, content = httplib2.Http().request( self.client_secrets['token_introspection_uri'], 'POST', urlencode(request), headers=headers) # TODO: Cache this reply return _json_loads(content)
puiterwijk/flask-oidc
flask_oidc/__init__.py
OpenIDConnect._flow_for_request
python
def _flow_for_request(self): flow = copy(self.flow) redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI'] if not redirect_uri: flow.redirect_uri = url_for('_oidc_callback', _external=True) else: flow.redirect_uri = redirect_uri return flow
Build a flow with the correct absolute callback URL for this request. :return:
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L533-L544
null
class OpenIDConnect(object): """ The core OpenID Connect client object. """ def __init__(self, app=None, credentials_store=None, http=None, time=None, urandom=None): self.credentials_store = credentials_store\ if credentials_store is not None\ else MemoryCredentials() if http is not None: warn('HTTP argument is deprecated and unused', DeprecationWarning) if time is not None: warn('time argument is deprecated and unused', DeprecationWarning) if urandom is not None: warn('urandom argument is deprecated and unused', DeprecationWarning) # By default, we do not have a custom callback self._custom_callback = None # get stuff from the app's config, which may override stuff set above if app is not None: self.init_app(app) def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass def load_secrets(self, app): # Load client_secrets.json to pre-initialize some configuration content = app.config['OIDC_CLIENT_SECRETS'] if isinstance(content, dict): return content else: return _json_loads(open(content, 'r').read()) @property def user_loggedin(self): """ Represents whether the user is currently logged in. Returns: bool: Whether the user is logged in with Flask-OIDC. .. versionadded:: 1.0 """ return g.oidc_id_token is not None def user_getfield(self, field, access_token=None): """ Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0 """ info = self.user_getinfo([field], access_token) return info.get(field) def user_getinfo(self, fields, access_token=None): """ Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0 """ if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def get_refresh_token(self): """Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info def get_cookie_id_token(self): """ .. deprecated:: 1.0 Use :func:`user_getinfo` instead. """ warn('You are using a deprecated function (get_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._get_cookie_id_token() def _get_cookie_id_token(self): try: id_token_cookie = request.cookies.get(current_app.config[ 'OIDC_ID_TOKEN_COOKIE_NAME']) if not id_token_cookie: # Do not error if we were unable to get the cookie. # The user can debug this themselves. return None return self.cookie_serializer.loads(id_token_cookie) except SignatureExpired: logger.debug("Invalid ID token cookie", exc_info=True) return None except BadSignature: logger.info("Signature invalid for ID token cookie", exc_info=True) return None def set_cookie_id_token(self, id_token): """ .. deprecated:: 1.0 """ warn('You are using a deprecated function (set_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._set_cookie_id_token(id_token) def _set_cookie_id_token(self, id_token): """ Cooperates with @after_request to set a new ID token cookie. """ g.oidc_id_token = id_token g.oidc_id_token_dirty = True def _after_request(self, response): """ Set a new ID token cookie if the ID token has changed. """ # This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response def _before_request(self): g.oidc_id_token = None self.authenticate_or_redirect() def authenticate_or_redirect(self): """ Helper function suitable for @app.before_request and @check. Sets g.oidc_id_token to the ID token if the user has successfully authenticated, else returns a redirect object so they can go try to authenticate. :returns: A redirect object, or None if the user is logged in. :rtype: Redirect .. deprecated:: 1.0 Use :func:`require_login` instead. """ # the auth callback and error pages don't need user to be authenticated if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']): return None # retrieve signed ID token cookie id_token = self._get_cookie_id_token() if id_token is None: return self.redirect_to_auth_server(request.url) # ID token expired # when Google is the IdP, this happens after one hour if time.time() >= id_token['exp']: # get credentials from store try: credentials = OAuth2Credentials.from_json( self.credentials_store[id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return self.redirect_to_auth_server(request.url) # refresh and store credentials try: credentials.refresh(httplib2.Http()) if credentials.id_token: id_token = credentials.id_token else: # It is not guaranteed that we will get a new ID Token on # refresh, so if we do not, let's just update the id token # expiry field and reuse the existing ID Token. if credentials.token_expiry is None: logger.debug('Expired ID token, no new expiry. Falling' ' back to assuming 1 hour') id_token['exp'] = time.time() + 3600 else: id_token['exp'] = calendar.timegm( credentials.token_expiry.timetuple()) self.credentials_store[id_token['sub']] = credentials.to_json() self._set_cookie_id_token(id_token) except AccessTokenRefreshError: # Can't refresh. Wipe credentials and redirect user to IdP # for re-authentication. logger.debug("Expired ID token, can't refresh credentials", exc_info=True) del self.credentials_store[id_token['sub']] return self.redirect_to_auth_server(request.url) # make ID token available to views g.oidc_id_token = id_token return None def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """ @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated # Backwards compatibility check = require_login """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ def require_keycloak_role(self, client, role): """ Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper def flow_for_request(self): """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ warn('You are using a deprecated function (flow_for_request). ' 'Please reconsider using this', DeprecationWarning) return self._flow_for_request() def redirect_to_auth_server(self, destination=None, customstate=None): """ Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead. """ if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url) def _is_id_token_valid(self, id_token): """ Check if `id_token` is a current ID token for this application, was issued by the Apps domain we expected, and that the email address has been verified. @see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation """ if not id_token: return False # step 2: check issuer if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']: logger.error('id_token issued by non-trusted issuer: %s' % id_token['iss']) return False if isinstance(id_token['aud'], list): # step 3 for audience list if self.flow.client_id not in id_token['aud']: logger.error('We are not a valid audience') return False # step 4 if 'azp' not in id_token and len(id_token['aud']) > 1: logger.error('Multiple audiences and not authorized party') return False else: # step 3 for single audience if id_token['aud'] != self.flow.client_id: logger.error('We are not the audience') return False # step 5 if 'azp' in id_token and id_token['azp'] != self.flow.client_id: logger.error('Authorized Party is not us') return False # step 6-8: TLS checked # step 9: check exp if int(time.time()) >= int(id_token['exp']): logger.error('Token has expired') return False # step 10: check iat if id_token['iat'] < (time.time() - current_app.config['OIDC_CLOCK_SKEW']): logger.error('Token issued in the past') return False # (not required if using HTTPS?) step 11: check nonce # step 12-13: not requested acr or auth_time, so not needed to test # additional steps specific to our usage if current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] and \ id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: logger.error('Invalid google apps domain') return False if not id_token.get('email_verified', False) and \ current_app.config['OIDC_REQUIRE_VERIFIED_EMAIL']: logger.error('Email not verified') return False return True WRONG_GOOGLE_APPS_DOMAIN = 'WRONG_GOOGLE_APPS_DOMAIN' def custom_callback(self, view_func): """ Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. """ @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback('custom') if plainreturn: return data else: return view_func(data, *args, **kwargs) self._custom_callback = decorated return decorated def _oidc_callback(self): plainreturn, data = self._process_callback('destination') if plainreturn: return data else: return redirect(data) def _process_callback(self, statefield): """ Exchange the auth code for actual credentials, then redirect to the originally requested page. """ # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response def _oidc_error(self, message='Not Authorized', code=None): return (message, 401, { 'Content-Type': 'text/plain', }) def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout self._set_cookie_id_token(None) # Below here is for resource servers to validate tokens def validate_token(self, token, scopes_required=None): """ This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1 """ valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid) def _validate_token(self, token, scopes_required=None): """The actual implementation of validate_token.""" if scopes_required is None: scopes_required = [] scopes_required = set(scopes_required) token_info = None valid_token = False has_required_scopes = False if token: try: token_info = self._get_token_info(token) except Exception as ex: token_info = {'active': False} logger.error('ERROR: Unable to get token info') logger.error(str(ex)) valid_token = token_info.get('active', False) if 'aud' in token_info and \ current_app.config['OIDC_RESOURCE_CHECK_AUD']: valid_audience = False aud = token_info['aud'] clid = self.client_secrets['client_id'] if isinstance(aud, list): valid_audience = clid in aud else: valid_audience = clid == aud if not valid_audience: logger.error('Refused token because of invalid ' 'audience') valid_token = False if valid_token: token_scopes = token_info.get('scope', '').split(' ') else: token_scopes = [] has_required_scopes = scopes_required.issubset( set(token_scopes)) if not has_required_scopes: logger.debug('Token missed required scopes') if (valid_token and has_required_scopes): g.oidc_token_info = token_info return True if not valid_token: return 'Token required but invalid' elif not has_required_scopes: return 'Token does not have required scopes' else: return 'Something went wrong checking your token' def accept_token(self, require_token=False, scopes_required=None, render_errors=True): """ Use this to decorate view functions that should accept OAuth2 tokens, this will most likely apply to API functions. Tokens are accepted as part of the query URL (access_token value) or a POST form value (access_token). Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param require_token: Whether a token is required for the current function. If this is True, we will abort the request if there was no token provided. :type require_token: bool :param scopes_required: List of scopes that are required to be granted by the token before being allowed to call the protected function. :type scopes_required: list :param render_errors: Whether or not to eagerly render error objects as JSON API responses. Set to False to pass the error object back unmodified for later rendering. :type render_errors: callback(obj) or None .. versionadded:: 1.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): token = request.headers['Authorization'].split(None,1)[1].strip() if 'access_token' in request.form: token = request.form['access_token'] elif 'access_token' in request.args: token = request.args['access_token'] validity = self.validate_token(token, scopes_required) if (validity is True) or (not require_token): return view_func(*args, **kwargs) else: response_body = {'error': 'invalid_token', 'error_description': validity} if render_errors: response_body = json.dumps(response_body) return response_body, 401, {'WWW-Authenticate': 'Bearer'} return decorated return wrapper def _get_token_info(self, token): # We hardcode to use client_secret_post, because that's what the Google # oauth2client library defaults to request = {'token': token} headers = {'Content-type': 'application/x-www-form-urlencoded'} hint = current_app.config['OIDC_TOKEN_TYPE_HINT'] if hint != 'none': request['token_type_hint'] = hint auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] if (auth_method == 'client_secret_basic'): basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret']) basic_auth_bytes = bytearray(basic_auth_string, 'utf-8') headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8') elif (auth_method == 'bearer'): headers['Authorization'] = 'Bearer %s' % token elif (auth_method == 'client_secret_post'): request['client_id'] = self.client_secrets['client_id'] if self.client_secrets['client_secret'] is not None: request['client_secret'] = self.client_secrets['client_secret'] resp, content = httplib2.Http().request( self.client_secrets['token_introspection_uri'], 'POST', urlencode(request), headers=headers) # TODO: Cache this reply return _json_loads(content)
puiterwijk/flask-oidc
flask_oidc/__init__.py
OpenIDConnect.redirect_to_auth_server
python
def redirect_to_auth_server(self, destination=None, customstate=None): if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url)
Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead.
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L546-L597
[ "def _set_cookie_id_token(self, id_token):\n \"\"\"\n Cooperates with @after_request to set a new ID token cookie.\n \"\"\"\n g.oidc_id_token = id_token\n g.oidc_id_token_dirty = True\n", "def _flow_for_request(self):\n \"\"\"\n Build a flow with the correct absolute callback URL for this request.\n :return:\n \"\"\"\n flow = copy(self.flow)\n redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI']\n if not redirect_uri:\n flow.redirect_uri = url_for('_oidc_callback', _external=True)\n else:\n flow.redirect_uri = redirect_uri\n return flow\n" ]
class OpenIDConnect(object): """ The core OpenID Connect client object. """ def __init__(self, app=None, credentials_store=None, http=None, time=None, urandom=None): self.credentials_store = credentials_store\ if credentials_store is not None\ else MemoryCredentials() if http is not None: warn('HTTP argument is deprecated and unused', DeprecationWarning) if time is not None: warn('time argument is deprecated and unused', DeprecationWarning) if urandom is not None: warn('urandom argument is deprecated and unused', DeprecationWarning) # By default, we do not have a custom callback self._custom_callback = None # get stuff from the app's config, which may override stuff set above if app is not None: self.init_app(app) def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass def load_secrets(self, app): # Load client_secrets.json to pre-initialize some configuration content = app.config['OIDC_CLIENT_SECRETS'] if isinstance(content, dict): return content else: return _json_loads(open(content, 'r').read()) @property def user_loggedin(self): """ Represents whether the user is currently logged in. Returns: bool: Whether the user is logged in with Flask-OIDC. .. versionadded:: 1.0 """ return g.oidc_id_token is not None def user_getfield(self, field, access_token=None): """ Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0 """ info = self.user_getinfo([field], access_token) return info.get(field) def user_getinfo(self, fields, access_token=None): """ Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0 """ if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def get_refresh_token(self): """Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info def get_cookie_id_token(self): """ .. deprecated:: 1.0 Use :func:`user_getinfo` instead. """ warn('You are using a deprecated function (get_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._get_cookie_id_token() def _get_cookie_id_token(self): try: id_token_cookie = request.cookies.get(current_app.config[ 'OIDC_ID_TOKEN_COOKIE_NAME']) if not id_token_cookie: # Do not error if we were unable to get the cookie. # The user can debug this themselves. return None return self.cookie_serializer.loads(id_token_cookie) except SignatureExpired: logger.debug("Invalid ID token cookie", exc_info=True) return None except BadSignature: logger.info("Signature invalid for ID token cookie", exc_info=True) return None def set_cookie_id_token(self, id_token): """ .. deprecated:: 1.0 """ warn('You are using a deprecated function (set_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._set_cookie_id_token(id_token) def _set_cookie_id_token(self, id_token): """ Cooperates with @after_request to set a new ID token cookie. """ g.oidc_id_token = id_token g.oidc_id_token_dirty = True def _after_request(self, response): """ Set a new ID token cookie if the ID token has changed. """ # This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response def _before_request(self): g.oidc_id_token = None self.authenticate_or_redirect() def authenticate_or_redirect(self): """ Helper function suitable for @app.before_request and @check. Sets g.oidc_id_token to the ID token if the user has successfully authenticated, else returns a redirect object so they can go try to authenticate. :returns: A redirect object, or None if the user is logged in. :rtype: Redirect .. deprecated:: 1.0 Use :func:`require_login` instead. """ # the auth callback and error pages don't need user to be authenticated if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']): return None # retrieve signed ID token cookie id_token = self._get_cookie_id_token() if id_token is None: return self.redirect_to_auth_server(request.url) # ID token expired # when Google is the IdP, this happens after one hour if time.time() >= id_token['exp']: # get credentials from store try: credentials = OAuth2Credentials.from_json( self.credentials_store[id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return self.redirect_to_auth_server(request.url) # refresh and store credentials try: credentials.refresh(httplib2.Http()) if credentials.id_token: id_token = credentials.id_token else: # It is not guaranteed that we will get a new ID Token on # refresh, so if we do not, let's just update the id token # expiry field and reuse the existing ID Token. if credentials.token_expiry is None: logger.debug('Expired ID token, no new expiry. Falling' ' back to assuming 1 hour') id_token['exp'] = time.time() + 3600 else: id_token['exp'] = calendar.timegm( credentials.token_expiry.timetuple()) self.credentials_store[id_token['sub']] = credentials.to_json() self._set_cookie_id_token(id_token) except AccessTokenRefreshError: # Can't refresh. Wipe credentials and redirect user to IdP # for re-authentication. logger.debug("Expired ID token, can't refresh credentials", exc_info=True) del self.credentials_store[id_token['sub']] return self.redirect_to_auth_server(request.url) # make ID token available to views g.oidc_id_token = id_token return None def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """ @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated # Backwards compatibility check = require_login """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ def require_keycloak_role(self, client, role): """ Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper def flow_for_request(self): """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ warn('You are using a deprecated function (flow_for_request). ' 'Please reconsider using this', DeprecationWarning) return self._flow_for_request() def _flow_for_request(self): """ Build a flow with the correct absolute callback URL for this request. :return: """ flow = copy(self.flow) redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI'] if not redirect_uri: flow.redirect_uri = url_for('_oidc_callback', _external=True) else: flow.redirect_uri = redirect_uri return flow def _is_id_token_valid(self, id_token): """ Check if `id_token` is a current ID token for this application, was issued by the Apps domain we expected, and that the email address has been verified. @see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation """ if not id_token: return False # step 2: check issuer if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']: logger.error('id_token issued by non-trusted issuer: %s' % id_token['iss']) return False if isinstance(id_token['aud'], list): # step 3 for audience list if self.flow.client_id not in id_token['aud']: logger.error('We are not a valid audience') return False # step 4 if 'azp' not in id_token and len(id_token['aud']) > 1: logger.error('Multiple audiences and not authorized party') return False else: # step 3 for single audience if id_token['aud'] != self.flow.client_id: logger.error('We are not the audience') return False # step 5 if 'azp' in id_token and id_token['azp'] != self.flow.client_id: logger.error('Authorized Party is not us') return False # step 6-8: TLS checked # step 9: check exp if int(time.time()) >= int(id_token['exp']): logger.error('Token has expired') return False # step 10: check iat if id_token['iat'] < (time.time() - current_app.config['OIDC_CLOCK_SKEW']): logger.error('Token issued in the past') return False # (not required if using HTTPS?) step 11: check nonce # step 12-13: not requested acr or auth_time, so not needed to test # additional steps specific to our usage if current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] and \ id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: logger.error('Invalid google apps domain') return False if not id_token.get('email_verified', False) and \ current_app.config['OIDC_REQUIRE_VERIFIED_EMAIL']: logger.error('Email not verified') return False return True WRONG_GOOGLE_APPS_DOMAIN = 'WRONG_GOOGLE_APPS_DOMAIN' def custom_callback(self, view_func): """ Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. """ @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback('custom') if plainreturn: return data else: return view_func(data, *args, **kwargs) self._custom_callback = decorated return decorated def _oidc_callback(self): plainreturn, data = self._process_callback('destination') if plainreturn: return data else: return redirect(data) def _process_callback(self, statefield): """ Exchange the auth code for actual credentials, then redirect to the originally requested page. """ # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response def _oidc_error(self, message='Not Authorized', code=None): return (message, 401, { 'Content-Type': 'text/plain', }) def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout self._set_cookie_id_token(None) # Below here is for resource servers to validate tokens def validate_token(self, token, scopes_required=None): """ This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1 """ valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid) def _validate_token(self, token, scopes_required=None): """The actual implementation of validate_token.""" if scopes_required is None: scopes_required = [] scopes_required = set(scopes_required) token_info = None valid_token = False has_required_scopes = False if token: try: token_info = self._get_token_info(token) except Exception as ex: token_info = {'active': False} logger.error('ERROR: Unable to get token info') logger.error(str(ex)) valid_token = token_info.get('active', False) if 'aud' in token_info and \ current_app.config['OIDC_RESOURCE_CHECK_AUD']: valid_audience = False aud = token_info['aud'] clid = self.client_secrets['client_id'] if isinstance(aud, list): valid_audience = clid in aud else: valid_audience = clid == aud if not valid_audience: logger.error('Refused token because of invalid ' 'audience') valid_token = False if valid_token: token_scopes = token_info.get('scope', '').split(' ') else: token_scopes = [] has_required_scopes = scopes_required.issubset( set(token_scopes)) if not has_required_scopes: logger.debug('Token missed required scopes') if (valid_token and has_required_scopes): g.oidc_token_info = token_info return True if not valid_token: return 'Token required but invalid' elif not has_required_scopes: return 'Token does not have required scopes' else: return 'Something went wrong checking your token' def accept_token(self, require_token=False, scopes_required=None, render_errors=True): """ Use this to decorate view functions that should accept OAuth2 tokens, this will most likely apply to API functions. Tokens are accepted as part of the query URL (access_token value) or a POST form value (access_token). Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param require_token: Whether a token is required for the current function. If this is True, we will abort the request if there was no token provided. :type require_token: bool :param scopes_required: List of scopes that are required to be granted by the token before being allowed to call the protected function. :type scopes_required: list :param render_errors: Whether or not to eagerly render error objects as JSON API responses. Set to False to pass the error object back unmodified for later rendering. :type render_errors: callback(obj) or None .. versionadded:: 1.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): token = request.headers['Authorization'].split(None,1)[1].strip() if 'access_token' in request.form: token = request.form['access_token'] elif 'access_token' in request.args: token = request.args['access_token'] validity = self.validate_token(token, scopes_required) if (validity is True) or (not require_token): return view_func(*args, **kwargs) else: response_body = {'error': 'invalid_token', 'error_description': validity} if render_errors: response_body = json.dumps(response_body) return response_body, 401, {'WWW-Authenticate': 'Bearer'} return decorated return wrapper def _get_token_info(self, token): # We hardcode to use client_secret_post, because that's what the Google # oauth2client library defaults to request = {'token': token} headers = {'Content-type': 'application/x-www-form-urlencoded'} hint = current_app.config['OIDC_TOKEN_TYPE_HINT'] if hint != 'none': request['token_type_hint'] = hint auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] if (auth_method == 'client_secret_basic'): basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret']) basic_auth_bytes = bytearray(basic_auth_string, 'utf-8') headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8') elif (auth_method == 'bearer'): headers['Authorization'] = 'Bearer %s' % token elif (auth_method == 'client_secret_post'): request['client_id'] = self.client_secrets['client_id'] if self.client_secrets['client_secret'] is not None: request['client_secret'] = self.client_secrets['client_secret'] resp, content = httplib2.Http().request( self.client_secrets['token_introspection_uri'], 'POST', urlencode(request), headers=headers) # TODO: Cache this reply return _json_loads(content)
puiterwijk/flask-oidc
flask_oidc/__init__.py
OpenIDConnect._is_id_token_valid
python
def _is_id_token_valid(self, id_token): if not id_token: return False # step 2: check issuer if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']: logger.error('id_token issued by non-trusted issuer: %s' % id_token['iss']) return False if isinstance(id_token['aud'], list): # step 3 for audience list if self.flow.client_id not in id_token['aud']: logger.error('We are not a valid audience') return False # step 4 if 'azp' not in id_token and len(id_token['aud']) > 1: logger.error('Multiple audiences and not authorized party') return False else: # step 3 for single audience if id_token['aud'] != self.flow.client_id: logger.error('We are not the audience') return False # step 5 if 'azp' in id_token and id_token['azp'] != self.flow.client_id: logger.error('Authorized Party is not us') return False # step 6-8: TLS checked # step 9: check exp if int(time.time()) >= int(id_token['exp']): logger.error('Token has expired') return False # step 10: check iat if id_token['iat'] < (time.time() - current_app.config['OIDC_CLOCK_SKEW']): logger.error('Token issued in the past') return False # (not required if using HTTPS?) step 11: check nonce # step 12-13: not requested acr or auth_time, so not needed to test # additional steps specific to our usage if current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] and \ id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: logger.error('Invalid google apps domain') return False if not id_token.get('email_verified', False) and \ current_app.config['OIDC_REQUIRE_VERIFIED_EMAIL']: logger.error('Email not verified') return False return True
Check if `id_token` is a current ID token for this application, was issued by the Apps domain we expected, and that the email address has been verified. @see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L599-L665
null
class OpenIDConnect(object): """ The core OpenID Connect client object. """ def __init__(self, app=None, credentials_store=None, http=None, time=None, urandom=None): self.credentials_store = credentials_store\ if credentials_store is not None\ else MemoryCredentials() if http is not None: warn('HTTP argument is deprecated and unused', DeprecationWarning) if time is not None: warn('time argument is deprecated and unused', DeprecationWarning) if urandom is not None: warn('urandom argument is deprecated and unused', DeprecationWarning) # By default, we do not have a custom callback self._custom_callback = None # get stuff from the app's config, which may override stuff set above if app is not None: self.init_app(app) def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass def load_secrets(self, app): # Load client_secrets.json to pre-initialize some configuration content = app.config['OIDC_CLIENT_SECRETS'] if isinstance(content, dict): return content else: return _json_loads(open(content, 'r').read()) @property def user_loggedin(self): """ Represents whether the user is currently logged in. Returns: bool: Whether the user is logged in with Flask-OIDC. .. versionadded:: 1.0 """ return g.oidc_id_token is not None def user_getfield(self, field, access_token=None): """ Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0 """ info = self.user_getinfo([field], access_token) return info.get(field) def user_getinfo(self, fields, access_token=None): """ Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0 """ if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def get_refresh_token(self): """Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info def get_cookie_id_token(self): """ .. deprecated:: 1.0 Use :func:`user_getinfo` instead. """ warn('You are using a deprecated function (get_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._get_cookie_id_token() def _get_cookie_id_token(self): try: id_token_cookie = request.cookies.get(current_app.config[ 'OIDC_ID_TOKEN_COOKIE_NAME']) if not id_token_cookie: # Do not error if we were unable to get the cookie. # The user can debug this themselves. return None return self.cookie_serializer.loads(id_token_cookie) except SignatureExpired: logger.debug("Invalid ID token cookie", exc_info=True) return None except BadSignature: logger.info("Signature invalid for ID token cookie", exc_info=True) return None def set_cookie_id_token(self, id_token): """ .. deprecated:: 1.0 """ warn('You are using a deprecated function (set_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._set_cookie_id_token(id_token) def _set_cookie_id_token(self, id_token): """ Cooperates with @after_request to set a new ID token cookie. """ g.oidc_id_token = id_token g.oidc_id_token_dirty = True def _after_request(self, response): """ Set a new ID token cookie if the ID token has changed. """ # This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response def _before_request(self): g.oidc_id_token = None self.authenticate_or_redirect() def authenticate_or_redirect(self): """ Helper function suitable for @app.before_request and @check. Sets g.oidc_id_token to the ID token if the user has successfully authenticated, else returns a redirect object so they can go try to authenticate. :returns: A redirect object, or None if the user is logged in. :rtype: Redirect .. deprecated:: 1.0 Use :func:`require_login` instead. """ # the auth callback and error pages don't need user to be authenticated if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']): return None # retrieve signed ID token cookie id_token = self._get_cookie_id_token() if id_token is None: return self.redirect_to_auth_server(request.url) # ID token expired # when Google is the IdP, this happens after one hour if time.time() >= id_token['exp']: # get credentials from store try: credentials = OAuth2Credentials.from_json( self.credentials_store[id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return self.redirect_to_auth_server(request.url) # refresh and store credentials try: credentials.refresh(httplib2.Http()) if credentials.id_token: id_token = credentials.id_token else: # It is not guaranteed that we will get a new ID Token on # refresh, so if we do not, let's just update the id token # expiry field and reuse the existing ID Token. if credentials.token_expiry is None: logger.debug('Expired ID token, no new expiry. Falling' ' back to assuming 1 hour') id_token['exp'] = time.time() + 3600 else: id_token['exp'] = calendar.timegm( credentials.token_expiry.timetuple()) self.credentials_store[id_token['sub']] = credentials.to_json() self._set_cookie_id_token(id_token) except AccessTokenRefreshError: # Can't refresh. Wipe credentials and redirect user to IdP # for re-authentication. logger.debug("Expired ID token, can't refresh credentials", exc_info=True) del self.credentials_store[id_token['sub']] return self.redirect_to_auth_server(request.url) # make ID token available to views g.oidc_id_token = id_token return None def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """ @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated # Backwards compatibility check = require_login """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ def require_keycloak_role(self, client, role): """ Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper def flow_for_request(self): """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ warn('You are using a deprecated function (flow_for_request). ' 'Please reconsider using this', DeprecationWarning) return self._flow_for_request() def _flow_for_request(self): """ Build a flow with the correct absolute callback URL for this request. :return: """ flow = copy(self.flow) redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI'] if not redirect_uri: flow.redirect_uri = url_for('_oidc_callback', _external=True) else: flow.redirect_uri = redirect_uri return flow def redirect_to_auth_server(self, destination=None, customstate=None): """ Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead. """ if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url) WRONG_GOOGLE_APPS_DOMAIN = 'WRONG_GOOGLE_APPS_DOMAIN' def custom_callback(self, view_func): """ Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. """ @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback('custom') if plainreturn: return data else: return view_func(data, *args, **kwargs) self._custom_callback = decorated return decorated def _oidc_callback(self): plainreturn, data = self._process_callback('destination') if plainreturn: return data else: return redirect(data) def _process_callback(self, statefield): """ Exchange the auth code for actual credentials, then redirect to the originally requested page. """ # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response def _oidc_error(self, message='Not Authorized', code=None): return (message, 401, { 'Content-Type': 'text/plain', }) def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout self._set_cookie_id_token(None) # Below here is for resource servers to validate tokens def validate_token(self, token, scopes_required=None): """ This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1 """ valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid) def _validate_token(self, token, scopes_required=None): """The actual implementation of validate_token.""" if scopes_required is None: scopes_required = [] scopes_required = set(scopes_required) token_info = None valid_token = False has_required_scopes = False if token: try: token_info = self._get_token_info(token) except Exception as ex: token_info = {'active': False} logger.error('ERROR: Unable to get token info') logger.error(str(ex)) valid_token = token_info.get('active', False) if 'aud' in token_info and \ current_app.config['OIDC_RESOURCE_CHECK_AUD']: valid_audience = False aud = token_info['aud'] clid = self.client_secrets['client_id'] if isinstance(aud, list): valid_audience = clid in aud else: valid_audience = clid == aud if not valid_audience: logger.error('Refused token because of invalid ' 'audience') valid_token = False if valid_token: token_scopes = token_info.get('scope', '').split(' ') else: token_scopes = [] has_required_scopes = scopes_required.issubset( set(token_scopes)) if not has_required_scopes: logger.debug('Token missed required scopes') if (valid_token and has_required_scopes): g.oidc_token_info = token_info return True if not valid_token: return 'Token required but invalid' elif not has_required_scopes: return 'Token does not have required scopes' else: return 'Something went wrong checking your token' def accept_token(self, require_token=False, scopes_required=None, render_errors=True): """ Use this to decorate view functions that should accept OAuth2 tokens, this will most likely apply to API functions. Tokens are accepted as part of the query URL (access_token value) or a POST form value (access_token). Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param require_token: Whether a token is required for the current function. If this is True, we will abort the request if there was no token provided. :type require_token: bool :param scopes_required: List of scopes that are required to be granted by the token before being allowed to call the protected function. :type scopes_required: list :param render_errors: Whether or not to eagerly render error objects as JSON API responses. Set to False to pass the error object back unmodified for later rendering. :type render_errors: callback(obj) or None .. versionadded:: 1.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): token = request.headers['Authorization'].split(None,1)[1].strip() if 'access_token' in request.form: token = request.form['access_token'] elif 'access_token' in request.args: token = request.args['access_token'] validity = self.validate_token(token, scopes_required) if (validity is True) or (not require_token): return view_func(*args, **kwargs) else: response_body = {'error': 'invalid_token', 'error_description': validity} if render_errors: response_body = json.dumps(response_body) return response_body, 401, {'WWW-Authenticate': 'Bearer'} return decorated return wrapper def _get_token_info(self, token): # We hardcode to use client_secret_post, because that's what the Google # oauth2client library defaults to request = {'token': token} headers = {'Content-type': 'application/x-www-form-urlencoded'} hint = current_app.config['OIDC_TOKEN_TYPE_HINT'] if hint != 'none': request['token_type_hint'] = hint auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] if (auth_method == 'client_secret_basic'): basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret']) basic_auth_bytes = bytearray(basic_auth_string, 'utf-8') headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8') elif (auth_method == 'bearer'): headers['Authorization'] = 'Bearer %s' % token elif (auth_method == 'client_secret_post'): request['client_id'] = self.client_secrets['client_id'] if self.client_secrets['client_secret'] is not None: request['client_secret'] = self.client_secrets['client_secret'] resp, content = httplib2.Http().request( self.client_secrets['token_introspection_uri'], 'POST', urlencode(request), headers=headers) # TODO: Cache this reply return _json_loads(content)
puiterwijk/flask-oidc
flask_oidc/__init__.py
OpenIDConnect.custom_callback
python
def custom_callback(self, view_func): @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback('custom') if plainreturn: return data else: return view_func(data, *args, **kwargs) self._custom_callback = decorated return decorated
Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server.
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L669-L683
null
class OpenIDConnect(object): """ The core OpenID Connect client object. """ def __init__(self, app=None, credentials_store=None, http=None, time=None, urandom=None): self.credentials_store = credentials_store\ if credentials_store is not None\ else MemoryCredentials() if http is not None: warn('HTTP argument is deprecated and unused', DeprecationWarning) if time is not None: warn('time argument is deprecated and unused', DeprecationWarning) if urandom is not None: warn('urandom argument is deprecated and unused', DeprecationWarning) # By default, we do not have a custom callback self._custom_callback = None # get stuff from the app's config, which may override stuff set above if app is not None: self.init_app(app) def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass def load_secrets(self, app): # Load client_secrets.json to pre-initialize some configuration content = app.config['OIDC_CLIENT_SECRETS'] if isinstance(content, dict): return content else: return _json_loads(open(content, 'r').read()) @property def user_loggedin(self): """ Represents whether the user is currently logged in. Returns: bool: Whether the user is logged in with Flask-OIDC. .. versionadded:: 1.0 """ return g.oidc_id_token is not None def user_getfield(self, field, access_token=None): """ Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0 """ info = self.user_getinfo([field], access_token) return info.get(field) def user_getinfo(self, fields, access_token=None): """ Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0 """ if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def get_refresh_token(self): """Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info def get_cookie_id_token(self): """ .. deprecated:: 1.0 Use :func:`user_getinfo` instead. """ warn('You are using a deprecated function (get_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._get_cookie_id_token() def _get_cookie_id_token(self): try: id_token_cookie = request.cookies.get(current_app.config[ 'OIDC_ID_TOKEN_COOKIE_NAME']) if not id_token_cookie: # Do not error if we were unable to get the cookie. # The user can debug this themselves. return None return self.cookie_serializer.loads(id_token_cookie) except SignatureExpired: logger.debug("Invalid ID token cookie", exc_info=True) return None except BadSignature: logger.info("Signature invalid for ID token cookie", exc_info=True) return None def set_cookie_id_token(self, id_token): """ .. deprecated:: 1.0 """ warn('You are using a deprecated function (set_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._set_cookie_id_token(id_token) def _set_cookie_id_token(self, id_token): """ Cooperates with @after_request to set a new ID token cookie. """ g.oidc_id_token = id_token g.oidc_id_token_dirty = True def _after_request(self, response): """ Set a new ID token cookie if the ID token has changed. """ # This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response def _before_request(self): g.oidc_id_token = None self.authenticate_or_redirect() def authenticate_or_redirect(self): """ Helper function suitable for @app.before_request and @check. Sets g.oidc_id_token to the ID token if the user has successfully authenticated, else returns a redirect object so they can go try to authenticate. :returns: A redirect object, or None if the user is logged in. :rtype: Redirect .. deprecated:: 1.0 Use :func:`require_login` instead. """ # the auth callback and error pages don't need user to be authenticated if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']): return None # retrieve signed ID token cookie id_token = self._get_cookie_id_token() if id_token is None: return self.redirect_to_auth_server(request.url) # ID token expired # when Google is the IdP, this happens after one hour if time.time() >= id_token['exp']: # get credentials from store try: credentials = OAuth2Credentials.from_json( self.credentials_store[id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return self.redirect_to_auth_server(request.url) # refresh and store credentials try: credentials.refresh(httplib2.Http()) if credentials.id_token: id_token = credentials.id_token else: # It is not guaranteed that we will get a new ID Token on # refresh, so if we do not, let's just update the id token # expiry field and reuse the existing ID Token. if credentials.token_expiry is None: logger.debug('Expired ID token, no new expiry. Falling' ' back to assuming 1 hour') id_token['exp'] = time.time() + 3600 else: id_token['exp'] = calendar.timegm( credentials.token_expiry.timetuple()) self.credentials_store[id_token['sub']] = credentials.to_json() self._set_cookie_id_token(id_token) except AccessTokenRefreshError: # Can't refresh. Wipe credentials and redirect user to IdP # for re-authentication. logger.debug("Expired ID token, can't refresh credentials", exc_info=True) del self.credentials_store[id_token['sub']] return self.redirect_to_auth_server(request.url) # make ID token available to views g.oidc_id_token = id_token return None def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """ @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated # Backwards compatibility check = require_login """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ def require_keycloak_role(self, client, role): """ Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper def flow_for_request(self): """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ warn('You are using a deprecated function (flow_for_request). ' 'Please reconsider using this', DeprecationWarning) return self._flow_for_request() def _flow_for_request(self): """ Build a flow with the correct absolute callback URL for this request. :return: """ flow = copy(self.flow) redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI'] if not redirect_uri: flow.redirect_uri = url_for('_oidc_callback', _external=True) else: flow.redirect_uri = redirect_uri return flow def redirect_to_auth_server(self, destination=None, customstate=None): """ Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead. """ if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url) def _is_id_token_valid(self, id_token): """ Check if `id_token` is a current ID token for this application, was issued by the Apps domain we expected, and that the email address has been verified. @see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation """ if not id_token: return False # step 2: check issuer if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']: logger.error('id_token issued by non-trusted issuer: %s' % id_token['iss']) return False if isinstance(id_token['aud'], list): # step 3 for audience list if self.flow.client_id not in id_token['aud']: logger.error('We are not a valid audience') return False # step 4 if 'azp' not in id_token and len(id_token['aud']) > 1: logger.error('Multiple audiences and not authorized party') return False else: # step 3 for single audience if id_token['aud'] != self.flow.client_id: logger.error('We are not the audience') return False # step 5 if 'azp' in id_token and id_token['azp'] != self.flow.client_id: logger.error('Authorized Party is not us') return False # step 6-8: TLS checked # step 9: check exp if int(time.time()) >= int(id_token['exp']): logger.error('Token has expired') return False # step 10: check iat if id_token['iat'] < (time.time() - current_app.config['OIDC_CLOCK_SKEW']): logger.error('Token issued in the past') return False # (not required if using HTTPS?) step 11: check nonce # step 12-13: not requested acr or auth_time, so not needed to test # additional steps specific to our usage if current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] and \ id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: logger.error('Invalid google apps domain') return False if not id_token.get('email_verified', False) and \ current_app.config['OIDC_REQUIRE_VERIFIED_EMAIL']: logger.error('Email not verified') return False return True WRONG_GOOGLE_APPS_DOMAIN = 'WRONG_GOOGLE_APPS_DOMAIN' def _oidc_callback(self): plainreturn, data = self._process_callback('destination') if plainreturn: return data else: return redirect(data) def _process_callback(self, statefield): """ Exchange the auth code for actual credentials, then redirect to the originally requested page. """ # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response def _oidc_error(self, message='Not Authorized', code=None): return (message, 401, { 'Content-Type': 'text/plain', }) def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout self._set_cookie_id_token(None) # Below here is for resource servers to validate tokens def validate_token(self, token, scopes_required=None): """ This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1 """ valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid) def _validate_token(self, token, scopes_required=None): """The actual implementation of validate_token.""" if scopes_required is None: scopes_required = [] scopes_required = set(scopes_required) token_info = None valid_token = False has_required_scopes = False if token: try: token_info = self._get_token_info(token) except Exception as ex: token_info = {'active': False} logger.error('ERROR: Unable to get token info') logger.error(str(ex)) valid_token = token_info.get('active', False) if 'aud' in token_info and \ current_app.config['OIDC_RESOURCE_CHECK_AUD']: valid_audience = False aud = token_info['aud'] clid = self.client_secrets['client_id'] if isinstance(aud, list): valid_audience = clid in aud else: valid_audience = clid == aud if not valid_audience: logger.error('Refused token because of invalid ' 'audience') valid_token = False if valid_token: token_scopes = token_info.get('scope', '').split(' ') else: token_scopes = [] has_required_scopes = scopes_required.issubset( set(token_scopes)) if not has_required_scopes: logger.debug('Token missed required scopes') if (valid_token and has_required_scopes): g.oidc_token_info = token_info return True if not valid_token: return 'Token required but invalid' elif not has_required_scopes: return 'Token does not have required scopes' else: return 'Something went wrong checking your token' def accept_token(self, require_token=False, scopes_required=None, render_errors=True): """ Use this to decorate view functions that should accept OAuth2 tokens, this will most likely apply to API functions. Tokens are accepted as part of the query URL (access_token value) or a POST form value (access_token). Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param require_token: Whether a token is required for the current function. If this is True, we will abort the request if there was no token provided. :type require_token: bool :param scopes_required: List of scopes that are required to be granted by the token before being allowed to call the protected function. :type scopes_required: list :param render_errors: Whether or not to eagerly render error objects as JSON API responses. Set to False to pass the error object back unmodified for later rendering. :type render_errors: callback(obj) or None .. versionadded:: 1.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): token = request.headers['Authorization'].split(None,1)[1].strip() if 'access_token' in request.form: token = request.form['access_token'] elif 'access_token' in request.args: token = request.args['access_token'] validity = self.validate_token(token, scopes_required) if (validity is True) or (not require_token): return view_func(*args, **kwargs) else: response_body = {'error': 'invalid_token', 'error_description': validity} if render_errors: response_body = json.dumps(response_body) return response_body, 401, {'WWW-Authenticate': 'Bearer'} return decorated return wrapper def _get_token_info(self, token): # We hardcode to use client_secret_post, because that's what the Google # oauth2client library defaults to request = {'token': token} headers = {'Content-type': 'application/x-www-form-urlencoded'} hint = current_app.config['OIDC_TOKEN_TYPE_HINT'] if hint != 'none': request['token_type_hint'] = hint auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] if (auth_method == 'client_secret_basic'): basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret']) basic_auth_bytes = bytearray(basic_auth_string, 'utf-8') headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8') elif (auth_method == 'bearer'): headers['Authorization'] = 'Bearer %s' % token elif (auth_method == 'client_secret_post'): request['client_id'] = self.client_secrets['client_id'] if self.client_secrets['client_secret'] is not None: request['client_secret'] = self.client_secrets['client_secret'] resp, content = httplib2.Http().request( self.client_secrets['token_introspection_uri'], 'POST', urlencode(request), headers=headers) # TODO: Cache this reply return _json_loads(content)
puiterwijk/flask-oidc
flask_oidc/__init__.py
OpenIDConnect._process_callback
python
def _process_callback(self, statefield): # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response
Exchange the auth code for actual credentials, then redirect to the originally requested page.
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L692-L744
null
class OpenIDConnect(object): """ The core OpenID Connect client object. """ def __init__(self, app=None, credentials_store=None, http=None, time=None, urandom=None): self.credentials_store = credentials_store\ if credentials_store is not None\ else MemoryCredentials() if http is not None: warn('HTTP argument is deprecated and unused', DeprecationWarning) if time is not None: warn('time argument is deprecated and unused', DeprecationWarning) if urandom is not None: warn('urandom argument is deprecated and unused', DeprecationWarning) # By default, we do not have a custom callback self._custom_callback = None # get stuff from the app's config, which may override stuff set above if app is not None: self.init_app(app) def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass def load_secrets(self, app): # Load client_secrets.json to pre-initialize some configuration content = app.config['OIDC_CLIENT_SECRETS'] if isinstance(content, dict): return content else: return _json_loads(open(content, 'r').read()) @property def user_loggedin(self): """ Represents whether the user is currently logged in. Returns: bool: Whether the user is logged in with Flask-OIDC. .. versionadded:: 1.0 """ return g.oidc_id_token is not None def user_getfield(self, field, access_token=None): """ Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0 """ info = self.user_getinfo([field], access_token) return info.get(field) def user_getinfo(self, fields, access_token=None): """ Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0 """ if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def get_refresh_token(self): """Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info def get_cookie_id_token(self): """ .. deprecated:: 1.0 Use :func:`user_getinfo` instead. """ warn('You are using a deprecated function (get_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._get_cookie_id_token() def _get_cookie_id_token(self): try: id_token_cookie = request.cookies.get(current_app.config[ 'OIDC_ID_TOKEN_COOKIE_NAME']) if not id_token_cookie: # Do not error if we were unable to get the cookie. # The user can debug this themselves. return None return self.cookie_serializer.loads(id_token_cookie) except SignatureExpired: logger.debug("Invalid ID token cookie", exc_info=True) return None except BadSignature: logger.info("Signature invalid for ID token cookie", exc_info=True) return None def set_cookie_id_token(self, id_token): """ .. deprecated:: 1.0 """ warn('You are using a deprecated function (set_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._set_cookie_id_token(id_token) def _set_cookie_id_token(self, id_token): """ Cooperates with @after_request to set a new ID token cookie. """ g.oidc_id_token = id_token g.oidc_id_token_dirty = True def _after_request(self, response): """ Set a new ID token cookie if the ID token has changed. """ # This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response def _before_request(self): g.oidc_id_token = None self.authenticate_or_redirect() def authenticate_or_redirect(self): """ Helper function suitable for @app.before_request and @check. Sets g.oidc_id_token to the ID token if the user has successfully authenticated, else returns a redirect object so they can go try to authenticate. :returns: A redirect object, or None if the user is logged in. :rtype: Redirect .. deprecated:: 1.0 Use :func:`require_login` instead. """ # the auth callback and error pages don't need user to be authenticated if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']): return None # retrieve signed ID token cookie id_token = self._get_cookie_id_token() if id_token is None: return self.redirect_to_auth_server(request.url) # ID token expired # when Google is the IdP, this happens after one hour if time.time() >= id_token['exp']: # get credentials from store try: credentials = OAuth2Credentials.from_json( self.credentials_store[id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return self.redirect_to_auth_server(request.url) # refresh and store credentials try: credentials.refresh(httplib2.Http()) if credentials.id_token: id_token = credentials.id_token else: # It is not guaranteed that we will get a new ID Token on # refresh, so if we do not, let's just update the id token # expiry field and reuse the existing ID Token. if credentials.token_expiry is None: logger.debug('Expired ID token, no new expiry. Falling' ' back to assuming 1 hour') id_token['exp'] = time.time() + 3600 else: id_token['exp'] = calendar.timegm( credentials.token_expiry.timetuple()) self.credentials_store[id_token['sub']] = credentials.to_json() self._set_cookie_id_token(id_token) except AccessTokenRefreshError: # Can't refresh. Wipe credentials and redirect user to IdP # for re-authentication. logger.debug("Expired ID token, can't refresh credentials", exc_info=True) del self.credentials_store[id_token['sub']] return self.redirect_to_auth_server(request.url) # make ID token available to views g.oidc_id_token = id_token return None def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """ @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated # Backwards compatibility check = require_login """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ def require_keycloak_role(self, client, role): """ Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper def flow_for_request(self): """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ warn('You are using a deprecated function (flow_for_request). ' 'Please reconsider using this', DeprecationWarning) return self._flow_for_request() def _flow_for_request(self): """ Build a flow with the correct absolute callback URL for this request. :return: """ flow = copy(self.flow) redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI'] if not redirect_uri: flow.redirect_uri = url_for('_oidc_callback', _external=True) else: flow.redirect_uri = redirect_uri return flow def redirect_to_auth_server(self, destination=None, customstate=None): """ Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead. """ if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url) def _is_id_token_valid(self, id_token): """ Check if `id_token` is a current ID token for this application, was issued by the Apps domain we expected, and that the email address has been verified. @see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation """ if not id_token: return False # step 2: check issuer if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']: logger.error('id_token issued by non-trusted issuer: %s' % id_token['iss']) return False if isinstance(id_token['aud'], list): # step 3 for audience list if self.flow.client_id not in id_token['aud']: logger.error('We are not a valid audience') return False # step 4 if 'azp' not in id_token and len(id_token['aud']) > 1: logger.error('Multiple audiences and not authorized party') return False else: # step 3 for single audience if id_token['aud'] != self.flow.client_id: logger.error('We are not the audience') return False # step 5 if 'azp' in id_token and id_token['azp'] != self.flow.client_id: logger.error('Authorized Party is not us') return False # step 6-8: TLS checked # step 9: check exp if int(time.time()) >= int(id_token['exp']): logger.error('Token has expired') return False # step 10: check iat if id_token['iat'] < (time.time() - current_app.config['OIDC_CLOCK_SKEW']): logger.error('Token issued in the past') return False # (not required if using HTTPS?) step 11: check nonce # step 12-13: not requested acr or auth_time, so not needed to test # additional steps specific to our usage if current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] and \ id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: logger.error('Invalid google apps domain') return False if not id_token.get('email_verified', False) and \ current_app.config['OIDC_REQUIRE_VERIFIED_EMAIL']: logger.error('Email not verified') return False return True WRONG_GOOGLE_APPS_DOMAIN = 'WRONG_GOOGLE_APPS_DOMAIN' def custom_callback(self, view_func): """ Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. """ @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback('custom') if plainreturn: return data else: return view_func(data, *args, **kwargs) self._custom_callback = decorated return decorated def _oidc_callback(self): plainreturn, data = self._process_callback('destination') if plainreturn: return data else: return redirect(data) def _oidc_error(self, message='Not Authorized', code=None): return (message, 401, { 'Content-Type': 'text/plain', }) def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout self._set_cookie_id_token(None) # Below here is for resource servers to validate tokens def validate_token(self, token, scopes_required=None): """ This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1 """ valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid) def _validate_token(self, token, scopes_required=None): """The actual implementation of validate_token.""" if scopes_required is None: scopes_required = [] scopes_required = set(scopes_required) token_info = None valid_token = False has_required_scopes = False if token: try: token_info = self._get_token_info(token) except Exception as ex: token_info = {'active': False} logger.error('ERROR: Unable to get token info') logger.error(str(ex)) valid_token = token_info.get('active', False) if 'aud' in token_info and \ current_app.config['OIDC_RESOURCE_CHECK_AUD']: valid_audience = False aud = token_info['aud'] clid = self.client_secrets['client_id'] if isinstance(aud, list): valid_audience = clid in aud else: valid_audience = clid == aud if not valid_audience: logger.error('Refused token because of invalid ' 'audience') valid_token = False if valid_token: token_scopes = token_info.get('scope', '').split(' ') else: token_scopes = [] has_required_scopes = scopes_required.issubset( set(token_scopes)) if not has_required_scopes: logger.debug('Token missed required scopes') if (valid_token and has_required_scopes): g.oidc_token_info = token_info return True if not valid_token: return 'Token required but invalid' elif not has_required_scopes: return 'Token does not have required scopes' else: return 'Something went wrong checking your token' def accept_token(self, require_token=False, scopes_required=None, render_errors=True): """ Use this to decorate view functions that should accept OAuth2 tokens, this will most likely apply to API functions. Tokens are accepted as part of the query URL (access_token value) or a POST form value (access_token). Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param require_token: Whether a token is required for the current function. If this is True, we will abort the request if there was no token provided. :type require_token: bool :param scopes_required: List of scopes that are required to be granted by the token before being allowed to call the protected function. :type scopes_required: list :param render_errors: Whether or not to eagerly render error objects as JSON API responses. Set to False to pass the error object back unmodified for later rendering. :type render_errors: callback(obj) or None .. versionadded:: 1.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): token = request.headers['Authorization'].split(None,1)[1].strip() if 'access_token' in request.form: token = request.form['access_token'] elif 'access_token' in request.args: token = request.args['access_token'] validity = self.validate_token(token, scopes_required) if (validity is True) or (not require_token): return view_func(*args, **kwargs) else: response_body = {'error': 'invalid_token', 'error_description': validity} if render_errors: response_body = json.dumps(response_body) return response_body, 401, {'WWW-Authenticate': 'Bearer'} return decorated return wrapper def _get_token_info(self, token): # We hardcode to use client_secret_post, because that's what the Google # oauth2client library defaults to request = {'token': token} headers = {'Content-type': 'application/x-www-form-urlencoded'} hint = current_app.config['OIDC_TOKEN_TYPE_HINT'] if hint != 'none': request['token_type_hint'] = hint auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] if (auth_method == 'client_secret_basic'): basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret']) basic_auth_bytes = bytearray(basic_auth_string, 'utf-8') headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8') elif (auth_method == 'bearer'): headers['Authorization'] = 'Bearer %s' % token elif (auth_method == 'client_secret_post'): request['client_id'] = self.client_secrets['client_id'] if self.client_secrets['client_secret'] is not None: request['client_secret'] = self.client_secrets['client_secret'] resp, content = httplib2.Http().request( self.client_secrets['token_introspection_uri'], 'POST', urlencode(request), headers=headers) # TODO: Cache this reply return _json_loads(content)
puiterwijk/flask-oidc
flask_oidc/__init__.py
OpenIDConnect.validate_token
python
def validate_token(self, token, scopes_required=None): valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid)
This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L769-L791
[ "def _validate_token(self, token, scopes_required=None):\n \"\"\"The actual implementation of validate_token.\"\"\"\n if scopes_required is None:\n scopes_required = []\n scopes_required = set(scopes_required)\n\n token_info = None\n valid_token = False\n has_required_scopes = False\n if token:\n try:\n token_info = self._get_token_info(token)\n except Exception as ex:\n token_info = {'active': False}\n logger.error('ERROR: Unable to get token info')\n logger.error(str(ex))\n\n valid_token = token_info.get('active', False)\n\n if 'aud' in token_info and \\\n current_app.config['OIDC_RESOURCE_CHECK_AUD']:\n valid_audience = False\n aud = token_info['aud']\n clid = self.client_secrets['client_id']\n if isinstance(aud, list):\n valid_audience = clid in aud\n else:\n valid_audience = clid == aud\n\n if not valid_audience:\n logger.error('Refused token because of invalid '\n 'audience')\n valid_token = False\n\n if valid_token:\n token_scopes = token_info.get('scope', '').split(' ')\n else:\n token_scopes = []\n has_required_scopes = scopes_required.issubset(\n set(token_scopes))\n\n if not has_required_scopes:\n logger.debug('Token missed required scopes')\n\n if (valid_token and has_required_scopes):\n g.oidc_token_info = token_info\n return True\n\n if not valid_token:\n return 'Token required but invalid'\n elif not has_required_scopes:\n return 'Token does not have required scopes'\n else:\n return 'Something went wrong checking your token'\n" ]
class OpenIDConnect(object): """ The core OpenID Connect client object. """ def __init__(self, app=None, credentials_store=None, http=None, time=None, urandom=None): self.credentials_store = credentials_store\ if credentials_store is not None\ else MemoryCredentials() if http is not None: warn('HTTP argument is deprecated and unused', DeprecationWarning) if time is not None: warn('time argument is deprecated and unused', DeprecationWarning) if urandom is not None: warn('urandom argument is deprecated and unused', DeprecationWarning) # By default, we do not have a custom callback self._custom_callback = None # get stuff from the app's config, which may override stuff set above if app is not None: self.init_app(app) def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass def load_secrets(self, app): # Load client_secrets.json to pre-initialize some configuration content = app.config['OIDC_CLIENT_SECRETS'] if isinstance(content, dict): return content else: return _json_loads(open(content, 'r').read()) @property def user_loggedin(self): """ Represents whether the user is currently logged in. Returns: bool: Whether the user is logged in with Flask-OIDC. .. versionadded:: 1.0 """ return g.oidc_id_token is not None def user_getfield(self, field, access_token=None): """ Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0 """ info = self.user_getinfo([field], access_token) return info.get(field) def user_getinfo(self, fields, access_token=None): """ Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0 """ if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def get_refresh_token(self): """Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info def get_cookie_id_token(self): """ .. deprecated:: 1.0 Use :func:`user_getinfo` instead. """ warn('You are using a deprecated function (get_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._get_cookie_id_token() def _get_cookie_id_token(self): try: id_token_cookie = request.cookies.get(current_app.config[ 'OIDC_ID_TOKEN_COOKIE_NAME']) if not id_token_cookie: # Do not error if we were unable to get the cookie. # The user can debug this themselves. return None return self.cookie_serializer.loads(id_token_cookie) except SignatureExpired: logger.debug("Invalid ID token cookie", exc_info=True) return None except BadSignature: logger.info("Signature invalid for ID token cookie", exc_info=True) return None def set_cookie_id_token(self, id_token): """ .. deprecated:: 1.0 """ warn('You are using a deprecated function (set_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._set_cookie_id_token(id_token) def _set_cookie_id_token(self, id_token): """ Cooperates with @after_request to set a new ID token cookie. """ g.oidc_id_token = id_token g.oidc_id_token_dirty = True def _after_request(self, response): """ Set a new ID token cookie if the ID token has changed. """ # This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response def _before_request(self): g.oidc_id_token = None self.authenticate_or_redirect() def authenticate_or_redirect(self): """ Helper function suitable for @app.before_request and @check. Sets g.oidc_id_token to the ID token if the user has successfully authenticated, else returns a redirect object so they can go try to authenticate. :returns: A redirect object, or None if the user is logged in. :rtype: Redirect .. deprecated:: 1.0 Use :func:`require_login` instead. """ # the auth callback and error pages don't need user to be authenticated if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']): return None # retrieve signed ID token cookie id_token = self._get_cookie_id_token() if id_token is None: return self.redirect_to_auth_server(request.url) # ID token expired # when Google is the IdP, this happens after one hour if time.time() >= id_token['exp']: # get credentials from store try: credentials = OAuth2Credentials.from_json( self.credentials_store[id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return self.redirect_to_auth_server(request.url) # refresh and store credentials try: credentials.refresh(httplib2.Http()) if credentials.id_token: id_token = credentials.id_token else: # It is not guaranteed that we will get a new ID Token on # refresh, so if we do not, let's just update the id token # expiry field and reuse the existing ID Token. if credentials.token_expiry is None: logger.debug('Expired ID token, no new expiry. Falling' ' back to assuming 1 hour') id_token['exp'] = time.time() + 3600 else: id_token['exp'] = calendar.timegm( credentials.token_expiry.timetuple()) self.credentials_store[id_token['sub']] = credentials.to_json() self._set_cookie_id_token(id_token) except AccessTokenRefreshError: # Can't refresh. Wipe credentials and redirect user to IdP # for re-authentication. logger.debug("Expired ID token, can't refresh credentials", exc_info=True) del self.credentials_store[id_token['sub']] return self.redirect_to_auth_server(request.url) # make ID token available to views g.oidc_id_token = id_token return None def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """ @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated # Backwards compatibility check = require_login """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ def require_keycloak_role(self, client, role): """ Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper def flow_for_request(self): """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ warn('You are using a deprecated function (flow_for_request). ' 'Please reconsider using this', DeprecationWarning) return self._flow_for_request() def _flow_for_request(self): """ Build a flow with the correct absolute callback URL for this request. :return: """ flow = copy(self.flow) redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI'] if not redirect_uri: flow.redirect_uri = url_for('_oidc_callback', _external=True) else: flow.redirect_uri = redirect_uri return flow def redirect_to_auth_server(self, destination=None, customstate=None): """ Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead. """ if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url) def _is_id_token_valid(self, id_token): """ Check if `id_token` is a current ID token for this application, was issued by the Apps domain we expected, and that the email address has been verified. @see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation """ if not id_token: return False # step 2: check issuer if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']: logger.error('id_token issued by non-trusted issuer: %s' % id_token['iss']) return False if isinstance(id_token['aud'], list): # step 3 for audience list if self.flow.client_id not in id_token['aud']: logger.error('We are not a valid audience') return False # step 4 if 'azp' not in id_token and len(id_token['aud']) > 1: logger.error('Multiple audiences and not authorized party') return False else: # step 3 for single audience if id_token['aud'] != self.flow.client_id: logger.error('We are not the audience') return False # step 5 if 'azp' in id_token and id_token['azp'] != self.flow.client_id: logger.error('Authorized Party is not us') return False # step 6-8: TLS checked # step 9: check exp if int(time.time()) >= int(id_token['exp']): logger.error('Token has expired') return False # step 10: check iat if id_token['iat'] < (time.time() - current_app.config['OIDC_CLOCK_SKEW']): logger.error('Token issued in the past') return False # (not required if using HTTPS?) step 11: check nonce # step 12-13: not requested acr or auth_time, so not needed to test # additional steps specific to our usage if current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] and \ id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: logger.error('Invalid google apps domain') return False if not id_token.get('email_verified', False) and \ current_app.config['OIDC_REQUIRE_VERIFIED_EMAIL']: logger.error('Email not verified') return False return True WRONG_GOOGLE_APPS_DOMAIN = 'WRONG_GOOGLE_APPS_DOMAIN' def custom_callback(self, view_func): """ Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. """ @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback('custom') if plainreturn: return data else: return view_func(data, *args, **kwargs) self._custom_callback = decorated return decorated def _oidc_callback(self): plainreturn, data = self._process_callback('destination') if plainreturn: return data else: return redirect(data) def _process_callback(self, statefield): """ Exchange the auth code for actual credentials, then redirect to the originally requested page. """ # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response def _oidc_error(self, message='Not Authorized', code=None): return (message, 401, { 'Content-Type': 'text/plain', }) def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout self._set_cookie_id_token(None) # Below here is for resource servers to validate tokens def _validate_token(self, token, scopes_required=None): """The actual implementation of validate_token.""" if scopes_required is None: scopes_required = [] scopes_required = set(scopes_required) token_info = None valid_token = False has_required_scopes = False if token: try: token_info = self._get_token_info(token) except Exception as ex: token_info = {'active': False} logger.error('ERROR: Unable to get token info') logger.error(str(ex)) valid_token = token_info.get('active', False) if 'aud' in token_info and \ current_app.config['OIDC_RESOURCE_CHECK_AUD']: valid_audience = False aud = token_info['aud'] clid = self.client_secrets['client_id'] if isinstance(aud, list): valid_audience = clid in aud else: valid_audience = clid == aud if not valid_audience: logger.error('Refused token because of invalid ' 'audience') valid_token = False if valid_token: token_scopes = token_info.get('scope', '').split(' ') else: token_scopes = [] has_required_scopes = scopes_required.issubset( set(token_scopes)) if not has_required_scopes: logger.debug('Token missed required scopes') if (valid_token and has_required_scopes): g.oidc_token_info = token_info return True if not valid_token: return 'Token required but invalid' elif not has_required_scopes: return 'Token does not have required scopes' else: return 'Something went wrong checking your token' def accept_token(self, require_token=False, scopes_required=None, render_errors=True): """ Use this to decorate view functions that should accept OAuth2 tokens, this will most likely apply to API functions. Tokens are accepted as part of the query URL (access_token value) or a POST form value (access_token). Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param require_token: Whether a token is required for the current function. If this is True, we will abort the request if there was no token provided. :type require_token: bool :param scopes_required: List of scopes that are required to be granted by the token before being allowed to call the protected function. :type scopes_required: list :param render_errors: Whether or not to eagerly render error objects as JSON API responses. Set to False to pass the error object back unmodified for later rendering. :type render_errors: callback(obj) or None .. versionadded:: 1.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): token = request.headers['Authorization'].split(None,1)[1].strip() if 'access_token' in request.form: token = request.form['access_token'] elif 'access_token' in request.args: token = request.args['access_token'] validity = self.validate_token(token, scopes_required) if (validity is True) or (not require_token): return view_func(*args, **kwargs) else: response_body = {'error': 'invalid_token', 'error_description': validity} if render_errors: response_body = json.dumps(response_body) return response_body, 401, {'WWW-Authenticate': 'Bearer'} return decorated return wrapper def _get_token_info(self, token): # We hardcode to use client_secret_post, because that's what the Google # oauth2client library defaults to request = {'token': token} headers = {'Content-type': 'application/x-www-form-urlencoded'} hint = current_app.config['OIDC_TOKEN_TYPE_HINT'] if hint != 'none': request['token_type_hint'] = hint auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] if (auth_method == 'client_secret_basic'): basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret']) basic_auth_bytes = bytearray(basic_auth_string, 'utf-8') headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8') elif (auth_method == 'bearer'): headers['Authorization'] = 'Bearer %s' % token elif (auth_method == 'client_secret_post'): request['client_id'] = self.client_secrets['client_id'] if self.client_secrets['client_secret'] is not None: request['client_secret'] = self.client_secrets['client_secret'] resp, content = httplib2.Http().request( self.client_secrets['token_introspection_uri'], 'POST', urlencode(request), headers=headers) # TODO: Cache this reply return _json_loads(content)
puiterwijk/flask-oidc
flask_oidc/__init__.py
OpenIDConnect._validate_token
python
def _validate_token(self, token, scopes_required=None): if scopes_required is None: scopes_required = [] scopes_required = set(scopes_required) token_info = None valid_token = False has_required_scopes = False if token: try: token_info = self._get_token_info(token) except Exception as ex: token_info = {'active': False} logger.error('ERROR: Unable to get token info') logger.error(str(ex)) valid_token = token_info.get('active', False) if 'aud' in token_info and \ current_app.config['OIDC_RESOURCE_CHECK_AUD']: valid_audience = False aud = token_info['aud'] clid = self.client_secrets['client_id'] if isinstance(aud, list): valid_audience = clid in aud else: valid_audience = clid == aud if not valid_audience: logger.error('Refused token because of invalid ' 'audience') valid_token = False if valid_token: token_scopes = token_info.get('scope', '').split(' ') else: token_scopes = [] has_required_scopes = scopes_required.issubset( set(token_scopes)) if not has_required_scopes: logger.debug('Token missed required scopes') if (valid_token and has_required_scopes): g.oidc_token_info = token_info return True if not valid_token: return 'Token required but invalid' elif not has_required_scopes: return 'Token does not have required scopes' else: return 'Something went wrong checking your token'
The actual implementation of validate_token.
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L793-L846
[ "def _get_token_info(self, token):\n # We hardcode to use client_secret_post, because that's what the Google\n # oauth2client library defaults to\n request = {'token': token}\n headers = {'Content-type': 'application/x-www-form-urlencoded'}\n\n hint = current_app.config['OIDC_TOKEN_TYPE_HINT']\n if hint != 'none':\n request['token_type_hint'] = hint\n\n auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] \n if (auth_method == 'client_secret_basic'):\n basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret'])\n basic_auth_bytes = bytearray(basic_auth_string, 'utf-8')\n headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8')\n elif (auth_method == 'bearer'):\n headers['Authorization'] = 'Bearer %s' % token\n elif (auth_method == 'client_secret_post'):\n request['client_id'] = self.client_secrets['client_id']\n if self.client_secrets['client_secret'] is not None:\n request['client_secret'] = self.client_secrets['client_secret']\n\n resp, content = httplib2.Http().request(\n self.client_secrets['token_introspection_uri'], 'POST',\n urlencode(request), headers=headers)\n # TODO: Cache this reply\n return _json_loads(content)\n" ]
class OpenIDConnect(object): """ The core OpenID Connect client object. """ def __init__(self, app=None, credentials_store=None, http=None, time=None, urandom=None): self.credentials_store = credentials_store\ if credentials_store is not None\ else MemoryCredentials() if http is not None: warn('HTTP argument is deprecated and unused', DeprecationWarning) if time is not None: warn('time argument is deprecated and unused', DeprecationWarning) if urandom is not None: warn('urandom argument is deprecated and unused', DeprecationWarning) # By default, we do not have a custom callback self._custom_callback = None # get stuff from the app's config, which may override stuff set above if app is not None: self.init_app(app) def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass def load_secrets(self, app): # Load client_secrets.json to pre-initialize some configuration content = app.config['OIDC_CLIENT_SECRETS'] if isinstance(content, dict): return content else: return _json_loads(open(content, 'r').read()) @property def user_loggedin(self): """ Represents whether the user is currently logged in. Returns: bool: Whether the user is logged in with Flask-OIDC. .. versionadded:: 1.0 """ return g.oidc_id_token is not None def user_getfield(self, field, access_token=None): """ Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0 """ info = self.user_getinfo([field], access_token) return info.get(field) def user_getinfo(self, fields, access_token=None): """ Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0 """ if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def get_refresh_token(self): """Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info def get_cookie_id_token(self): """ .. deprecated:: 1.0 Use :func:`user_getinfo` instead. """ warn('You are using a deprecated function (get_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._get_cookie_id_token() def _get_cookie_id_token(self): try: id_token_cookie = request.cookies.get(current_app.config[ 'OIDC_ID_TOKEN_COOKIE_NAME']) if not id_token_cookie: # Do not error if we were unable to get the cookie. # The user can debug this themselves. return None return self.cookie_serializer.loads(id_token_cookie) except SignatureExpired: logger.debug("Invalid ID token cookie", exc_info=True) return None except BadSignature: logger.info("Signature invalid for ID token cookie", exc_info=True) return None def set_cookie_id_token(self, id_token): """ .. deprecated:: 1.0 """ warn('You are using a deprecated function (set_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._set_cookie_id_token(id_token) def _set_cookie_id_token(self, id_token): """ Cooperates with @after_request to set a new ID token cookie. """ g.oidc_id_token = id_token g.oidc_id_token_dirty = True def _after_request(self, response): """ Set a new ID token cookie if the ID token has changed. """ # This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response def _before_request(self): g.oidc_id_token = None self.authenticate_or_redirect() def authenticate_or_redirect(self): """ Helper function suitable for @app.before_request and @check. Sets g.oidc_id_token to the ID token if the user has successfully authenticated, else returns a redirect object so they can go try to authenticate. :returns: A redirect object, or None if the user is logged in. :rtype: Redirect .. deprecated:: 1.0 Use :func:`require_login` instead. """ # the auth callback and error pages don't need user to be authenticated if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']): return None # retrieve signed ID token cookie id_token = self._get_cookie_id_token() if id_token is None: return self.redirect_to_auth_server(request.url) # ID token expired # when Google is the IdP, this happens after one hour if time.time() >= id_token['exp']: # get credentials from store try: credentials = OAuth2Credentials.from_json( self.credentials_store[id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return self.redirect_to_auth_server(request.url) # refresh and store credentials try: credentials.refresh(httplib2.Http()) if credentials.id_token: id_token = credentials.id_token else: # It is not guaranteed that we will get a new ID Token on # refresh, so if we do not, let's just update the id token # expiry field and reuse the existing ID Token. if credentials.token_expiry is None: logger.debug('Expired ID token, no new expiry. Falling' ' back to assuming 1 hour') id_token['exp'] = time.time() + 3600 else: id_token['exp'] = calendar.timegm( credentials.token_expiry.timetuple()) self.credentials_store[id_token['sub']] = credentials.to_json() self._set_cookie_id_token(id_token) except AccessTokenRefreshError: # Can't refresh. Wipe credentials and redirect user to IdP # for re-authentication. logger.debug("Expired ID token, can't refresh credentials", exc_info=True) del self.credentials_store[id_token['sub']] return self.redirect_to_auth_server(request.url) # make ID token available to views g.oidc_id_token = id_token return None def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """ @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated # Backwards compatibility check = require_login """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ def require_keycloak_role(self, client, role): """ Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper def flow_for_request(self): """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ warn('You are using a deprecated function (flow_for_request). ' 'Please reconsider using this', DeprecationWarning) return self._flow_for_request() def _flow_for_request(self): """ Build a flow with the correct absolute callback URL for this request. :return: """ flow = copy(self.flow) redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI'] if not redirect_uri: flow.redirect_uri = url_for('_oidc_callback', _external=True) else: flow.redirect_uri = redirect_uri return flow def redirect_to_auth_server(self, destination=None, customstate=None): """ Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead. """ if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url) def _is_id_token_valid(self, id_token): """ Check if `id_token` is a current ID token for this application, was issued by the Apps domain we expected, and that the email address has been verified. @see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation """ if not id_token: return False # step 2: check issuer if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']: logger.error('id_token issued by non-trusted issuer: %s' % id_token['iss']) return False if isinstance(id_token['aud'], list): # step 3 for audience list if self.flow.client_id not in id_token['aud']: logger.error('We are not a valid audience') return False # step 4 if 'azp' not in id_token and len(id_token['aud']) > 1: logger.error('Multiple audiences and not authorized party') return False else: # step 3 for single audience if id_token['aud'] != self.flow.client_id: logger.error('We are not the audience') return False # step 5 if 'azp' in id_token and id_token['azp'] != self.flow.client_id: logger.error('Authorized Party is not us') return False # step 6-8: TLS checked # step 9: check exp if int(time.time()) >= int(id_token['exp']): logger.error('Token has expired') return False # step 10: check iat if id_token['iat'] < (time.time() - current_app.config['OIDC_CLOCK_SKEW']): logger.error('Token issued in the past') return False # (not required if using HTTPS?) step 11: check nonce # step 12-13: not requested acr or auth_time, so not needed to test # additional steps specific to our usage if current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] and \ id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: logger.error('Invalid google apps domain') return False if not id_token.get('email_verified', False) and \ current_app.config['OIDC_REQUIRE_VERIFIED_EMAIL']: logger.error('Email not verified') return False return True WRONG_GOOGLE_APPS_DOMAIN = 'WRONG_GOOGLE_APPS_DOMAIN' def custom_callback(self, view_func): """ Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. """ @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback('custom') if plainreturn: return data else: return view_func(data, *args, **kwargs) self._custom_callback = decorated return decorated def _oidc_callback(self): plainreturn, data = self._process_callback('destination') if plainreturn: return data else: return redirect(data) def _process_callback(self, statefield): """ Exchange the auth code for actual credentials, then redirect to the originally requested page. """ # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response def _oidc_error(self, message='Not Authorized', code=None): return (message, 401, { 'Content-Type': 'text/plain', }) def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout self._set_cookie_id_token(None) # Below here is for resource servers to validate tokens def validate_token(self, token, scopes_required=None): """ This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1 """ valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid) def accept_token(self, require_token=False, scopes_required=None, render_errors=True): """ Use this to decorate view functions that should accept OAuth2 tokens, this will most likely apply to API functions. Tokens are accepted as part of the query URL (access_token value) or a POST form value (access_token). Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param require_token: Whether a token is required for the current function. If this is True, we will abort the request if there was no token provided. :type require_token: bool :param scopes_required: List of scopes that are required to be granted by the token before being allowed to call the protected function. :type scopes_required: list :param render_errors: Whether or not to eagerly render error objects as JSON API responses. Set to False to pass the error object back unmodified for later rendering. :type render_errors: callback(obj) or None .. versionadded:: 1.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): token = request.headers['Authorization'].split(None,1)[1].strip() if 'access_token' in request.form: token = request.form['access_token'] elif 'access_token' in request.args: token = request.args['access_token'] validity = self.validate_token(token, scopes_required) if (validity is True) or (not require_token): return view_func(*args, **kwargs) else: response_body = {'error': 'invalid_token', 'error_description': validity} if render_errors: response_body = json.dumps(response_body) return response_body, 401, {'WWW-Authenticate': 'Bearer'} return decorated return wrapper def _get_token_info(self, token): # We hardcode to use client_secret_post, because that's what the Google # oauth2client library defaults to request = {'token': token} headers = {'Content-type': 'application/x-www-form-urlencoded'} hint = current_app.config['OIDC_TOKEN_TYPE_HINT'] if hint != 'none': request['token_type_hint'] = hint auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] if (auth_method == 'client_secret_basic'): basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret']) basic_auth_bytes = bytearray(basic_auth_string, 'utf-8') headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8') elif (auth_method == 'bearer'): headers['Authorization'] = 'Bearer %s' % token elif (auth_method == 'client_secret_post'): request['client_id'] = self.client_secrets['client_id'] if self.client_secrets['client_secret'] is not None: request['client_secret'] = self.client_secrets['client_secret'] resp, content = httplib2.Http().request( self.client_secrets['token_introspection_uri'], 'POST', urlencode(request), headers=headers) # TODO: Cache this reply return _json_loads(content)
puiterwijk/flask-oidc
flask_oidc/__init__.py
OpenIDConnect.accept_token
python
def accept_token(self, require_token=False, scopes_required=None, render_errors=True): def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): token = request.headers['Authorization'].split(None,1)[1].strip() if 'access_token' in request.form: token = request.form['access_token'] elif 'access_token' in request.args: token = request.args['access_token'] validity = self.validate_token(token, scopes_required) if (validity is True) or (not require_token): return view_func(*args, **kwargs) else: response_body = {'error': 'invalid_token', 'error_description': validity} if render_errors: response_body = json.dumps(response_body) return response_body, 401, {'WWW-Authenticate': 'Bearer'} return decorated return wrapper
Use this to decorate view functions that should accept OAuth2 tokens, this will most likely apply to API functions. Tokens are accepted as part of the query URL (access_token value) or a POST form value (access_token). Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param require_token: Whether a token is required for the current function. If this is True, we will abort the request if there was no token provided. :type require_token: bool :param scopes_required: List of scopes that are required to be granted by the token before being allowed to call the protected function. :type scopes_required: list :param render_errors: Whether or not to eagerly render error objects as JSON API responses. Set to False to pass the error object back unmodified for later rendering. :type render_errors: callback(obj) or None .. versionadded:: 1.0
train
https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L848-L898
null
class OpenIDConnect(object): """ The core OpenID Connect client object. """ def __init__(self, app=None, credentials_store=None, http=None, time=None, urandom=None): self.credentials_store = credentials_store\ if credentials_store is not None\ else MemoryCredentials() if http is not None: warn('HTTP argument is deprecated and unused', DeprecationWarning) if time is not None: warn('time argument is deprecated and unused', DeprecationWarning) if urandom is not None: warn('urandom argument is deprecated and unused', DeprecationWarning) # By default, we do not have a custom callback self._custom_callback = None # get stuff from the app's config, which may override stuff set above if app is not None: self.init_app(app) def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass def load_secrets(self, app): # Load client_secrets.json to pre-initialize some configuration content = app.config['OIDC_CLIENT_SECRETS'] if isinstance(content, dict): return content else: return _json_loads(open(content, 'r').read()) @property def user_loggedin(self): """ Represents whether the user is currently logged in. Returns: bool: Whether the user is logged in with Flask-OIDC. .. versionadded:: 1.0 """ return g.oidc_id_token is not None def user_getfield(self, field, access_token=None): """ Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0 """ info = self.user_getinfo([field], access_token) return info.get(field) def user_getinfo(self, fields, access_token=None): """ Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0 """ if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def get_refresh_token(self): """Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info def get_cookie_id_token(self): """ .. deprecated:: 1.0 Use :func:`user_getinfo` instead. """ warn('You are using a deprecated function (get_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._get_cookie_id_token() def _get_cookie_id_token(self): try: id_token_cookie = request.cookies.get(current_app.config[ 'OIDC_ID_TOKEN_COOKIE_NAME']) if not id_token_cookie: # Do not error if we were unable to get the cookie. # The user can debug this themselves. return None return self.cookie_serializer.loads(id_token_cookie) except SignatureExpired: logger.debug("Invalid ID token cookie", exc_info=True) return None except BadSignature: logger.info("Signature invalid for ID token cookie", exc_info=True) return None def set_cookie_id_token(self, id_token): """ .. deprecated:: 1.0 """ warn('You are using a deprecated function (set_cookie_id_token). ' 'Please reconsider using this', DeprecationWarning) return self._set_cookie_id_token(id_token) def _set_cookie_id_token(self, id_token): """ Cooperates with @after_request to set a new ID token cookie. """ g.oidc_id_token = id_token g.oidc_id_token_dirty = True def _after_request(self, response): """ Set a new ID token cookie if the ID token has changed. """ # This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response def _before_request(self): g.oidc_id_token = None self.authenticate_or_redirect() def authenticate_or_redirect(self): """ Helper function suitable for @app.before_request and @check. Sets g.oidc_id_token to the ID token if the user has successfully authenticated, else returns a redirect object so they can go try to authenticate. :returns: A redirect object, or None if the user is logged in. :rtype: Redirect .. deprecated:: 1.0 Use :func:`require_login` instead. """ # the auth callback and error pages don't need user to be authenticated if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']): return None # retrieve signed ID token cookie id_token = self._get_cookie_id_token() if id_token is None: return self.redirect_to_auth_server(request.url) # ID token expired # when Google is the IdP, this happens after one hour if time.time() >= id_token['exp']: # get credentials from store try: credentials = OAuth2Credentials.from_json( self.credentials_store[id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return self.redirect_to_auth_server(request.url) # refresh and store credentials try: credentials.refresh(httplib2.Http()) if credentials.id_token: id_token = credentials.id_token else: # It is not guaranteed that we will get a new ID Token on # refresh, so if we do not, let's just update the id token # expiry field and reuse the existing ID Token. if credentials.token_expiry is None: logger.debug('Expired ID token, no new expiry. Falling' ' back to assuming 1 hour') id_token['exp'] = time.time() + 3600 else: id_token['exp'] = calendar.timegm( credentials.token_expiry.timetuple()) self.credentials_store[id_token['sub']] = credentials.to_json() self._set_cookie_id_token(id_token) except AccessTokenRefreshError: # Can't refresh. Wipe credentials and redirect user to IdP # for re-authentication. logger.debug("Expired ID token, can't refresh credentials", exc_info=True) del self.credentials_store[id_token['sub']] return self.redirect_to_auth_server(request.url) # make ID token available to views g.oidc_id_token = id_token return None def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """ @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated # Backwards compatibility check = require_login """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ def require_keycloak_role(self, client, role): """ Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0 """ def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper def flow_for_request(self): """ .. deprecated:: 1.0 Use :func:`require_login` instead. """ warn('You are using a deprecated function (flow_for_request). ' 'Please reconsider using this', DeprecationWarning) return self._flow_for_request() def _flow_for_request(self): """ Build a flow with the correct absolute callback URL for this request. :return: """ flow = copy(self.flow) redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI'] if not redirect_uri: flow.redirect_uri = url_for('_oidc_callback', _external=True) else: flow.redirect_uri = redirect_uri return flow def redirect_to_auth_server(self, destination=None, customstate=None): """ Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead. """ if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url) def _is_id_token_valid(self, id_token): """ Check if `id_token` is a current ID token for this application, was issued by the Apps domain we expected, and that the email address has been verified. @see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation """ if not id_token: return False # step 2: check issuer if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']: logger.error('id_token issued by non-trusted issuer: %s' % id_token['iss']) return False if isinstance(id_token['aud'], list): # step 3 for audience list if self.flow.client_id not in id_token['aud']: logger.error('We are not a valid audience') return False # step 4 if 'azp' not in id_token and len(id_token['aud']) > 1: logger.error('Multiple audiences and not authorized party') return False else: # step 3 for single audience if id_token['aud'] != self.flow.client_id: logger.error('We are not the audience') return False # step 5 if 'azp' in id_token and id_token['azp'] != self.flow.client_id: logger.error('Authorized Party is not us') return False # step 6-8: TLS checked # step 9: check exp if int(time.time()) >= int(id_token['exp']): logger.error('Token has expired') return False # step 10: check iat if id_token['iat'] < (time.time() - current_app.config['OIDC_CLOCK_SKEW']): logger.error('Token issued in the past') return False # (not required if using HTTPS?) step 11: check nonce # step 12-13: not requested acr or auth_time, so not needed to test # additional steps specific to our usage if current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] and \ id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: logger.error('Invalid google apps domain') return False if not id_token.get('email_verified', False) and \ current_app.config['OIDC_REQUIRE_VERIFIED_EMAIL']: logger.error('Email not verified') return False return True WRONG_GOOGLE_APPS_DOMAIN = 'WRONG_GOOGLE_APPS_DOMAIN' def custom_callback(self, view_func): """ Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. """ @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback('custom') if plainreturn: return data else: return view_func(data, *args, **kwargs) self._custom_callback = decorated return decorated def _oidc_callback(self): plainreturn, data = self._process_callback('destination') if plainreturn: return data else: return redirect(data) def _process_callback(self, statefield): """ Exchange the auth code for actual credentials, then redirect to the originally requested page. """ # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response def _oidc_error(self, message='Not Authorized', code=None): return (message, 401, { 'Content-Type': 'text/plain', }) def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout self._set_cookie_id_token(None) # Below here is for resource servers to validate tokens def validate_token(self, token, scopes_required=None): """ This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1 """ valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid) def _validate_token(self, token, scopes_required=None): """The actual implementation of validate_token.""" if scopes_required is None: scopes_required = [] scopes_required = set(scopes_required) token_info = None valid_token = False has_required_scopes = False if token: try: token_info = self._get_token_info(token) except Exception as ex: token_info = {'active': False} logger.error('ERROR: Unable to get token info') logger.error(str(ex)) valid_token = token_info.get('active', False) if 'aud' in token_info and \ current_app.config['OIDC_RESOURCE_CHECK_AUD']: valid_audience = False aud = token_info['aud'] clid = self.client_secrets['client_id'] if isinstance(aud, list): valid_audience = clid in aud else: valid_audience = clid == aud if not valid_audience: logger.error('Refused token because of invalid ' 'audience') valid_token = False if valid_token: token_scopes = token_info.get('scope', '').split(' ') else: token_scopes = [] has_required_scopes = scopes_required.issubset( set(token_scopes)) if not has_required_scopes: logger.debug('Token missed required scopes') if (valid_token and has_required_scopes): g.oidc_token_info = token_info return True if not valid_token: return 'Token required but invalid' elif not has_required_scopes: return 'Token does not have required scopes' else: return 'Something went wrong checking your token' def _get_token_info(self, token): # We hardcode to use client_secret_post, because that's what the Google # oauth2client library defaults to request = {'token': token} headers = {'Content-type': 'application/x-www-form-urlencoded'} hint = current_app.config['OIDC_TOKEN_TYPE_HINT'] if hint != 'none': request['token_type_hint'] = hint auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] if (auth_method == 'client_secret_basic'): basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret']) basic_auth_bytes = bytearray(basic_auth_string, 'utf-8') headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8') elif (auth_method == 'bearer'): headers['Authorization'] = 'Bearer %s' % token elif (auth_method == 'client_secret_post'): request['client_id'] = self.client_secrets['client_id'] if self.client_secrets['client_secret'] is not None: request['client_secret'] = self.client_secrets['client_secret'] resp, content = httplib2.Http().request( self.client_secrets['token_introspection_uri'], 'POST', urlencode(request), headers=headers) # TODO: Cache this reply return _json_loads(content)
MahjongRepository/mahjong
mahjong/hand_calculating/scores.py
ScoresCalculator.calculate_scores
python
def calculate_scores(self, han, fu, config, is_yakuman=False): # kazoe hand if han >= 13 and not is_yakuman: # Hands over 26+ han don't count as double yakuman if config.options.kazoe_limit == HandConfig.KAZOE_LIMITED: han = 13 # Hands over 13+ is a sanbaiman elif config.options.kazoe_limit == HandConfig.KAZOE_SANBAIMAN: han = 12 if han >= 5: if han >= 78: rounded = 48000 elif han >= 65: rounded = 40000 elif han >= 52: rounded = 32000 elif han >= 39: rounded = 24000 # double yakuman elif han >= 26: rounded = 16000 # yakuman elif han >= 13: rounded = 8000 # sanbaiman elif han >= 11: rounded = 6000 # baiman elif han >= 8: rounded = 4000 # haneman elif han >= 6: rounded = 3000 else: rounded = 2000 double_rounded = rounded * 2 four_rounded = double_rounded * 2 six_rounded = double_rounded * 3 else: base_points = fu * pow(2, 2 + han) rounded = (base_points + 99) // 100 * 100 double_rounded = (2 * base_points + 99) // 100 * 100 four_rounded = (4 * base_points + 99) // 100 * 100 six_rounded = (6 * base_points + 99) // 100 * 100 is_kiriage = False if config.options.kiriage: if han == 4 and fu == 30: is_kiriage = True if han == 3 and fu == 60: is_kiriage = True # mangan if rounded > 2000 or is_kiriage: rounded = 2000 double_rounded = rounded * 2 four_rounded = double_rounded * 2 six_rounded = double_rounded * 3 if config.is_tsumo: return {'main': double_rounded, 'additional': config.is_dealer and double_rounded or rounded} else: return {'main': config.is_dealer and six_rounded or four_rounded, 'additional': 0}
Calculate how much scores cost a hand with given han and fu :param han: int :param fu: int :param config: HandConfig object :param is_yakuman: boolean :return: a dictionary with main and additional cost for ron additional cost is always = 0 for tsumo main cost is cost for dealer and additional is cost for player {'main': 1000, 'additional': 0}
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/hand_calculating/scores.py#L7-L83
null
class ScoresCalculator(object):
MahjongRepository/mahjong
mahjong/hand_calculating/fu.py
FuCalculator.calculate_fu
python
def calculate_fu(self, hand, win_tile, win_group, config, valued_tiles=None, melds=None,): win_tile_34 = win_tile // 4 if not valued_tiles: valued_tiles = [] if not melds: melds = [] fu_details = [] if len(hand) == 7: return [{'fu': 25, 'reason': FuCalculator.BASE}], 25 pair = [x for x in hand if is_pair(x)][0] pon_sets = [x for x in hand if is_pon(x)] copied_opened_melds = [x.tiles_34 for x in melds if x.type == Meld.CHI] closed_chi_sets = [] for x in hand: if x not in copied_opened_melds: closed_chi_sets.append(x) else: copied_opened_melds.remove(x) is_open_hand = any([x.opened for x in melds]) if win_group in closed_chi_sets: tile_index = simplify(win_tile_34) # penchan if contains_terminals(win_group): # 1-2-... wait if tile_index == 2 and win_group.index(win_tile_34) == 2: fu_details.append({'fu': 2, 'reason': FuCalculator.PENCHAN}) # 8-9-... wait elif tile_index == 6 and win_group.index(win_tile_34) == 0: fu_details.append({'fu': 2, 'reason': FuCalculator.PENCHAN}) # kanchan waiting 5-...-7 if win_group.index(win_tile_34) == 1: fu_details.append({'fu': 2, 'reason': FuCalculator.KANCHAN}) # valued pair count_of_valued_pairs = valued_tiles.count(pair[0]) if count_of_valued_pairs == 1: fu_details.append({'fu': 2, 'reason': FuCalculator.VALUED_PAIR}) # east-east pair when you are on east gave double fu if count_of_valued_pairs == 2: fu_details.append({'fu': 2, 'reason': FuCalculator.VALUED_PAIR}) fu_details.append({'fu': 2, 'reason': FuCalculator.VALUED_PAIR}) # pair wait if is_pair(win_group): fu_details.append({'fu': 2, 'reason': FuCalculator.PAIR_WAIT}) for set_item in pon_sets: open_meld = [x for x in melds if set_item == x.tiles_34] open_meld = open_meld and open_meld[0] or None set_was_open = open_meld and open_meld.opened or False is_kan = (open_meld and (open_meld.type == Meld.KAN or open_meld.type == Meld.CHANKAN)) or False is_honor = set_item[0] in TERMINAL_INDICES + HONOR_INDICES # we win by ron on the third pon tile, our pon will be count as open if not config.is_tsumo and set_item == win_group: set_was_open = True if is_honor: if is_kan: if set_was_open: fu_details.append({'fu': 16, 'reason': FuCalculator.OPEN_TERMINAL_KAN}) else: fu_details.append({'fu': 32, 'reason': FuCalculator.CLOSED_TERMINAL_KAN}) else: if set_was_open: fu_details.append({'fu': 4, 'reason': FuCalculator.OPEN_TERMINAL_PON}) else: fu_details.append({'fu': 8, 'reason': FuCalculator.CLOSED_TERMINAL_PON}) else: if is_kan: if set_was_open: fu_details.append({'fu': 8, 'reason': FuCalculator.OPEN_KAN}) else: fu_details.append({'fu': 16, 'reason': FuCalculator.CLOSED_KAN}) else: if set_was_open: fu_details.append({'fu': 2, 'reason': FuCalculator.OPEN_PON}) else: fu_details.append({'fu': 4, 'reason': FuCalculator.CLOSED_PON}) add_tsumo_fu = len(fu_details) > 0 or config.options.fu_for_pinfu_tsumo if config.is_tsumo and add_tsumo_fu: # 2 additional fu for tsumo (but not for pinfu) fu_details.append({'fu': 2, 'reason': FuCalculator.TSUMO}) if is_open_hand and not len(fu_details) and config.options.fu_for_open_pinfu: # there is no 1-20 hands, so we had to add additional fu fu_details.append({'fu': 2, 'reason': FuCalculator.HAND_WITHOUT_FU}) if is_open_hand or config.is_tsumo: fu_details.append({'fu': 20, 'reason': FuCalculator.BASE}) else: fu_details.append({'fu': 30, 'reason': FuCalculator.BASE}) return fu_details, self.round_fu(fu_details)
Calculate hand fu with explanations :param hand: :param win_tile: 136 tile format :param win_group: one set where win tile exists :param is_tsumo: :param config: HandConfig object :param valued_tiles: dragons, player wind, round wind :param melds: opened sets :return:
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/hand_calculating/fu.py#L29-L154
[ "def round_fu(self, fu_details):\n # 22 -> 30 and etc.\n fu = sum([x['fu'] for x in fu_details])\n return (fu + 9) // 10 * 10\n" ]
class FuCalculator(object): BASE = 'base' PENCHAN = 'penchan' KANCHAN = 'kanchan' VALUED_PAIR = 'valued_pair' PAIR_WAIT = 'pair_wait' TSUMO = 'tsumo' HAND_WITHOUT_FU = 'hand_without_fu' CLOSED_PON = 'closed_pon' OPEN_PON = 'open_pon' CLOSED_TERMINAL_PON = 'closed_terminal_pon' OPEN_TERMINAL_PON = 'open_terminal_pon' CLOSED_KAN = 'closed_kan' OPEN_KAN = 'open_kan' CLOSED_TERMINAL_KAN = 'closed_terminal_kan' OPEN_TERMINAL_KAN = 'open_terminal_kan' def round_fu(self, fu_details): # 22 -> 30 and etc. fu = sum([x['fu'] for x in fu_details]) return (fu + 9) // 10 * 10
MahjongRepository/mahjong
mahjong/shanten.py
Shanten.calculate_shanten
python
def calculate_shanten(self, tiles_34, open_sets_34=None, chiitoitsu=True, kokushi=True): # we will modify them later, so we need to use a copy tiles_34 = copy.deepcopy(tiles_34) self._init(tiles_34) count_of_tiles = sum(tiles_34) if count_of_tiles > 14: return -2 # With open hand we need to remove open sets from hand and replace them with isolated pon sets # it will allow to calculate count of shanten correctly if open_sets_34: isolated_tiles = find_isolated_tile_indices(tiles_34) for meld in open_sets_34: if not isolated_tiles: break isolated_tile = isolated_tiles.pop() tiles_34[meld[0]] -= 1 tiles_34[meld[1]] -= 1 tiles_34[meld[2]] -= 1 tiles_34[isolated_tile] = 3 if not open_sets_34: self.min_shanten = self._scan_chiitoitsu_and_kokushi(chiitoitsu, kokushi) self._remove_character_tiles(count_of_tiles) init_mentsu = math.floor((14 - count_of_tiles) / 3) self._scan(init_mentsu) return self.min_shanten
Return the count of tiles before tempai :param tiles_34: 34 tiles format array :param open_sets_34: array of array of 34 tiles format :param chiitoitsu: bool :param kokushi: bool :return: int
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/shanten.py#L21-L63
[ "def _init(self, tiles):\n self.tiles = tiles\n self.number_melds = 0\n self.number_tatsu = 0\n self.number_pairs = 0\n self.number_jidahai = 0\n self.number_characters = 0\n self.number_isolated_tiles = 0\n self.min_shanten = 8\n", "def _scan(self, init_mentsu):\n self.number_characters = 0\n for i in range(0, 27):\n self.number_characters |= (self.tiles[i] == 4) << i\n self.number_melds += init_mentsu\n self._run(0)\n", "def _scan_chiitoitsu_and_kokushi(self, chiitoitsu, kokushi):\n shanten = self.min_shanten\n\n indices = [0, 8, 9, 17, 18, 26, 27, 28, 29, 30, 31, 32, 33]\n\n completed_terminals = 0\n for i in indices:\n completed_terminals += self.tiles[i] >= 2\n\n terminals = 0\n for i in indices:\n terminals += self.tiles[i] != 0\n\n indices = [1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25]\n\n completed_pairs = completed_terminals\n for i in indices:\n completed_pairs += self.tiles[i] >= 2\n\n pairs = terminals\n for i in indices:\n pairs += self.tiles[i] != 0\n\n if chiitoitsu:\n ret_shanten = 6 - completed_pairs + (pairs < 7 and 7 - pairs or 0)\n if ret_shanten < shanten:\n shanten = ret_shanten\n\n if kokushi:\n ret_shanten = 13 - terminals - (completed_terminals and 1 or 0)\n if ret_shanten < shanten:\n shanten = ret_shanten\n\n return shanten\n", "def _remove_character_tiles(self, nc):\n number = 0\n isolated = 0\n\n for i in range(27, 34):\n if self.tiles[i] == 4:\n self.number_melds += 1\n self.number_jidahai += 1\n number |= (1 << (i - 27))\n isolated |= (1 << (i - 27))\n\n if self.tiles[i] == 3:\n self.number_melds += 1\n\n if self.tiles[i] == 2:\n self.number_pairs += 1\n\n if self.tiles[i] == 1:\n isolated |= (1 << (i - 27))\n\n if self.number_jidahai and (nc % 3) == 2:\n self.number_jidahai -= 1\n\n if isolated:\n self.number_isolated_tiles |= (1 << 27)\n if (number | isolated) == number:\n self.number_characters |= (1 << 27)\n" ]
class Shanten(object): AGARI_STATE = -1 tiles = [] number_melds = 0 number_tatsu = 0 number_pairs = 0 number_jidahai = 0 number_characters = 0 number_isolated_tiles = 0 min_shanten = 0 def _init(self, tiles): self.tiles = tiles self.number_melds = 0 self.number_tatsu = 0 self.number_pairs = 0 self.number_jidahai = 0 self.number_characters = 0 self.number_isolated_tiles = 0 self.min_shanten = 8 def _scan(self, init_mentsu): self.number_characters = 0 for i in range(0, 27): self.number_characters |= (self.tiles[i] == 4) << i self.number_melds += init_mentsu self._run(0) def _run(self, depth): if self.min_shanten == Shanten.AGARI_STATE: return while not self.tiles[depth]: depth += 1 if depth >= 27: break if depth >= 27: return self._update_result() i = depth if i > 8: i -= 9 if i > 8: i -= 9 if self.tiles[depth] == 4: self._increase_set(depth) if i < 7 and self.tiles[depth + 2]: if self.tiles[depth + 1]: self._increase_syuntsu(depth) self._run(depth + 1) self._decrease_syuntsu(depth) self._increase_tatsu_second(depth) self._run(depth + 1) self._decrease_tatsu_second(depth) if i < 8 and self.tiles[depth + 1]: self._increase_tatsu_first(depth) self._run(depth + 1) self._decrease_tatsu_first(depth) self._increase_isolated_tile(depth) self._run(depth + 1) self._decrease_isolated_tile(depth) self._decrease_set(depth) self._increase_pair(depth) if i < 7 and self.tiles[depth + 2]: if self.tiles[depth + 1]: self._increase_syuntsu(depth) self._run(depth) self._decrease_syuntsu(depth) self._increase_tatsu_second(depth) self._run(depth + 1) self._decrease_tatsu_second(depth) if i < 8 and self.tiles[depth + 1]: self._increase_tatsu_first(depth) self._run(depth + 1) self._decrease_tatsu_first(depth) self._decrease_pair(depth) if self.tiles[depth] == 3: self._increase_set(depth) self._run(depth + 1) self._decrease_set(depth) self._increase_pair(depth) if i < 7 and self.tiles[depth + 1] and self.tiles[depth + 2]: self._increase_syuntsu(depth) self._run(depth + 1) self._decrease_syuntsu(depth) else: if i < 7 and self.tiles[depth + 2]: self._increase_tatsu_second(depth) self._run(depth + 1) self._decrease_tatsu_second(depth) if i < 8 and self.tiles[depth + 1]: self._increase_tatsu_first(depth) self._run(depth + 1) self._decrease_tatsu_first(depth) self._decrease_pair(depth) if i < 7 and self.tiles[depth + 2] >= 2 and self.tiles[depth + 1] >= 2: self._increase_syuntsu(depth) self._increase_syuntsu(depth) self._run(depth) self._decrease_syuntsu(depth) self._decrease_syuntsu(depth) if self.tiles[depth] == 2: self._increase_pair(depth) self._run(depth + 1) self._decrease_pair(depth) if i < 7 and self.tiles[depth + 2] and self.tiles[depth + 1]: self._increase_syuntsu(depth) self._run(depth) self._decrease_syuntsu(depth) if self.tiles[depth] == 1: if i < 6 and self.tiles[depth + 1] == 1 and self.tiles[depth + 2] and self.tiles[depth + 3] != 4: self._increase_syuntsu(depth) self._run(depth + 2) self._decrease_syuntsu(depth) else: self._increase_isolated_tile(depth) self._run(depth + 1) self._decrease_isolated_tile(depth) if i < 7 and self.tiles[depth + 2]: if self.tiles[depth + 1]: self._increase_syuntsu(depth) self._run(depth + 1) self._decrease_syuntsu(depth) self._increase_tatsu_second(depth) self._run(depth + 1) self._decrease_tatsu_second(depth) if i < 8 and self.tiles[depth + 1]: self._increase_tatsu_first(depth) self._run(depth + 1) self._decrease_tatsu_first(depth) def _update_result(self): ret_shanten = 8 - self.number_melds * 2 - self.number_tatsu - self.number_pairs n_mentsu_kouho = self.number_melds + self.number_tatsu if self.number_pairs: n_mentsu_kouho += self.number_pairs - 1 elif self.number_characters and self.number_isolated_tiles: if (self.number_characters | self.number_isolated_tiles) == self.number_characters: ret_shanten += 1 if n_mentsu_kouho > 4: ret_shanten += n_mentsu_kouho - 4 if ret_shanten != Shanten.AGARI_STATE and ret_shanten < self.number_jidahai: ret_shanten = self.number_jidahai if ret_shanten < self.min_shanten: self.min_shanten = ret_shanten def _increase_set(self, k): self.tiles[k] -= 3 self.number_melds += 1 def _decrease_set(self, k): self.tiles[k] += 3 self.number_melds -= 1 def _increase_pair(self, k): self.tiles[k] -= 2 self.number_pairs += 1 def _decrease_pair(self, k): self.tiles[k] += 2 self.number_pairs -= 1 def _increase_syuntsu(self, k): self.tiles[k] -= 1 self.tiles[k + 1] -= 1 self.tiles[k + 2] -= 1 self.number_melds += 1 def _decrease_syuntsu(self, k): self.tiles[k] += 1 self.tiles[k + 1] += 1 self.tiles[k + 2] += 1 self.number_melds -= 1 def _increase_tatsu_first(self, k): self.tiles[k] -= 1 self.tiles[k + 1] -= 1 self.number_tatsu += 1 def _decrease_tatsu_first(self, k): self.tiles[k] += 1 self.tiles[k + 1] += 1 self.number_tatsu -= 1 def _increase_tatsu_second(self, k): self.tiles[k] -= 1 self.tiles[k + 2] -= 1 self.number_tatsu += 1 def _decrease_tatsu_second(self, k): self.tiles[k] += 1 self.tiles[k + 2] += 1 self.number_tatsu -= 1 def _increase_isolated_tile(self, k): self.tiles[k] -= 1 self.number_isolated_tiles |= (1 << k) def _decrease_isolated_tile(self, k): self.tiles[k] += 1 self.number_isolated_tiles |= (1 << k) def _scan_chiitoitsu_and_kokushi(self, chiitoitsu, kokushi): shanten = self.min_shanten indices = [0, 8, 9, 17, 18, 26, 27, 28, 29, 30, 31, 32, 33] completed_terminals = 0 for i in indices: completed_terminals += self.tiles[i] >= 2 terminals = 0 for i in indices: terminals += self.tiles[i] != 0 indices = [1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25] completed_pairs = completed_terminals for i in indices: completed_pairs += self.tiles[i] >= 2 pairs = terminals for i in indices: pairs += self.tiles[i] != 0 if chiitoitsu: ret_shanten = 6 - completed_pairs + (pairs < 7 and 7 - pairs or 0) if ret_shanten < shanten: shanten = ret_shanten if kokushi: ret_shanten = 13 - terminals - (completed_terminals and 1 or 0) if ret_shanten < shanten: shanten = ret_shanten return shanten def _remove_character_tiles(self, nc): number = 0 isolated = 0 for i in range(27, 34): if self.tiles[i] == 4: self.number_melds += 1 self.number_jidahai += 1 number |= (1 << (i - 27)) isolated |= (1 << (i - 27)) if self.tiles[i] == 3: self.number_melds += 1 if self.tiles[i] == 2: self.number_pairs += 1 if self.tiles[i] == 1: isolated |= (1 << (i - 27)) if self.number_jidahai and (nc % 3) == 2: self.number_jidahai -= 1 if isolated: self.number_isolated_tiles |= (1 << 27) if (number | isolated) == number: self.number_characters |= (1 << 27)
MahjongRepository/mahjong
mahjong/hand_calculating/yaku_list/sanankou.py
Sanankou.is_condition_met
python
def is_condition_met(self, hand, win_tile, melds, is_tsumo): win_tile //= 4 open_sets = [x.tiles_34 for x in melds if x.opened] chi_sets = [x for x in hand if (is_chi(x) and win_tile in x and x not in open_sets)] pon_sets = [x for x in hand if is_pon(x)] closed_pon_sets = [] for item in pon_sets: if item in open_sets: continue # if we do the ron on syanpon wait our pon will be consider as open # and it is not 789999 set if win_tile in item and not is_tsumo and not len(chi_sets): continue closed_pon_sets.append(item) return len(closed_pon_sets) == 3
Three closed pon sets, the other sets need not to be closed :param hand: list of hand's sets :param win_tile: 136 tiles format :param melds: list Meld objects :param is_tsumo: :return: true|false
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/hand_calculating/yaku_list/sanankou.py#L25-L53
null
class Sanankou(Yaku): """ Three closed pon sets, the other sets need not to be closed """ def __init__(self, yaku_id): super(Sanankou, self).__init__(yaku_id) def set_attributes(self): self.tenhou_id = 29 self.name = 'San Ankou' self.english = 'Tripple Concealed Triplets' self.han_open = 2 self.han_closed = 2 self.is_yakuman = False
MahjongRepository/mahjong
mahjong/hand_calculating/yaku_list/yakuman/daisuushi.py
DaiSuushii.is_condition_met
python
def is_condition_met(self, hand, *args): pon_sets = [x for x in hand if is_pon(x)] if len(pon_sets) != 4: return False count_wind_sets = 0 winds = [EAST, SOUTH, WEST, NORTH] for item in pon_sets: if is_pon(item) and item[0] in winds: count_wind_sets += 1 return count_wind_sets == 4
The hand contains four sets of winds :param hand: list of hand's sets :return: boolean
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/hand_calculating/yaku_list/yakuman/daisuushi.py#L26-L42
null
class DaiSuushii(Yaku): """ The hand contains four sets of winds """ def __init__(self, yaku_id): super(DaiSuushii, self).__init__(yaku_id) def set_attributes(self): self.tenhou_id = 49 self.name = 'Dai Suushii' self.english = 'Big Four Winds' self.han_open = 26 self.han_closed = 26 self.is_yakuman = True
MahjongRepository/mahjong
mahjong/hand_calculating/hand.py
HandCalculator.estimate_hand_value
python
def estimate_hand_value(self, tiles, win_tile, melds=None, dora_indicators=None, config=None): if not melds: melds = [] if not dora_indicators: dora_indicators = [] self.config = config or HandConfig() agari = Agari() hand_yaku = [] scores_calculator = ScoresCalculator() tiles_34 = TilesConverter.to_34_array(tiles) divider = HandDivider() fu_calculator = FuCalculator() opened_melds = [x.tiles_34 for x in melds if x.opened] all_melds = [x.tiles_34 for x in melds] is_open_hand = len(opened_melds) > 0 # special situation if self.config.is_nagashi_mangan: hand_yaku.append(self.config.yaku.nagashi_mangan) fu = 30 han = self.config.yaku.nagashi_mangan.han_closed cost = scores_calculator.calculate_scores(han, fu, self.config, False) return HandResponse(cost, han, fu, hand_yaku) if win_tile not in tiles: return HandResponse(error="Win tile not in the hand") if self.config.is_riichi and is_open_hand: return HandResponse(error="Riichi can't be declared with open hand") if self.config.is_ippatsu and is_open_hand: return HandResponse(error="Ippatsu can't be declared with open hand") if self.config.is_ippatsu and not self.config.is_riichi and not self.config.is_daburu_riichi: return HandResponse(error="Ippatsu can't be declared without riichi") if not agari.is_agari(tiles_34, all_melds): return HandResponse(error='Hand is not winning') if not self.config.options.has_double_yakuman: self.config.yaku.daburu_kokushi.han_closed = 13 self.config.yaku.suuankou_tanki.han_closed = 13 self.config.yaku.daburu_chuuren_poutou.han_closed = 13 self.config.yaku.daisuushi.han_closed = 13 self.config.yaku.daisuushi.han_open = 13 hand_options = divider.divide_hand(tiles_34, melds) calculated_hands = [] for hand in hand_options: is_chiitoitsu = self.config.yaku.chiitoitsu.is_condition_met(hand) valued_tiles = [HAKU, HATSU, CHUN, self.config.player_wind, self.config.round_wind] win_groups = self._find_win_groups(win_tile, hand, opened_melds) for win_group in win_groups: cost = None error = None hand_yaku = [] han = 0 fu_details, fu = fu_calculator.calculate_fu( hand, win_tile, win_group, self.config, valued_tiles, melds ) is_pinfu = len(fu_details) == 1 and not is_chiitoitsu and not is_open_hand pon_sets = [x for x in hand if is_pon(x)] chi_sets = [x for x in hand if is_chi(x)] if self.config.is_tsumo: if not is_open_hand: hand_yaku.append(self.config.yaku.tsumo) if is_pinfu: hand_yaku.append(self.config.yaku.pinfu) # let's skip hand that looks like chitoitsu, but it contains open sets if is_chiitoitsu and is_open_hand: continue if is_chiitoitsu: hand_yaku.append(self.config.yaku.chiitoitsu) if self.config.options.has_daisharin and self.config.yaku.daisharin.is_condition_met(hand, self.config.options.has_daisharin_other_suits): self.config.yaku.daisharin.rename(hand) hand_yaku.append(self.config.yaku.daisharin) is_tanyao = self.config.yaku.tanyao.is_condition_met(hand) if is_open_hand and not self.config.options.has_open_tanyao: is_tanyao = False if is_tanyao: hand_yaku.append(self.config.yaku.tanyao) if self.config.is_riichi and not self.config.is_daburu_riichi: hand_yaku.append(self.config.yaku.riichi) if self.config.is_daburu_riichi: hand_yaku.append(self.config.yaku.daburu_riichi) if self.config.is_ippatsu: hand_yaku.append(self.config.yaku.ippatsu) if self.config.is_rinshan: hand_yaku.append(self.config.yaku.rinshan) if self.config.is_chankan: hand_yaku.append(self.config.yaku.chankan) if self.config.is_haitei: hand_yaku.append(self.config.yaku.haitei) if self.config.is_houtei: hand_yaku.append(self.config.yaku.houtei) if self.config.is_renhou: if self.config.options.renhou_as_yakuman: hand_yaku.append(self.config.yaku.renhou_yakuman) else: hand_yaku.append(self.config.yaku.renhou) if self.config.is_tenhou: hand_yaku.append(self.config.yaku.tenhou) if self.config.is_chiihou: hand_yaku.append(self.config.yaku.chiihou) if self.config.yaku.honitsu.is_condition_met(hand): hand_yaku.append(self.config.yaku.honitsu) if self.config.yaku.chinitsu.is_condition_met(hand): hand_yaku.append(self.config.yaku.chinitsu) if self.config.yaku.tsuisou.is_condition_met(hand): hand_yaku.append(self.config.yaku.tsuisou) if self.config.yaku.honroto.is_condition_met(hand): hand_yaku.append(self.config.yaku.honroto) if self.config.yaku.chinroto.is_condition_met(hand): hand_yaku.append(self.config.yaku.chinroto) # small optimization, try to detect yaku with chi required sets only if we have chi sets in hand if len(chi_sets): if self.config.yaku.chanta.is_condition_met(hand): hand_yaku.append(self.config.yaku.chanta) if self.config.yaku.junchan.is_condition_met(hand): hand_yaku.append(self.config.yaku.junchan) if self.config.yaku.ittsu.is_condition_met(hand): hand_yaku.append(self.config.yaku.ittsu) if not is_open_hand: if self.config.yaku.ryanpeiko.is_condition_met(hand): hand_yaku.append(self.config.yaku.ryanpeiko) elif self.config.yaku.iipeiko.is_condition_met(hand): hand_yaku.append(self.config.yaku.iipeiko) if self.config.yaku.sanshoku.is_condition_met(hand): hand_yaku.append(self.config.yaku.sanshoku) # small optimization, try to detect yaku with pon required sets only if we have pon sets in hand if len(pon_sets): if self.config.yaku.toitoi.is_condition_met(hand): hand_yaku.append(self.config.yaku.toitoi) if self.config.yaku.sanankou.is_condition_met(hand, win_tile, melds, self.config.is_tsumo): hand_yaku.append(self.config.yaku.sanankou) if self.config.yaku.sanshoku_douko.is_condition_met(hand): hand_yaku.append(self.config.yaku.sanshoku_douko) if self.config.yaku.shosangen.is_condition_met(hand): hand_yaku.append(self.config.yaku.shosangen) if self.config.yaku.haku.is_condition_met(hand): hand_yaku.append(self.config.yaku.haku) if self.config.yaku.hatsu.is_condition_met(hand): hand_yaku.append(self.config.yaku.hatsu) if self.config.yaku.chun.is_condition_met(hand): hand_yaku.append(self.config.yaku.chun) if self.config.yaku.east.is_condition_met(hand, self.config.player_wind, self.config.round_wind): if self.config.player_wind == EAST: hand_yaku.append(self.config.yaku.yakuhai_place) if self.config.round_wind == EAST: hand_yaku.append(self.config.yaku.yakuhai_round) if self.config.yaku.south.is_condition_met(hand, self.config.player_wind, self.config.round_wind): if self.config.player_wind == SOUTH: hand_yaku.append(self.config.yaku.yakuhai_place) if self.config.round_wind == SOUTH: hand_yaku.append(self.config.yaku.yakuhai_round) if self.config.yaku.west.is_condition_met(hand, self.config.player_wind, self.config.round_wind): if self.config.player_wind == WEST: hand_yaku.append(self.config.yaku.yakuhai_place) if self.config.round_wind == WEST: hand_yaku.append(self.config.yaku.yakuhai_round) if self.config.yaku.north.is_condition_met(hand, self.config.player_wind, self.config.round_wind): if self.config.player_wind == NORTH: hand_yaku.append(self.config.yaku.yakuhai_place) if self.config.round_wind == NORTH: hand_yaku.append(self.config.yaku.yakuhai_round) if self.config.yaku.daisangen.is_condition_met(hand): hand_yaku.append(self.config.yaku.daisangen) if self.config.yaku.shosuushi.is_condition_met(hand): hand_yaku.append(self.config.yaku.shosuushi) if self.config.yaku.daisuushi.is_condition_met(hand): hand_yaku.append(self.config.yaku.daisuushi) if self.config.yaku.ryuisou.is_condition_met(hand): hand_yaku.append(self.config.yaku.ryuisou) # closed kan can't be used in chuuren_poutou if not len(melds) and self.config.yaku.chuuren_poutou.is_condition_met(hand): if tiles_34[win_tile // 4] == 2: hand_yaku.append(self.config.yaku.daburu_chuuren_poutou) else: hand_yaku.append(self.config.yaku.chuuren_poutou) if not is_open_hand and self.config.yaku.suuankou.is_condition_met(hand, win_tile, self.config.is_tsumo): if tiles_34[win_tile // 4] == 2: hand_yaku.append(self.config.yaku.suuankou_tanki) else: hand_yaku.append(self.config.yaku.suuankou) if self.config.yaku.sankantsu.is_condition_met(hand, melds): hand_yaku.append(self.config.yaku.sankantsu) if self.config.yaku.suukantsu.is_condition_met(hand, melds): hand_yaku.append(self.config.yaku.suukantsu) # yakuman is not connected with other yaku yakuman_list = [x for x in hand_yaku if x.is_yakuman] if yakuman_list: hand_yaku = yakuman_list # calculate han for item in hand_yaku: if is_open_hand and item.han_open: han += item.han_open else: han += item.han_closed if han == 0: error = 'There are no yaku in the hand' cost = None # we don't need to add dora to yakuman if not yakuman_list: tiles_for_dora = tiles[:] # we had to search for dora in kan fourth tiles as well for meld in melds: if meld.type == Meld.KAN or meld.type == Meld.CHANKAN: tiles_for_dora.append(meld.tiles[3]) count_of_dora = 0 count_of_aka_dora = 0 for tile in tiles_for_dora: count_of_dora += plus_dora(tile, dora_indicators) for tile in tiles_for_dora: if is_aka_dora(tile, self.config.options.has_aka_dora): count_of_aka_dora += 1 if count_of_dora: self.config.yaku.dora.han_open = count_of_dora self.config.yaku.dora.han_closed = count_of_dora hand_yaku.append(self.config.yaku.dora) han += count_of_dora if count_of_aka_dora: self.config.yaku.aka_dora.han_open = count_of_aka_dora self.config.yaku.aka_dora.han_closed = count_of_aka_dora hand_yaku.append(self.config.yaku.aka_dora) han += count_of_aka_dora if not error: cost = scores_calculator.calculate_scores(han, fu, self.config, len(yakuman_list) > 0) calculated_hand = { 'cost': cost, 'error': error, 'hand_yaku': hand_yaku, 'han': han, 'fu': fu, 'fu_details': fu_details } calculated_hands.append(calculated_hand) # exception hand if not is_open_hand and self.config.yaku.kokushi.is_condition_met(None, tiles_34): if tiles_34[win_tile // 4] == 2: hand_yaku.append(self.config.yaku.daburu_kokushi) else: hand_yaku.append(self.config.yaku.kokushi) if self.config.is_renhou and self.config.options.renhou_as_yakuman: hand_yaku.append(self.config.yaku.renhou_yakuman) if self.config.is_tenhou: hand_yaku.append(self.config.yaku.tenhou) if self.config.is_chiihou: hand_yaku.append(self.config.yaku.chiihou) # calculate han han = 0 for item in hand_yaku: if is_open_hand and item.han_open: han += item.han_open else: han += item.han_closed fu = 0 cost = scores_calculator.calculate_scores(han, fu, self.config, len(hand_yaku) > 0) calculated_hands.append({ 'cost': cost, 'error': None, 'hand_yaku': hand_yaku, 'han': han, 'fu': fu, 'fu_details': [] }) # let's use cost for most expensive hand calculated_hands = sorted(calculated_hands, key=lambda x: (x['han'], x['fu']), reverse=True) calculated_hand = calculated_hands[0] cost = calculated_hand['cost'] error = calculated_hand['error'] hand_yaku = calculated_hand['hand_yaku'] han = calculated_hand['han'] fu = calculated_hand['fu'] fu_details = calculated_hand['fu_details'] return HandResponse(cost, han, fu, hand_yaku, error, fu_details)
:param tiles: array with 14 tiles in 136-tile format :param win_tile: 136 format tile that caused win (ron or tsumo) :param melds: array with Meld objects :param dora_indicators: array of tiles in 136-tile format :param config: HandConfig object :return: HandResponse object
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/hand_calculating/hand.py#L17-L387
[ "def _find_win_groups(self, win_tile, hand, opened_melds):\n win_tile_34 = (win_tile or 0) // 4\n\n # to detect win groups\n # we had to use only closed sets\n closed_set_items = []\n for x in hand:\n if x not in opened_melds:\n closed_set_items.append(x)\n else:\n opened_melds.remove(x)\n\n # for forms like 45666 and ron on 6\n # we can assume that ron was on 456 form and on 66 form\n # and depends on form we will have different hand cost\n # so, we had to check all possible win groups\n win_groups = [x for x in closed_set_items if win_tile_34 in x]\n unique_win_groups = [list(x) for x in set(tuple(x) for x in win_groups)]\n\n return unique_win_groups\n" ]
class HandCalculator(object): config = None def _find_win_groups(self, win_tile, hand, opened_melds): win_tile_34 = (win_tile or 0) // 4 # to detect win groups # we had to use only closed sets closed_set_items = [] for x in hand: if x not in opened_melds: closed_set_items.append(x) else: opened_melds.remove(x) # for forms like 45666 and ron on 6 # we can assume that ron was on 456 form and on 66 form # and depends on form we will have different hand cost # so, we had to check all possible win groups win_groups = [x for x in closed_set_items if win_tile_34 in x] unique_win_groups = [list(x) for x in set(tuple(x) for x in win_groups)] return unique_win_groups
MahjongRepository/mahjong
mahjong/utils.py
is_aka_dora
python
def is_aka_dora(tile, aka_enabled): if not aka_enabled: return False if tile in [FIVE_RED_MAN, FIVE_RED_PIN, FIVE_RED_SOU]: return True return False
:param tile: int 136 tiles format :param aka_enabled: depends on table rules :return: boolean
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/utils.py#L6-L19
null
import copy from mahjong.constants import EAST, FIVE_RED_MAN, FIVE_RED_PIN, FIVE_RED_SOU, TERMINAL_INDICES, CHUN def plus_dora(tile, dora_indicators): """ :param tile: int 136 tiles format :param dora_indicators: array of 136 tiles format :return: int count of dora """ tile_index = tile // 4 dora_count = 0 for dora in dora_indicators: dora //= 4 # sou, pin, man if tile_index < EAST: # with indicator 9, dora will be 1 if dora == 8: dora = -1 elif dora == 17: dora = 8 elif dora == 26: dora = 17 if tile_index == dora + 1: dora_count += 1 else: if dora < EAST: continue dora -= 9 * 3 tile_index_temp = tile_index - 9 * 3 # dora indicator is north if dora == 3: dora = -1 # dora indicator is hatsu if dora == 6: dora = 3 if tile_index_temp == dora + 1: dora_count += 1 return dora_count def is_chi(item): """ :param item: array of tile 34 indices :return: boolean """ if len(item) != 3: return False return item[0] == item[1] - 1 == item[2] - 2 def is_pon(item): """ :param item: array of tile 34 indices :return: boolean """ if len(item) != 3: return False return item[0] == item[1] == item[2] def is_pair(item): """ :param item: array of tile 34 indices :return: boolean """ return len(item) == 2 def is_man(tile): """ :param tile: 34 tile format :return: boolean """ return tile <= 8 def is_pin(tile): """ :param tile: 34 tile format :return: boolean """ return 8 < tile <= 17 def is_sou(tile): """ :param tile: 34 tile format :return: boolean """ return 17 < tile <= 26 def is_honor(tile): """ :param tile: 34 tile format :return: boolean """ return tile >= 27 def is_terminal(tile): """ :param tile: 34 tile format :return: boolean """ return tile in TERMINAL_INDICES def is_dora_indicator_for_terminal(tile): """ :param tile: 34 tile format :return: boolean """ return tile == 7 or tile == 8 or tile == 16 or tile == 17 or tile == 25 or tile == 26 def contains_terminals(hand_set): """ :param hand_set: array of 34 tiles :return: boolean """ return any([x in TERMINAL_INDICES for x in hand_set]) def simplify(tile): """ :param tile: 34 tile format :return: tile: 0-8 presentation """ return tile - 9 * (tile // 9) def find_isolated_tile_indices(hand_34): """ Tiles that don't have -1, 0 and +1 neighbors :param hand_34: array of tiles in 34 tile format :return: array of isolated tiles indices """ isolated_indices = [] for x in range(0, CHUN + 1): # for honor tiles we don't need to check nearby tiles if is_honor(x) and hand_34[x] == 0: isolated_indices.append(x) else: simplified = simplify(x) # 1 suit tile if simplified == 0: if hand_34[x] == 0 and hand_34[x + 1] == 0: isolated_indices.append(x) # 9 suit tile elif simplified == 8: if hand_34[x] == 0 and hand_34[x - 1] == 0: isolated_indices.append(x) # 2-8 tiles tiles else: if hand_34[x] == 0 and hand_34[x - 1] == 0 and hand_34[x + 1] == 0: isolated_indices.append(x) return isolated_indices def is_tile_strictly_isolated(hand_34, tile_34): """ Tile is strictly isolated if it doesn't have -2, -1, 0, +1, +2 neighbors :param hand_34: array of tiles in 34 tile format :param tile_34: int :return: bool """ hand_34 = copy.copy(hand_34) # we don't need to count target tile in the hand hand_34[tile_34] -= 1 if hand_34[tile_34] < 0: hand_34[tile_34] = 0 indices = [] if is_honor(tile_34): return hand_34[tile_34] == 0 else: simplified = simplify(tile_34) # 1 suit tile if simplified == 0: indices = [tile_34, tile_34 + 1, tile_34 + 2] # 2 suit tile elif simplified == 1: indices = [tile_34 - 1, tile_34, tile_34 + 1, tile_34 + 2] # 8 suit tile elif simplified == 7: indices = [tile_34 - 2, tile_34 - 1, tile_34, tile_34 + 1] # 9 suit tile elif simplified == 8: indices = [tile_34 - 2, tile_34 - 1, tile_34] # 3-7 tiles tiles else: indices = [tile_34 - 2, tile_34 - 1, tile_34, tile_34 + 1, tile_34 + 2] return all([hand_34[x] == 0 for x in indices]) def count_tiles_by_suits(tiles_34): """ Separate tiles by suits and count them :param tiles_34: array of tiles to count :return: dict """ suits = [ {'count': 0, 'name': 'sou', 'function': is_sou}, {'count': 0, 'name': 'man', 'function': is_man}, {'count': 0, 'name': 'pin', 'function': is_pin}, {'count': 0, 'name': 'honor', 'function': is_honor} ] for x in range(0, 34): tile = tiles_34[x] if not tile: continue for item in suits: if item['function'](x): item['count'] += tile return suits
MahjongRepository/mahjong
mahjong/utils.py
plus_dora
python
def plus_dora(tile, dora_indicators): tile_index = tile // 4 dora_count = 0 for dora in dora_indicators: dora //= 4 # sou, pin, man if tile_index < EAST: # with indicator 9, dora will be 1 if dora == 8: dora = -1 elif dora == 17: dora = 8 elif dora == 26: dora = 17 if tile_index == dora + 1: dora_count += 1 else: if dora < EAST: continue dora -= 9 * 3 tile_index_temp = tile_index - 9 * 3 # dora indicator is north if dora == 3: dora = -1 # dora indicator is hatsu if dora == 6: dora = 3 if tile_index_temp == dora + 1: dora_count += 1 return dora_count
:param tile: int 136 tiles format :param dora_indicators: array of 136 tiles format :return: int count of dora
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/utils.py#L22-L65
null
import copy from mahjong.constants import EAST, FIVE_RED_MAN, FIVE_RED_PIN, FIVE_RED_SOU, TERMINAL_INDICES, CHUN def is_aka_dora(tile, aka_enabled): """ :param tile: int 136 tiles format :param aka_enabled: depends on table rules :return: boolean """ if not aka_enabled: return False if tile in [FIVE_RED_MAN, FIVE_RED_PIN, FIVE_RED_SOU]: return True return False def is_chi(item): """ :param item: array of tile 34 indices :return: boolean """ if len(item) != 3: return False return item[0] == item[1] - 1 == item[2] - 2 def is_pon(item): """ :param item: array of tile 34 indices :return: boolean """ if len(item) != 3: return False return item[0] == item[1] == item[2] def is_pair(item): """ :param item: array of tile 34 indices :return: boolean """ return len(item) == 2 def is_man(tile): """ :param tile: 34 tile format :return: boolean """ return tile <= 8 def is_pin(tile): """ :param tile: 34 tile format :return: boolean """ return 8 < tile <= 17 def is_sou(tile): """ :param tile: 34 tile format :return: boolean """ return 17 < tile <= 26 def is_honor(tile): """ :param tile: 34 tile format :return: boolean """ return tile >= 27 def is_terminal(tile): """ :param tile: 34 tile format :return: boolean """ return tile in TERMINAL_INDICES def is_dora_indicator_for_terminal(tile): """ :param tile: 34 tile format :return: boolean """ return tile == 7 or tile == 8 or tile == 16 or tile == 17 or tile == 25 or tile == 26 def contains_terminals(hand_set): """ :param hand_set: array of 34 tiles :return: boolean """ return any([x in TERMINAL_INDICES for x in hand_set]) def simplify(tile): """ :param tile: 34 tile format :return: tile: 0-8 presentation """ return tile - 9 * (tile // 9) def find_isolated_tile_indices(hand_34): """ Tiles that don't have -1, 0 and +1 neighbors :param hand_34: array of tiles in 34 tile format :return: array of isolated tiles indices """ isolated_indices = [] for x in range(0, CHUN + 1): # for honor tiles we don't need to check nearby tiles if is_honor(x) and hand_34[x] == 0: isolated_indices.append(x) else: simplified = simplify(x) # 1 suit tile if simplified == 0: if hand_34[x] == 0 and hand_34[x + 1] == 0: isolated_indices.append(x) # 9 suit tile elif simplified == 8: if hand_34[x] == 0 and hand_34[x - 1] == 0: isolated_indices.append(x) # 2-8 tiles tiles else: if hand_34[x] == 0 and hand_34[x - 1] == 0 and hand_34[x + 1] == 0: isolated_indices.append(x) return isolated_indices def is_tile_strictly_isolated(hand_34, tile_34): """ Tile is strictly isolated if it doesn't have -2, -1, 0, +1, +2 neighbors :param hand_34: array of tiles in 34 tile format :param tile_34: int :return: bool """ hand_34 = copy.copy(hand_34) # we don't need to count target tile in the hand hand_34[tile_34] -= 1 if hand_34[tile_34] < 0: hand_34[tile_34] = 0 indices = [] if is_honor(tile_34): return hand_34[tile_34] == 0 else: simplified = simplify(tile_34) # 1 suit tile if simplified == 0: indices = [tile_34, tile_34 + 1, tile_34 + 2] # 2 suit tile elif simplified == 1: indices = [tile_34 - 1, tile_34, tile_34 + 1, tile_34 + 2] # 8 suit tile elif simplified == 7: indices = [tile_34 - 2, tile_34 - 1, tile_34, tile_34 + 1] # 9 suit tile elif simplified == 8: indices = [tile_34 - 2, tile_34 - 1, tile_34] # 3-7 tiles tiles else: indices = [tile_34 - 2, tile_34 - 1, tile_34, tile_34 + 1, tile_34 + 2] return all([hand_34[x] == 0 for x in indices]) def count_tiles_by_suits(tiles_34): """ Separate tiles by suits and count them :param tiles_34: array of tiles to count :return: dict """ suits = [ {'count': 0, 'name': 'sou', 'function': is_sou}, {'count': 0, 'name': 'man', 'function': is_man}, {'count': 0, 'name': 'pin', 'function': is_pin}, {'count': 0, 'name': 'honor', 'function': is_honor} ] for x in range(0, 34): tile = tiles_34[x] if not tile: continue for item in suits: if item['function'](x): item['count'] += tile return suits
MahjongRepository/mahjong
mahjong/utils.py
find_isolated_tile_indices
python
def find_isolated_tile_indices(hand_34): isolated_indices = [] for x in range(0, CHUN + 1): # for honor tiles we don't need to check nearby tiles if is_honor(x) and hand_34[x] == 0: isolated_indices.append(x) else: simplified = simplify(x) # 1 suit tile if simplified == 0: if hand_34[x] == 0 and hand_34[x + 1] == 0: isolated_indices.append(x) # 9 suit tile elif simplified == 8: if hand_34[x] == 0 and hand_34[x - 1] == 0: isolated_indices.append(x) # 2-8 tiles tiles else: if hand_34[x] == 0 and hand_34[x - 1] == 0 and hand_34[x + 1] == 0: isolated_indices.append(x) return isolated_indices
Tiles that don't have -1, 0 and +1 neighbors :param hand_34: array of tiles in 34 tile format :return: array of isolated tiles indices
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/utils.py#L162-L190
[ "def simplify(tile):\n \"\"\"\n :param tile: 34 tile format\n :return: tile: 0-8 presentation\n \"\"\"\n return tile - 9 * (tile // 9)\n", "def is_honor(tile):\n \"\"\"\n :param tile: 34 tile format\n :return: boolean\n \"\"\"\n return tile >= 27\n" ]
import copy from mahjong.constants import EAST, FIVE_RED_MAN, FIVE_RED_PIN, FIVE_RED_SOU, TERMINAL_INDICES, CHUN def is_aka_dora(tile, aka_enabled): """ :param tile: int 136 tiles format :param aka_enabled: depends on table rules :return: boolean """ if not aka_enabled: return False if tile in [FIVE_RED_MAN, FIVE_RED_PIN, FIVE_RED_SOU]: return True return False def plus_dora(tile, dora_indicators): """ :param tile: int 136 tiles format :param dora_indicators: array of 136 tiles format :return: int count of dora """ tile_index = tile // 4 dora_count = 0 for dora in dora_indicators: dora //= 4 # sou, pin, man if tile_index < EAST: # with indicator 9, dora will be 1 if dora == 8: dora = -1 elif dora == 17: dora = 8 elif dora == 26: dora = 17 if tile_index == dora + 1: dora_count += 1 else: if dora < EAST: continue dora -= 9 * 3 tile_index_temp = tile_index - 9 * 3 # dora indicator is north if dora == 3: dora = -1 # dora indicator is hatsu if dora == 6: dora = 3 if tile_index_temp == dora + 1: dora_count += 1 return dora_count def is_chi(item): """ :param item: array of tile 34 indices :return: boolean """ if len(item) != 3: return False return item[0] == item[1] - 1 == item[2] - 2 def is_pon(item): """ :param item: array of tile 34 indices :return: boolean """ if len(item) != 3: return False return item[0] == item[1] == item[2] def is_pair(item): """ :param item: array of tile 34 indices :return: boolean """ return len(item) == 2 def is_man(tile): """ :param tile: 34 tile format :return: boolean """ return tile <= 8 def is_pin(tile): """ :param tile: 34 tile format :return: boolean """ return 8 < tile <= 17 def is_sou(tile): """ :param tile: 34 tile format :return: boolean """ return 17 < tile <= 26 def is_honor(tile): """ :param tile: 34 tile format :return: boolean """ return tile >= 27 def is_terminal(tile): """ :param tile: 34 tile format :return: boolean """ return tile in TERMINAL_INDICES def is_dora_indicator_for_terminal(tile): """ :param tile: 34 tile format :return: boolean """ return tile == 7 or tile == 8 or tile == 16 or tile == 17 or tile == 25 or tile == 26 def contains_terminals(hand_set): """ :param hand_set: array of 34 tiles :return: boolean """ return any([x in TERMINAL_INDICES for x in hand_set]) def simplify(tile): """ :param tile: 34 tile format :return: tile: 0-8 presentation """ return tile - 9 * (tile // 9) def is_tile_strictly_isolated(hand_34, tile_34): """ Tile is strictly isolated if it doesn't have -2, -1, 0, +1, +2 neighbors :param hand_34: array of tiles in 34 tile format :param tile_34: int :return: bool """ hand_34 = copy.copy(hand_34) # we don't need to count target tile in the hand hand_34[tile_34] -= 1 if hand_34[tile_34] < 0: hand_34[tile_34] = 0 indices = [] if is_honor(tile_34): return hand_34[tile_34] == 0 else: simplified = simplify(tile_34) # 1 suit tile if simplified == 0: indices = [tile_34, tile_34 + 1, tile_34 + 2] # 2 suit tile elif simplified == 1: indices = [tile_34 - 1, tile_34, tile_34 + 1, tile_34 + 2] # 8 suit tile elif simplified == 7: indices = [tile_34 - 2, tile_34 - 1, tile_34, tile_34 + 1] # 9 suit tile elif simplified == 8: indices = [tile_34 - 2, tile_34 - 1, tile_34] # 3-7 tiles tiles else: indices = [tile_34 - 2, tile_34 - 1, tile_34, tile_34 + 1, tile_34 + 2] return all([hand_34[x] == 0 for x in indices]) def count_tiles_by_suits(tiles_34): """ Separate tiles by suits and count them :param tiles_34: array of tiles to count :return: dict """ suits = [ {'count': 0, 'name': 'sou', 'function': is_sou}, {'count': 0, 'name': 'man', 'function': is_man}, {'count': 0, 'name': 'pin', 'function': is_pin}, {'count': 0, 'name': 'honor', 'function': is_honor} ] for x in range(0, 34): tile = tiles_34[x] if not tile: continue for item in suits: if item['function'](x): item['count'] += tile return suits
MahjongRepository/mahjong
mahjong/utils.py
is_tile_strictly_isolated
python
def is_tile_strictly_isolated(hand_34, tile_34): hand_34 = copy.copy(hand_34) # we don't need to count target tile in the hand hand_34[tile_34] -= 1 if hand_34[tile_34] < 0: hand_34[tile_34] = 0 indices = [] if is_honor(tile_34): return hand_34[tile_34] == 0 else: simplified = simplify(tile_34) # 1 suit tile if simplified == 0: indices = [tile_34, tile_34 + 1, tile_34 + 2] # 2 suit tile elif simplified == 1: indices = [tile_34 - 1, tile_34, tile_34 + 1, tile_34 + 2] # 8 suit tile elif simplified == 7: indices = [tile_34 - 2, tile_34 - 1, tile_34, tile_34 + 1] # 9 suit tile elif simplified == 8: indices = [tile_34 - 2, tile_34 - 1, tile_34] # 3-7 tiles tiles else: indices = [tile_34 - 2, tile_34 - 1, tile_34, tile_34 + 1, tile_34 + 2] return all([hand_34[x] == 0 for x in indices])
Tile is strictly isolated if it doesn't have -2, -1, 0, +1, +2 neighbors :param hand_34: array of tiles in 34 tile format :param tile_34: int :return: bool
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/utils.py#L193-L228
[ "def simplify(tile):\n \"\"\"\n :param tile: 34 tile format\n :return: tile: 0-8 presentation\n \"\"\"\n return tile - 9 * (tile // 9)\n", "def is_honor(tile):\n \"\"\"\n :param tile: 34 tile format\n :return: boolean\n \"\"\"\n return tile >= 27\n" ]
import copy from mahjong.constants import EAST, FIVE_RED_MAN, FIVE_RED_PIN, FIVE_RED_SOU, TERMINAL_INDICES, CHUN def is_aka_dora(tile, aka_enabled): """ :param tile: int 136 tiles format :param aka_enabled: depends on table rules :return: boolean """ if not aka_enabled: return False if tile in [FIVE_RED_MAN, FIVE_RED_PIN, FIVE_RED_SOU]: return True return False def plus_dora(tile, dora_indicators): """ :param tile: int 136 tiles format :param dora_indicators: array of 136 tiles format :return: int count of dora """ tile_index = tile // 4 dora_count = 0 for dora in dora_indicators: dora //= 4 # sou, pin, man if tile_index < EAST: # with indicator 9, dora will be 1 if dora == 8: dora = -1 elif dora == 17: dora = 8 elif dora == 26: dora = 17 if tile_index == dora + 1: dora_count += 1 else: if dora < EAST: continue dora -= 9 * 3 tile_index_temp = tile_index - 9 * 3 # dora indicator is north if dora == 3: dora = -1 # dora indicator is hatsu if dora == 6: dora = 3 if tile_index_temp == dora + 1: dora_count += 1 return dora_count def is_chi(item): """ :param item: array of tile 34 indices :return: boolean """ if len(item) != 3: return False return item[0] == item[1] - 1 == item[2] - 2 def is_pon(item): """ :param item: array of tile 34 indices :return: boolean """ if len(item) != 3: return False return item[0] == item[1] == item[2] def is_pair(item): """ :param item: array of tile 34 indices :return: boolean """ return len(item) == 2 def is_man(tile): """ :param tile: 34 tile format :return: boolean """ return tile <= 8 def is_pin(tile): """ :param tile: 34 tile format :return: boolean """ return 8 < tile <= 17 def is_sou(tile): """ :param tile: 34 tile format :return: boolean """ return 17 < tile <= 26 def is_honor(tile): """ :param tile: 34 tile format :return: boolean """ return tile >= 27 def is_terminal(tile): """ :param tile: 34 tile format :return: boolean """ return tile in TERMINAL_INDICES def is_dora_indicator_for_terminal(tile): """ :param tile: 34 tile format :return: boolean """ return tile == 7 or tile == 8 or tile == 16 or tile == 17 or tile == 25 or tile == 26 def contains_terminals(hand_set): """ :param hand_set: array of 34 tiles :return: boolean """ return any([x in TERMINAL_INDICES for x in hand_set]) def simplify(tile): """ :param tile: 34 tile format :return: tile: 0-8 presentation """ return tile - 9 * (tile // 9) def find_isolated_tile_indices(hand_34): """ Tiles that don't have -1, 0 and +1 neighbors :param hand_34: array of tiles in 34 tile format :return: array of isolated tiles indices """ isolated_indices = [] for x in range(0, CHUN + 1): # for honor tiles we don't need to check nearby tiles if is_honor(x) and hand_34[x] == 0: isolated_indices.append(x) else: simplified = simplify(x) # 1 suit tile if simplified == 0: if hand_34[x] == 0 and hand_34[x + 1] == 0: isolated_indices.append(x) # 9 suit tile elif simplified == 8: if hand_34[x] == 0 and hand_34[x - 1] == 0: isolated_indices.append(x) # 2-8 tiles tiles else: if hand_34[x] == 0 and hand_34[x - 1] == 0 and hand_34[x + 1] == 0: isolated_indices.append(x) return isolated_indices def count_tiles_by_suits(tiles_34): """ Separate tiles by suits and count them :param tiles_34: array of tiles to count :return: dict """ suits = [ {'count': 0, 'name': 'sou', 'function': is_sou}, {'count': 0, 'name': 'man', 'function': is_man}, {'count': 0, 'name': 'pin', 'function': is_pin}, {'count': 0, 'name': 'honor', 'function': is_honor} ] for x in range(0, 34): tile = tiles_34[x] if not tile: continue for item in suits: if item['function'](x): item['count'] += tile return suits
MahjongRepository/mahjong
mahjong/utils.py
count_tiles_by_suits
python
def count_tiles_by_suits(tiles_34): suits = [ {'count': 0, 'name': 'sou', 'function': is_sou}, {'count': 0, 'name': 'man', 'function': is_man}, {'count': 0, 'name': 'pin', 'function': is_pin}, {'count': 0, 'name': 'honor', 'function': is_honor} ] for x in range(0, 34): tile = tiles_34[x] if not tile: continue for item in suits: if item['function'](x): item['count'] += tile return suits
Separate tiles by suits and count them :param tiles_34: array of tiles to count :return: dict
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/utils.py#L231-L253
null
import copy from mahjong.constants import EAST, FIVE_RED_MAN, FIVE_RED_PIN, FIVE_RED_SOU, TERMINAL_INDICES, CHUN def is_aka_dora(tile, aka_enabled): """ :param tile: int 136 tiles format :param aka_enabled: depends on table rules :return: boolean """ if not aka_enabled: return False if tile in [FIVE_RED_MAN, FIVE_RED_PIN, FIVE_RED_SOU]: return True return False def plus_dora(tile, dora_indicators): """ :param tile: int 136 tiles format :param dora_indicators: array of 136 tiles format :return: int count of dora """ tile_index = tile // 4 dora_count = 0 for dora in dora_indicators: dora //= 4 # sou, pin, man if tile_index < EAST: # with indicator 9, dora will be 1 if dora == 8: dora = -1 elif dora == 17: dora = 8 elif dora == 26: dora = 17 if tile_index == dora + 1: dora_count += 1 else: if dora < EAST: continue dora -= 9 * 3 tile_index_temp = tile_index - 9 * 3 # dora indicator is north if dora == 3: dora = -1 # dora indicator is hatsu if dora == 6: dora = 3 if tile_index_temp == dora + 1: dora_count += 1 return dora_count def is_chi(item): """ :param item: array of tile 34 indices :return: boolean """ if len(item) != 3: return False return item[0] == item[1] - 1 == item[2] - 2 def is_pon(item): """ :param item: array of tile 34 indices :return: boolean """ if len(item) != 3: return False return item[0] == item[1] == item[2] def is_pair(item): """ :param item: array of tile 34 indices :return: boolean """ return len(item) == 2 def is_man(tile): """ :param tile: 34 tile format :return: boolean """ return tile <= 8 def is_pin(tile): """ :param tile: 34 tile format :return: boolean """ return 8 < tile <= 17 def is_sou(tile): """ :param tile: 34 tile format :return: boolean """ return 17 < tile <= 26 def is_honor(tile): """ :param tile: 34 tile format :return: boolean """ return tile >= 27 def is_terminal(tile): """ :param tile: 34 tile format :return: boolean """ return tile in TERMINAL_INDICES def is_dora_indicator_for_terminal(tile): """ :param tile: 34 tile format :return: boolean """ return tile == 7 or tile == 8 or tile == 16 or tile == 17 or tile == 25 or tile == 26 def contains_terminals(hand_set): """ :param hand_set: array of 34 tiles :return: boolean """ return any([x in TERMINAL_INDICES for x in hand_set]) def simplify(tile): """ :param tile: 34 tile format :return: tile: 0-8 presentation """ return tile - 9 * (tile // 9) def find_isolated_tile_indices(hand_34): """ Tiles that don't have -1, 0 and +1 neighbors :param hand_34: array of tiles in 34 tile format :return: array of isolated tiles indices """ isolated_indices = [] for x in range(0, CHUN + 1): # for honor tiles we don't need to check nearby tiles if is_honor(x) and hand_34[x] == 0: isolated_indices.append(x) else: simplified = simplify(x) # 1 suit tile if simplified == 0: if hand_34[x] == 0 and hand_34[x + 1] == 0: isolated_indices.append(x) # 9 suit tile elif simplified == 8: if hand_34[x] == 0 and hand_34[x - 1] == 0: isolated_indices.append(x) # 2-8 tiles tiles else: if hand_34[x] == 0 and hand_34[x - 1] == 0 and hand_34[x + 1] == 0: isolated_indices.append(x) return isolated_indices def is_tile_strictly_isolated(hand_34, tile_34): """ Tile is strictly isolated if it doesn't have -2, -1, 0, +1, +2 neighbors :param hand_34: array of tiles in 34 tile format :param tile_34: int :return: bool """ hand_34 = copy.copy(hand_34) # we don't need to count target tile in the hand hand_34[tile_34] -= 1 if hand_34[tile_34] < 0: hand_34[tile_34] = 0 indices = [] if is_honor(tile_34): return hand_34[tile_34] == 0 else: simplified = simplify(tile_34) # 1 suit tile if simplified == 0: indices = [tile_34, tile_34 + 1, tile_34 + 2] # 2 suit tile elif simplified == 1: indices = [tile_34 - 1, tile_34, tile_34 + 1, tile_34 + 2] # 8 suit tile elif simplified == 7: indices = [tile_34 - 2, tile_34 - 1, tile_34, tile_34 + 1] # 9 suit tile elif simplified == 8: indices = [tile_34 - 2, tile_34 - 1, tile_34] # 3-7 tiles tiles else: indices = [tile_34 - 2, tile_34 - 1, tile_34, tile_34 + 1, tile_34 + 2] return all([hand_34[x] == 0 for x in indices])
MahjongRepository/mahjong
mahjong/hand_calculating/yaku_list/yakuman/tsuisou.py
Tsuuiisou.is_condition_met
python
def is_condition_met(self, hand, *args): indices = reduce(lambda z, y: z + y, hand) return all(x in HONOR_INDICES for x in indices)
Hand composed entirely of honour tiles. :param hand: list of hand's sets :return: boolean
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/hand_calculating/yaku_list/yakuman/tsuisou.py#L27-L34
null
class Tsuuiisou(Yaku): """ Hand composed entirely of honour tiles """ def __init__(self, yaku_id): super(Tsuuiisou, self).__init__(yaku_id) def set_attributes(self): self.tenhou_id = 42 self.name = 'Tsuu iisou' self.english = 'All Honors' self.han_open = 13 self.han_closed = 13 self.is_yakuman = True
MahjongRepository/mahjong
mahjong/hand_calculating/divider.py
HandDivider.divide_hand
python
def divide_hand(self, tiles_34, melds=None): if not melds: melds = [] closed_hand_tiles_34 = tiles_34[:] # small optimization, we can't have a pair in open part of the hand, # so we don't need to try find pairs in open sets open_tile_indices = melds and reduce(lambda x, y: x + y, [x.tiles_34 for x in melds]) or [] for open_item in open_tile_indices: closed_hand_tiles_34[open_item] -= 1 pair_indices = self.find_pairs(closed_hand_tiles_34) # let's try to find all possible hand options hands = [] for pair_index in pair_indices: local_tiles_34 = tiles_34[:] # we don't need to combine already open sets for open_item in open_tile_indices: local_tiles_34[open_item] -= 1 local_tiles_34[pair_index] -= 2 # 0 - 8 man tiles man = self.find_valid_combinations(local_tiles_34, 0, 8) # 9 - 17 pin tiles pin = self.find_valid_combinations(local_tiles_34, 9, 17) # 18 - 26 sou tiles sou = self.find_valid_combinations(local_tiles_34, 18, 26) honor = [] for x in HONOR_INDICES: if local_tiles_34[x] == 3: honor.append([x] * 3) if honor: honor = [honor] arrays = [[[pair_index] * 2]] if sou: arrays.append(sou) if man: arrays.append(man) if pin: arrays.append(pin) if honor: arrays.append(honor) for meld in melds: arrays.append([meld.tiles_34]) # let's find all possible hand from our valid sets for s in itertools.product(*arrays): hand = [] for item in list(s): if isinstance(item[0], list): for x in item: hand.append(x) else: hand.append(item) hand = sorted(hand, key=lambda a: a[0]) if len(hand) == 5: hands.append(hand) # small optimization, let's remove hand duplicates unique_hands = [] for hand in hands: hand = sorted(hand, key=lambda x: (x[0], x[1])) if hand not in unique_hands: unique_hands.append(hand) hands = unique_hands if len(pair_indices) == 7: hand = [] for index in pair_indices: hand.append([index] * 2) hands.append(hand) return hands
Return a list of possible hands. :param tiles_34: :param melds: list of Meld objects :return:
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/hand_calculating/divider.py#L12-L102
[ "def find_pairs(self, tiles_34, first_index=0, second_index=33):\n \"\"\"\n Find all possible pairs in the hand and return their indices\n :return: array of pair indices\n \"\"\"\n pair_indices = []\n for x in range(first_index, second_index + 1):\n # ignore pon of honor tiles, because it can't be a part of pair\n if x in HONOR_INDICES and tiles_34[x] != 2:\n continue\n\n if tiles_34[x] >= 2:\n pair_indices.append(x)\n\n return pair_indices\n", "def find_valid_combinations(self, tiles_34, first_index, second_index, hand_not_completed=False):\n \"\"\"\n Find and return all valid set combinations in given suit\n :param tiles_34:\n :param first_index:\n :param second_index:\n :param hand_not_completed: in that mode we can return just possible shi\\pon sets\n :return: list of valid combinations\n \"\"\"\n indices = []\n for x in range(first_index, second_index + 1):\n if tiles_34[x] > 0:\n indices.extend([x] * tiles_34[x])\n\n if not indices:\n return []\n\n all_possible_combinations = list(itertools.permutations(indices, 3))\n\n def is_valid_combination(possible_set):\n if is_chi(possible_set):\n return True\n\n if is_pon(possible_set):\n return True\n\n return False\n\n valid_combinations = []\n for combination in all_possible_combinations:\n if is_valid_combination(combination):\n valid_combinations.append(list(combination))\n\n if not valid_combinations:\n return []\n\n count_of_needed_combinations = int(len(indices) / 3)\n\n # simple case, we have count of sets == count of tiles\n if count_of_needed_combinations == len(valid_combinations) and \\\n reduce(lambda z, y: z + y, valid_combinations) == indices:\n return [valid_combinations]\n\n # filter and remove not possible pon sets\n for item in valid_combinations:\n if is_pon(item):\n count_of_sets = 1\n count_of_tiles = 0\n while count_of_sets > count_of_tiles:\n count_of_tiles = len([x for x in indices if x == item[0]]) / 3\n count_of_sets = len([x for x in valid_combinations\n if x[0] == item[0] and x[1] == item[1] and x[2] == item[2]])\n\n if count_of_sets > count_of_tiles:\n valid_combinations.remove(item)\n\n # filter and remove not possible chi sets\n for item in valid_combinations:\n if is_chi(item):\n count_of_sets = 5\n # TODO calculate real count of possible sets\n count_of_possible_sets = 4\n while count_of_sets > count_of_possible_sets:\n count_of_sets = len([x for x in valid_combinations\n if x[0] == item[0] and x[1] == item[1] and x[2] == item[2]])\n\n if count_of_sets > count_of_possible_sets:\n valid_combinations.remove(item)\n\n # lit of chi\\pon sets for not completed hand\n if hand_not_completed:\n return [valid_combinations]\n\n # hard case - we can build a lot of sets from our tiles\n # for example we have 123456 tiles and we can build sets:\n # [1, 2, 3] [4, 5, 6] [2, 3, 4] [3, 4, 5]\n # and only two of them valid in the same time [1, 2, 3] [4, 5, 6]\n\n possible_combinations = set(itertools.permutations(\n range(0, len(valid_combinations)), count_of_needed_combinations\n ))\n\n combinations_results = []\n for combination in possible_combinations:\n result = []\n for item in combination:\n result += valid_combinations[item]\n result = sorted(result)\n\n if result == indices:\n results = []\n for item in combination:\n results.append(valid_combinations[item])\n results = sorted(results, key=lambda z: z[0])\n if results not in combinations_results:\n combinations_results.append(results)\n\n return combinations_results\n" ]
class HandDivider(object): def find_pairs(self, tiles_34, first_index=0, second_index=33): """ Find all possible pairs in the hand and return their indices :return: array of pair indices """ pair_indices = [] for x in range(first_index, second_index + 1): # ignore pon of honor tiles, because it can't be a part of pair if x in HONOR_INDICES and tiles_34[x] != 2: continue if tiles_34[x] >= 2: pair_indices.append(x) return pair_indices def find_valid_combinations(self, tiles_34, first_index, second_index, hand_not_completed=False): """ Find and return all valid set combinations in given suit :param tiles_34: :param first_index: :param second_index: :param hand_not_completed: in that mode we can return just possible shi\pon sets :return: list of valid combinations """ indices = [] for x in range(first_index, second_index + 1): if tiles_34[x] > 0: indices.extend([x] * tiles_34[x]) if not indices: return [] all_possible_combinations = list(itertools.permutations(indices, 3)) def is_valid_combination(possible_set): if is_chi(possible_set): return True if is_pon(possible_set): return True return False valid_combinations = [] for combination in all_possible_combinations: if is_valid_combination(combination): valid_combinations.append(list(combination)) if not valid_combinations: return [] count_of_needed_combinations = int(len(indices) / 3) # simple case, we have count of sets == count of tiles if count_of_needed_combinations == len(valid_combinations) and \ reduce(lambda z, y: z + y, valid_combinations) == indices: return [valid_combinations] # filter and remove not possible pon sets for item in valid_combinations: if is_pon(item): count_of_sets = 1 count_of_tiles = 0 while count_of_sets > count_of_tiles: count_of_tiles = len([x for x in indices if x == item[0]]) / 3 count_of_sets = len([x for x in valid_combinations if x[0] == item[0] and x[1] == item[1] and x[2] == item[2]]) if count_of_sets > count_of_tiles: valid_combinations.remove(item) # filter and remove not possible chi sets for item in valid_combinations: if is_chi(item): count_of_sets = 5 # TODO calculate real count of possible sets count_of_possible_sets = 4 while count_of_sets > count_of_possible_sets: count_of_sets = len([x for x in valid_combinations if x[0] == item[0] and x[1] == item[1] and x[2] == item[2]]) if count_of_sets > count_of_possible_sets: valid_combinations.remove(item) # lit of chi\pon sets for not completed hand if hand_not_completed: return [valid_combinations] # hard case - we can build a lot of sets from our tiles # for example we have 123456 tiles and we can build sets: # [1, 2, 3] [4, 5, 6] [2, 3, 4] [3, 4, 5] # and only two of them valid in the same time [1, 2, 3] [4, 5, 6] possible_combinations = set(itertools.permutations( range(0, len(valid_combinations)), count_of_needed_combinations )) combinations_results = [] for combination in possible_combinations: result = [] for item in combination: result += valid_combinations[item] result = sorted(result) if result == indices: results = [] for item in combination: results.append(valid_combinations[item]) results = sorted(results, key=lambda z: z[0]) if results not in combinations_results: combinations_results.append(results) return combinations_results
MahjongRepository/mahjong
mahjong/hand_calculating/divider.py
HandDivider.find_pairs
python
def find_pairs(self, tiles_34, first_index=0, second_index=33): pair_indices = [] for x in range(first_index, second_index + 1): # ignore pon of honor tiles, because it can't be a part of pair if x in HONOR_INDICES and tiles_34[x] != 2: continue if tiles_34[x] >= 2: pair_indices.append(x) return pair_indices
Find all possible pairs in the hand and return their indices :return: array of pair indices
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/hand_calculating/divider.py#L104-L118
null
class HandDivider(object): def divide_hand(self, tiles_34, melds=None): """ Return a list of possible hands. :param tiles_34: :param melds: list of Meld objects :return: """ if not melds: melds = [] closed_hand_tiles_34 = tiles_34[:] # small optimization, we can't have a pair in open part of the hand, # so we don't need to try find pairs in open sets open_tile_indices = melds and reduce(lambda x, y: x + y, [x.tiles_34 for x in melds]) or [] for open_item in open_tile_indices: closed_hand_tiles_34[open_item] -= 1 pair_indices = self.find_pairs(closed_hand_tiles_34) # let's try to find all possible hand options hands = [] for pair_index in pair_indices: local_tiles_34 = tiles_34[:] # we don't need to combine already open sets for open_item in open_tile_indices: local_tiles_34[open_item] -= 1 local_tiles_34[pair_index] -= 2 # 0 - 8 man tiles man = self.find_valid_combinations(local_tiles_34, 0, 8) # 9 - 17 pin tiles pin = self.find_valid_combinations(local_tiles_34, 9, 17) # 18 - 26 sou tiles sou = self.find_valid_combinations(local_tiles_34, 18, 26) honor = [] for x in HONOR_INDICES: if local_tiles_34[x] == 3: honor.append([x] * 3) if honor: honor = [honor] arrays = [[[pair_index] * 2]] if sou: arrays.append(sou) if man: arrays.append(man) if pin: arrays.append(pin) if honor: arrays.append(honor) for meld in melds: arrays.append([meld.tiles_34]) # let's find all possible hand from our valid sets for s in itertools.product(*arrays): hand = [] for item in list(s): if isinstance(item[0], list): for x in item: hand.append(x) else: hand.append(item) hand = sorted(hand, key=lambda a: a[0]) if len(hand) == 5: hands.append(hand) # small optimization, let's remove hand duplicates unique_hands = [] for hand in hands: hand = sorted(hand, key=lambda x: (x[0], x[1])) if hand not in unique_hands: unique_hands.append(hand) hands = unique_hands if len(pair_indices) == 7: hand = [] for index in pair_indices: hand.append([index] * 2) hands.append(hand) return hands def find_valid_combinations(self, tiles_34, first_index, second_index, hand_not_completed=False): """ Find and return all valid set combinations in given suit :param tiles_34: :param first_index: :param second_index: :param hand_not_completed: in that mode we can return just possible shi\pon sets :return: list of valid combinations """ indices = [] for x in range(first_index, second_index + 1): if tiles_34[x] > 0: indices.extend([x] * tiles_34[x]) if not indices: return [] all_possible_combinations = list(itertools.permutations(indices, 3)) def is_valid_combination(possible_set): if is_chi(possible_set): return True if is_pon(possible_set): return True return False valid_combinations = [] for combination in all_possible_combinations: if is_valid_combination(combination): valid_combinations.append(list(combination)) if not valid_combinations: return [] count_of_needed_combinations = int(len(indices) / 3) # simple case, we have count of sets == count of tiles if count_of_needed_combinations == len(valid_combinations) and \ reduce(lambda z, y: z + y, valid_combinations) == indices: return [valid_combinations] # filter and remove not possible pon sets for item in valid_combinations: if is_pon(item): count_of_sets = 1 count_of_tiles = 0 while count_of_sets > count_of_tiles: count_of_tiles = len([x for x in indices if x == item[0]]) / 3 count_of_sets = len([x for x in valid_combinations if x[0] == item[0] and x[1] == item[1] and x[2] == item[2]]) if count_of_sets > count_of_tiles: valid_combinations.remove(item) # filter and remove not possible chi sets for item in valid_combinations: if is_chi(item): count_of_sets = 5 # TODO calculate real count of possible sets count_of_possible_sets = 4 while count_of_sets > count_of_possible_sets: count_of_sets = len([x for x in valid_combinations if x[0] == item[0] and x[1] == item[1] and x[2] == item[2]]) if count_of_sets > count_of_possible_sets: valid_combinations.remove(item) # lit of chi\pon sets for not completed hand if hand_not_completed: return [valid_combinations] # hard case - we can build a lot of sets from our tiles # for example we have 123456 tiles and we can build sets: # [1, 2, 3] [4, 5, 6] [2, 3, 4] [3, 4, 5] # and only two of them valid in the same time [1, 2, 3] [4, 5, 6] possible_combinations = set(itertools.permutations( range(0, len(valid_combinations)), count_of_needed_combinations )) combinations_results = [] for combination in possible_combinations: result = [] for item in combination: result += valid_combinations[item] result = sorted(result) if result == indices: results = [] for item in combination: results.append(valid_combinations[item]) results = sorted(results, key=lambda z: z[0]) if results not in combinations_results: combinations_results.append(results) return combinations_results
MahjongRepository/mahjong
mahjong/hand_calculating/divider.py
HandDivider.find_valid_combinations
python
def find_valid_combinations(self, tiles_34, first_index, second_index, hand_not_completed=False): indices = [] for x in range(first_index, second_index + 1): if tiles_34[x] > 0: indices.extend([x] * tiles_34[x]) if not indices: return [] all_possible_combinations = list(itertools.permutations(indices, 3)) def is_valid_combination(possible_set): if is_chi(possible_set): return True if is_pon(possible_set): return True return False valid_combinations = [] for combination in all_possible_combinations: if is_valid_combination(combination): valid_combinations.append(list(combination)) if not valid_combinations: return [] count_of_needed_combinations = int(len(indices) / 3) # simple case, we have count of sets == count of tiles if count_of_needed_combinations == len(valid_combinations) and \ reduce(lambda z, y: z + y, valid_combinations) == indices: return [valid_combinations] # filter and remove not possible pon sets for item in valid_combinations: if is_pon(item): count_of_sets = 1 count_of_tiles = 0 while count_of_sets > count_of_tiles: count_of_tiles = len([x for x in indices if x == item[0]]) / 3 count_of_sets = len([x for x in valid_combinations if x[0] == item[0] and x[1] == item[1] and x[2] == item[2]]) if count_of_sets > count_of_tiles: valid_combinations.remove(item) # filter and remove not possible chi sets for item in valid_combinations: if is_chi(item): count_of_sets = 5 # TODO calculate real count of possible sets count_of_possible_sets = 4 while count_of_sets > count_of_possible_sets: count_of_sets = len([x for x in valid_combinations if x[0] == item[0] and x[1] == item[1] and x[2] == item[2]]) if count_of_sets > count_of_possible_sets: valid_combinations.remove(item) # lit of chi\pon sets for not completed hand if hand_not_completed: return [valid_combinations] # hard case - we can build a lot of sets from our tiles # for example we have 123456 tiles and we can build sets: # [1, 2, 3] [4, 5, 6] [2, 3, 4] [3, 4, 5] # and only two of them valid in the same time [1, 2, 3] [4, 5, 6] possible_combinations = set(itertools.permutations( range(0, len(valid_combinations)), count_of_needed_combinations )) combinations_results = [] for combination in possible_combinations: result = [] for item in combination: result += valid_combinations[item] result = sorted(result) if result == indices: results = [] for item in combination: results.append(valid_combinations[item]) results = sorted(results, key=lambda z: z[0]) if results not in combinations_results: combinations_results.append(results) return combinations_results
Find and return all valid set combinations in given suit :param tiles_34: :param first_index: :param second_index: :param hand_not_completed: in that mode we can return just possible shi\pon sets :return: list of valid combinations
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/hand_calculating/divider.py#L120-L217
[ "def is_valid_combination(possible_set):\n if is_chi(possible_set):\n return True\n\n if is_pon(possible_set):\n return True\n\n return False\n" ]
class HandDivider(object): def divide_hand(self, tiles_34, melds=None): """ Return a list of possible hands. :param tiles_34: :param melds: list of Meld objects :return: """ if not melds: melds = [] closed_hand_tiles_34 = tiles_34[:] # small optimization, we can't have a pair in open part of the hand, # so we don't need to try find pairs in open sets open_tile_indices = melds and reduce(lambda x, y: x + y, [x.tiles_34 for x in melds]) or [] for open_item in open_tile_indices: closed_hand_tiles_34[open_item] -= 1 pair_indices = self.find_pairs(closed_hand_tiles_34) # let's try to find all possible hand options hands = [] for pair_index in pair_indices: local_tiles_34 = tiles_34[:] # we don't need to combine already open sets for open_item in open_tile_indices: local_tiles_34[open_item] -= 1 local_tiles_34[pair_index] -= 2 # 0 - 8 man tiles man = self.find_valid_combinations(local_tiles_34, 0, 8) # 9 - 17 pin tiles pin = self.find_valid_combinations(local_tiles_34, 9, 17) # 18 - 26 sou tiles sou = self.find_valid_combinations(local_tiles_34, 18, 26) honor = [] for x in HONOR_INDICES: if local_tiles_34[x] == 3: honor.append([x] * 3) if honor: honor = [honor] arrays = [[[pair_index] * 2]] if sou: arrays.append(sou) if man: arrays.append(man) if pin: arrays.append(pin) if honor: arrays.append(honor) for meld in melds: arrays.append([meld.tiles_34]) # let's find all possible hand from our valid sets for s in itertools.product(*arrays): hand = [] for item in list(s): if isinstance(item[0], list): for x in item: hand.append(x) else: hand.append(item) hand = sorted(hand, key=lambda a: a[0]) if len(hand) == 5: hands.append(hand) # small optimization, let's remove hand duplicates unique_hands = [] for hand in hands: hand = sorted(hand, key=lambda x: (x[0], x[1])) if hand not in unique_hands: unique_hands.append(hand) hands = unique_hands if len(pair_indices) == 7: hand = [] for index in pair_indices: hand.append([index] * 2) hands.append(hand) return hands def find_pairs(self, tiles_34, first_index=0, second_index=33): """ Find all possible pairs in the hand and return their indices :return: array of pair indices """ pair_indices = [] for x in range(first_index, second_index + 1): # ignore pon of honor tiles, because it can't be a part of pair if x in HONOR_INDICES and tiles_34[x] != 2: continue if tiles_34[x] >= 2: pair_indices.append(x) return pair_indices
MahjongRepository/mahjong
mahjong/tile.py
TilesConverter.to_one_line_string
python
def to_one_line_string(tiles): tiles = sorted(tiles) man = [t for t in tiles if t < 36] pin = [t for t in tiles if 36 <= t < 72] pin = [t - 36 for t in pin] sou = [t for t in tiles if 72 <= t < 108] sou = [t - 72 for t in sou] honors = [t for t in tiles if t >= 108] honors = [t - 108 for t in honors] sou = sou and ''.join([str((i // 4) + 1) for i in sou]) + 's' or '' pin = pin and ''.join([str((i // 4) + 1) for i in pin]) + 'p' or '' man = man and ''.join([str((i // 4) + 1) for i in man]) + 'm' or '' honors = honors and ''.join([str((i // 4) + 1) for i in honors]) + 'z' or '' return man + pin + sou + honors
Convert 136 tiles array to the one line string Example of output 123s123p123m33z
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/tile.py#L17-L40
null
class TilesConverter(object): @staticmethod @staticmethod def to_34_array(tiles): """ Convert 136 array to the 34 tiles array """ results = [0] * 34 for tile in tiles: tile //= 4 results[tile] += 1 return results @staticmethod def to_136_array(tiles): """ Convert 34 array to the 136 tiles array """ temp = [] results = [] for x in range(0, 34): if tiles[x]: temp_value = [x * 4] * tiles[x] for tile in temp_value: if tile in results: count_of_tiles = len([x for x in temp if x == tile]) new_tile = tile + count_of_tiles results.append(new_tile) temp.append(tile) else: results.append(tile) temp.append(tile) return results @staticmethod def string_to_136_array(sou=None, pin=None, man=None, honors=None, has_aka_dora=False): """ Method to convert one line string tiles format to the 136 array. You can pass r instead of 5 for it to become a red five from that suit. To prevent old usage without red, has_aka_dora has to be True for this to do that. We need it to increase readability of our tests """ def _split_string(string, offset, red=None): data = [] temp = [] if not string: return [] for i in string: if i == 'r' and has_aka_dora: temp.append(red) data.append(red) else: tile = offset + (int(i) - 1) * 4 if tile == red and has_aka_dora: # prevent non reds to become red tile += 1 if tile in data: count_of_tiles = len([x for x in temp if x == tile]) new_tile = tile + count_of_tiles data.append(new_tile) temp.append(tile) else: data.append(tile) temp.append(tile) return data results = _split_string(man, 0, FIVE_RED_MAN) results += _split_string(pin, 36, FIVE_RED_PIN) results += _split_string(sou, 72, FIVE_RED_SOU) results += _split_string(honors, 108) return results @staticmethod def string_to_34_array(sou=None, pin=None, man=None, honors=None): """ Method to convert one line string tiles format to the 34 array We need it to increase readability of our tests """ results = TilesConverter.string_to_136_array(sou, pin, man, honors) results = TilesConverter.to_34_array(results) return results @staticmethod def find_34_tile_in_136_array(tile34, tiles): """ Our shanten calculator will operate with 34 tiles format, after calculations we need to find calculated 34 tile in player's 136 tiles. For example we had 0 tile from 34 array in 136 array it can be present as 0, 1, 2, 3 """ if tile34 is None or tile34 > 33: return None tile = tile34 * 4 possible_tiles = [tile] + [tile + i for i in range(1, 4)] found_tile = None for possible_tile in possible_tiles: if possible_tile in tiles: found_tile = possible_tile break return found_tile
MahjongRepository/mahjong
mahjong/tile.py
TilesConverter.to_136_array
python
def to_136_array(tiles): temp = [] results = [] for x in range(0, 34): if tiles[x]: temp_value = [x * 4] * tiles[x] for tile in temp_value: if tile in results: count_of_tiles = len([x for x in temp if x == tile]) new_tile = tile + count_of_tiles results.append(new_tile) temp.append(tile) else: results.append(tile) temp.append(tile) return results
Convert 34 array to the 136 tiles array
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/tile.py#L54-L73
null
class TilesConverter(object): @staticmethod def to_one_line_string(tiles): """ Convert 136 tiles array to the one line string Example of output 123s123p123m33z """ tiles = sorted(tiles) man = [t for t in tiles if t < 36] pin = [t for t in tiles if 36 <= t < 72] pin = [t - 36 for t in pin] sou = [t for t in tiles if 72 <= t < 108] sou = [t - 72 for t in sou] honors = [t for t in tiles if t >= 108] honors = [t - 108 for t in honors] sou = sou and ''.join([str((i // 4) + 1) for i in sou]) + 's' or '' pin = pin and ''.join([str((i // 4) + 1) for i in pin]) + 'p' or '' man = man and ''.join([str((i // 4) + 1) for i in man]) + 'm' or '' honors = honors and ''.join([str((i // 4) + 1) for i in honors]) + 'z' or '' return man + pin + sou + honors @staticmethod def to_34_array(tiles): """ Convert 136 array to the 34 tiles array """ results = [0] * 34 for tile in tiles: tile //= 4 results[tile] += 1 return results @staticmethod @staticmethod def string_to_136_array(sou=None, pin=None, man=None, honors=None, has_aka_dora=False): """ Method to convert one line string tiles format to the 136 array. You can pass r instead of 5 for it to become a red five from that suit. To prevent old usage without red, has_aka_dora has to be True for this to do that. We need it to increase readability of our tests """ def _split_string(string, offset, red=None): data = [] temp = [] if not string: return [] for i in string: if i == 'r' and has_aka_dora: temp.append(red) data.append(red) else: tile = offset + (int(i) - 1) * 4 if tile == red and has_aka_dora: # prevent non reds to become red tile += 1 if tile in data: count_of_tiles = len([x for x in temp if x == tile]) new_tile = tile + count_of_tiles data.append(new_tile) temp.append(tile) else: data.append(tile) temp.append(tile) return data results = _split_string(man, 0, FIVE_RED_MAN) results += _split_string(pin, 36, FIVE_RED_PIN) results += _split_string(sou, 72, FIVE_RED_SOU) results += _split_string(honors, 108) return results @staticmethod def string_to_34_array(sou=None, pin=None, man=None, honors=None): """ Method to convert one line string tiles format to the 34 array We need it to increase readability of our tests """ results = TilesConverter.string_to_136_array(sou, pin, man, honors) results = TilesConverter.to_34_array(results) return results @staticmethod def find_34_tile_in_136_array(tile34, tiles): """ Our shanten calculator will operate with 34 tiles format, after calculations we need to find calculated 34 tile in player's 136 tiles. For example we had 0 tile from 34 array in 136 array it can be present as 0, 1, 2, 3 """ if tile34 is None or tile34 > 33: return None tile = tile34 * 4 possible_tiles = [tile] + [tile + i for i in range(1, 4)] found_tile = None for possible_tile in possible_tiles: if possible_tile in tiles: found_tile = possible_tile break return found_tile
MahjongRepository/mahjong
mahjong/tile.py
TilesConverter.string_to_136_array
python
def string_to_136_array(sou=None, pin=None, man=None, honors=None, has_aka_dora=False): def _split_string(string, offset, red=None): data = [] temp = [] if not string: return [] for i in string: if i == 'r' and has_aka_dora: temp.append(red) data.append(red) else: tile = offset + (int(i) - 1) * 4 if tile == red and has_aka_dora: # prevent non reds to become red tile += 1 if tile in data: count_of_tiles = len([x for x in temp if x == tile]) new_tile = tile + count_of_tiles data.append(new_tile) temp.append(tile) else: data.append(tile) temp.append(tile) return data results = _split_string(man, 0, FIVE_RED_MAN) results += _split_string(pin, 36, FIVE_RED_PIN) results += _split_string(sou, 72, FIVE_RED_SOU) results += _split_string(honors, 108) return results
Method to convert one line string tiles format to the 136 array. You can pass r instead of 5 for it to become a red five from that suit. To prevent old usage without red, has_aka_dora has to be True for this to do that. We need it to increase readability of our tests
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/tile.py#L76-L117
[ "def _split_string(string, offset, red=None):\n data = []\n temp = []\n\n if not string:\n return []\n\n for i in string:\n if i == 'r' and has_aka_dora:\n temp.append(red)\n data.append(red)\n else:\n tile = offset + (int(i) - 1) * 4\n if tile == red and has_aka_dora:\n # prevent non reds to become red\n tile += 1\n if tile in data:\n count_of_tiles = len([x for x in temp if x == tile])\n new_tile = tile + count_of_tiles\n data.append(new_tile)\n\n temp.append(tile)\n else:\n data.append(tile)\n temp.append(tile)\n\n return data\n" ]
class TilesConverter(object): @staticmethod def to_one_line_string(tiles): """ Convert 136 tiles array to the one line string Example of output 123s123p123m33z """ tiles = sorted(tiles) man = [t for t in tiles if t < 36] pin = [t for t in tiles if 36 <= t < 72] pin = [t - 36 for t in pin] sou = [t for t in tiles if 72 <= t < 108] sou = [t - 72 for t in sou] honors = [t for t in tiles if t >= 108] honors = [t - 108 for t in honors] sou = sou and ''.join([str((i // 4) + 1) for i in sou]) + 's' or '' pin = pin and ''.join([str((i // 4) + 1) for i in pin]) + 'p' or '' man = man and ''.join([str((i // 4) + 1) for i in man]) + 'm' or '' honors = honors and ''.join([str((i // 4) + 1) for i in honors]) + 'z' or '' return man + pin + sou + honors @staticmethod def to_34_array(tiles): """ Convert 136 array to the 34 tiles array """ results = [0] * 34 for tile in tiles: tile //= 4 results[tile] += 1 return results @staticmethod def to_136_array(tiles): """ Convert 34 array to the 136 tiles array """ temp = [] results = [] for x in range(0, 34): if tiles[x]: temp_value = [x * 4] * tiles[x] for tile in temp_value: if tile in results: count_of_tiles = len([x for x in temp if x == tile]) new_tile = tile + count_of_tiles results.append(new_tile) temp.append(tile) else: results.append(tile) temp.append(tile) return results @staticmethod @staticmethod def string_to_34_array(sou=None, pin=None, man=None, honors=None): """ Method to convert one line string tiles format to the 34 array We need it to increase readability of our tests """ results = TilesConverter.string_to_136_array(sou, pin, man, honors) results = TilesConverter.to_34_array(results) return results @staticmethod def find_34_tile_in_136_array(tile34, tiles): """ Our shanten calculator will operate with 34 tiles format, after calculations we need to find calculated 34 tile in player's 136 tiles. For example we had 0 tile from 34 array in 136 array it can be present as 0, 1, 2, 3 """ if tile34 is None or tile34 > 33: return None tile = tile34 * 4 possible_tiles = [tile] + [tile + i for i in range(1, 4)] found_tile = None for possible_tile in possible_tiles: if possible_tile in tiles: found_tile = possible_tile break return found_tile
MahjongRepository/mahjong
mahjong/tile.py
TilesConverter.string_to_34_array
python
def string_to_34_array(sou=None, pin=None, man=None, honors=None): results = TilesConverter.string_to_136_array(sou, pin, man, honors) results = TilesConverter.to_34_array(results) return results
Method to convert one line string tiles format to the 34 array We need it to increase readability of our tests
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/tile.py#L120-L127
[ "def to_34_array(tiles):\n \"\"\"\n Convert 136 array to the 34 tiles array\n \"\"\"\n results = [0] * 34\n for tile in tiles:\n tile //= 4\n results[tile] += 1\n return results\n", "def string_to_136_array(sou=None, pin=None, man=None, honors=None, has_aka_dora=False):\n \"\"\"\n Method to convert one line string tiles format to the 136 array.\n You can pass r instead of 5 for it to become a red five from \n that suit. To prevent old usage without red, \n has_aka_dora has to be True for this to do that.\n We need it to increase readability of our tests\n \"\"\"\n def _split_string(string, offset, red=None):\n data = []\n temp = []\n\n if not string:\n return []\n\n for i in string:\n if i == 'r' and has_aka_dora:\n temp.append(red)\n data.append(red)\n else:\n tile = offset + (int(i) - 1) * 4\n if tile == red and has_aka_dora:\n # prevent non reds to become red\n tile += 1\n if tile in data:\n count_of_tiles = len([x for x in temp if x == tile])\n new_tile = tile + count_of_tiles\n data.append(new_tile)\n\n temp.append(tile)\n else:\n data.append(tile)\n temp.append(tile)\n\n return data\n\n results = _split_string(man, 0, FIVE_RED_MAN)\n results += _split_string(pin, 36, FIVE_RED_PIN)\n results += _split_string(sou, 72, FIVE_RED_SOU)\n results += _split_string(honors, 108)\n\n return results\n" ]
class TilesConverter(object): @staticmethod def to_one_line_string(tiles): """ Convert 136 tiles array to the one line string Example of output 123s123p123m33z """ tiles = sorted(tiles) man = [t for t in tiles if t < 36] pin = [t for t in tiles if 36 <= t < 72] pin = [t - 36 for t in pin] sou = [t for t in tiles if 72 <= t < 108] sou = [t - 72 for t in sou] honors = [t for t in tiles if t >= 108] honors = [t - 108 for t in honors] sou = sou and ''.join([str((i // 4) + 1) for i in sou]) + 's' or '' pin = pin and ''.join([str((i // 4) + 1) for i in pin]) + 'p' or '' man = man and ''.join([str((i // 4) + 1) for i in man]) + 'm' or '' honors = honors and ''.join([str((i // 4) + 1) for i in honors]) + 'z' or '' return man + pin + sou + honors @staticmethod def to_34_array(tiles): """ Convert 136 array to the 34 tiles array """ results = [0] * 34 for tile in tiles: tile //= 4 results[tile] += 1 return results @staticmethod def to_136_array(tiles): """ Convert 34 array to the 136 tiles array """ temp = [] results = [] for x in range(0, 34): if tiles[x]: temp_value = [x * 4] * tiles[x] for tile in temp_value: if tile in results: count_of_tiles = len([x for x in temp if x == tile]) new_tile = tile + count_of_tiles results.append(new_tile) temp.append(tile) else: results.append(tile) temp.append(tile) return results @staticmethod def string_to_136_array(sou=None, pin=None, man=None, honors=None, has_aka_dora=False): """ Method to convert one line string tiles format to the 136 array. You can pass r instead of 5 for it to become a red five from that suit. To prevent old usage without red, has_aka_dora has to be True for this to do that. We need it to increase readability of our tests """ def _split_string(string, offset, red=None): data = [] temp = [] if not string: return [] for i in string: if i == 'r' and has_aka_dora: temp.append(red) data.append(red) else: tile = offset + (int(i) - 1) * 4 if tile == red and has_aka_dora: # prevent non reds to become red tile += 1 if tile in data: count_of_tiles = len([x for x in temp if x == tile]) new_tile = tile + count_of_tiles data.append(new_tile) temp.append(tile) else: data.append(tile) temp.append(tile) return data results = _split_string(man, 0, FIVE_RED_MAN) results += _split_string(pin, 36, FIVE_RED_PIN) results += _split_string(sou, 72, FIVE_RED_SOU) results += _split_string(honors, 108) return results @staticmethod @staticmethod def find_34_tile_in_136_array(tile34, tiles): """ Our shanten calculator will operate with 34 tiles format, after calculations we need to find calculated 34 tile in player's 136 tiles. For example we had 0 tile from 34 array in 136 array it can be present as 0, 1, 2, 3 """ if tile34 is None or tile34 > 33: return None tile = tile34 * 4 possible_tiles = [tile] + [tile + i for i in range(1, 4)] found_tile = None for possible_tile in possible_tiles: if possible_tile in tiles: found_tile = possible_tile break return found_tile
MahjongRepository/mahjong
mahjong/tile.py
TilesConverter.find_34_tile_in_136_array
python
def find_34_tile_in_136_array(tile34, tiles): if tile34 is None or tile34 > 33: return None tile = tile34 * 4 possible_tiles = [tile] + [tile + i for i in range(1, 4)] found_tile = None for possible_tile in possible_tiles: if possible_tile in tiles: found_tile = possible_tile break return found_tile
Our shanten calculator will operate with 34 tiles format, after calculations we need to find calculated 34 tile in player's 136 tiles. For example we had 0 tile from 34 array in 136 array it can be present as 0, 1, 2, 3
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/tile.py#L130-L152
null
class TilesConverter(object): @staticmethod def to_one_line_string(tiles): """ Convert 136 tiles array to the one line string Example of output 123s123p123m33z """ tiles = sorted(tiles) man = [t for t in tiles if t < 36] pin = [t for t in tiles if 36 <= t < 72] pin = [t - 36 for t in pin] sou = [t for t in tiles if 72 <= t < 108] sou = [t - 72 for t in sou] honors = [t for t in tiles if t >= 108] honors = [t - 108 for t in honors] sou = sou and ''.join([str((i // 4) + 1) for i in sou]) + 's' or '' pin = pin and ''.join([str((i // 4) + 1) for i in pin]) + 'p' or '' man = man and ''.join([str((i // 4) + 1) for i in man]) + 'm' or '' honors = honors and ''.join([str((i // 4) + 1) for i in honors]) + 'z' or '' return man + pin + sou + honors @staticmethod def to_34_array(tiles): """ Convert 136 array to the 34 tiles array """ results = [0] * 34 for tile in tiles: tile //= 4 results[tile] += 1 return results @staticmethod def to_136_array(tiles): """ Convert 34 array to the 136 tiles array """ temp = [] results = [] for x in range(0, 34): if tiles[x]: temp_value = [x * 4] * tiles[x] for tile in temp_value: if tile in results: count_of_tiles = len([x for x in temp if x == tile]) new_tile = tile + count_of_tiles results.append(new_tile) temp.append(tile) else: results.append(tile) temp.append(tile) return results @staticmethod def string_to_136_array(sou=None, pin=None, man=None, honors=None, has_aka_dora=False): """ Method to convert one line string tiles format to the 136 array. You can pass r instead of 5 for it to become a red five from that suit. To prevent old usage without red, has_aka_dora has to be True for this to do that. We need it to increase readability of our tests """ def _split_string(string, offset, red=None): data = [] temp = [] if not string: return [] for i in string: if i == 'r' and has_aka_dora: temp.append(red) data.append(red) else: tile = offset + (int(i) - 1) * 4 if tile == red and has_aka_dora: # prevent non reds to become red tile += 1 if tile in data: count_of_tiles = len([x for x in temp if x == tile]) new_tile = tile + count_of_tiles data.append(new_tile) temp.append(tile) else: data.append(tile) temp.append(tile) return data results = _split_string(man, 0, FIVE_RED_MAN) results += _split_string(pin, 36, FIVE_RED_PIN) results += _split_string(sou, 72, FIVE_RED_SOU) results += _split_string(honors, 108) return results @staticmethod def string_to_34_array(sou=None, pin=None, man=None, honors=None): """ Method to convert one line string tiles format to the 34 array We need it to increase readability of our tests """ results = TilesConverter.string_to_136_array(sou, pin, man, honors) results = TilesConverter.to_34_array(results) return results @staticmethod
MahjongRepository/mahjong
mahjong/agari.py
Agari.is_agari
python
def is_agari(self, tiles_34, open_sets_34=None): # we will modify them later, so we need to use a copy tiles = copy.deepcopy(tiles_34) # With open hand we need to remove open sets from hand and replace them with isolated pon sets # it will allow to determine agari state correctly if open_sets_34: isolated_tiles = find_isolated_tile_indices(tiles) for meld in open_sets_34: if not isolated_tiles: break isolated_tile = isolated_tiles.pop() tiles[meld[0]] -= 1 tiles[meld[1]] -= 1 tiles[meld[2]] -= 1 tiles[isolated_tile] = 3 j = (1 << tiles[27]) | (1 << tiles[28]) | (1 << tiles[29]) | (1 << tiles[30]) | \ (1 << tiles[31]) | (1 << tiles[32]) | (1 << tiles[33]) if j >= 0x10: return False # 13 orphans if ((j & 3) == 2) and (tiles[0] * tiles[8] * tiles[9] * tiles[17] * tiles[18] * tiles[26] * tiles[27] * tiles[28] * tiles[29] * tiles[30] * tiles[31] * tiles[32] * tiles[33] == 2): return True # seven pairs if not (j & 10) and sum([tiles[i] == 2 for i in range(0, 34)]) == 7: return True if j & 2: return False n00 = tiles[0] + tiles[3] + tiles[6] n01 = tiles[1] + tiles[4] + tiles[7] n02 = tiles[2] + tiles[5] + tiles[8] n10 = tiles[9] + tiles[12] + tiles[15] n11 = tiles[10] + tiles[13] + tiles[16] n12 = tiles[11] + tiles[14] + tiles[17] n20 = tiles[18] + tiles[21] + tiles[24] n21 = tiles[19] + tiles[22] + tiles[25] n22 = tiles[20] + tiles[23] + tiles[26] n0 = (n00 + n01 + n02) % 3 if n0 == 1: return False n1 = (n10 + n11 + n12) % 3 if n1 == 1: return False n2 = (n20 + n21 + n22) % 3 if n2 == 1: return False if ((n0 == 2) + (n1 == 2) + (n2 == 2) + (tiles[27] == 2) + (tiles[28] == 2) + (tiles[29] == 2) + (tiles[30] == 2) + (tiles[31] == 2) + (tiles[32] == 2) + (tiles[33] == 2) != 1): return False nn0 = (n00 * 1 + n01 * 2) % 3 m0 = self._to_meld(tiles, 0) nn1 = (n10 * 1 + n11 * 2) % 3 m1 = self._to_meld(tiles, 9) nn2 = (n20 * 1 + n21 * 2) % 3 m2 = self._to_meld(tiles, 18) if j & 4: return not (n0 | nn0 | n1 | nn1 | n2 | nn2) and self._is_mentsu(m0) \ and self._is_mentsu(m1) and self._is_mentsu(m2) if n0 == 2: return not (n1 | nn1 | n2 | nn2) and self._is_mentsu(m1) and self._is_mentsu(m2) \ and self._is_atama_mentsu(nn0, m0) if n1 == 2: return not (n2 | nn2 | n0 | nn0) and self._is_mentsu(m2) and self._is_mentsu(m0) \ and self._is_atama_mentsu(nn1, m1) if n2 == 2: return not (n0 | nn0 | n1 | nn1) and self._is_mentsu(m0) and self._is_mentsu(m1) \ and self._is_atama_mentsu(nn2, m2) return False
Determine was it win or not :param tiles_34: 34 tiles format array :param open_sets_34: array of array of 34 tiles format :return: boolean
train
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/agari.py#L9-L105
null
class Agari(object): def _is_mentsu(self, m): a = m & 7 b = 0 c = 0 if a == 1 or a == 4: b = c = 1 elif a == 2: b = c = 2 m >>= 3 a = (m & 7) - b if a < 0: return False is_not_mentsu = False for x in range(0, 6): b = c c = 0 if a == 1 or a == 4: b += 1 c += 1 elif a == 2: b += 2 c += 2 m >>= 3 a = (m & 7) - b if a < 0: is_not_mentsu = True break if is_not_mentsu: return False m >>= 3 a = (m & 7) - c return a == 0 or a == 3 def _is_atama_mentsu(self, nn, m): if nn == 0: if (m & (7 << 6)) >= (2 << 6) and self._is_mentsu(m - (2 << 6)): return True if (m & (7 << 15)) >= (2 << 15) and self._is_mentsu(m - (2 << 15)): return True if (m & (7 << 24)) >= (2 << 24) and self._is_mentsu(m - (2 << 24)): return True elif nn == 1: if (m & (7 << 3)) >= (2 << 3) and self._is_mentsu(m - (2 << 3)): return True if (m & (7 << 12)) >= (2 << 12) and self._is_mentsu(m - (2 << 12)): return True if (m & (7 << 21)) >= (2 << 21) and self._is_mentsu(m - (2 << 21)): return True elif nn == 2: if (m & (7 << 0)) >= (2 << 0) and self._is_mentsu(m - (2 << 0)): return True if (m & (7 << 9)) >= (2 << 9) and self._is_mentsu(m - (2 << 9)): return True if (m & (7 << 18)) >= (2 << 18) and self._is_mentsu(m - (2 << 18)): return True return False def _to_meld(self, tiles, d): result = 0 for i in range(0, 9): result |= (tiles[d + i] << i * 3) return result
adamcharnock/django-hordak
hordak/utilities/money.py
ratio_split
python
def ratio_split(amount, ratios): ratio_total = sum(ratios) divided_value = amount / ratio_total values = [] for ratio in ratios: value = divided_value * ratio values.append(value) # Now round the values, keeping track of the bits we cut off rounded = [v.quantize(Decimal("0.01")) for v in values] remainders = [v - rounded[i] for i, v in enumerate(values)] remainder = sum(remainders) # Give the last person the (positive or negative) remainder rounded[-1] = (rounded[-1] + remainder).quantize(Decimal("0.01")) assert sum(rounded) == amount return rounded
Split in_value according to the ratios specified in `ratios` This is special in that it ensures the returned values always sum to in_value (i.e. we avoid losses or gains due to rounding errors). As a result, this method returns a list of `Decimal` values with length equal to that of `ratios`. Examples: .. code-block:: python >>> from hordak.utilities.money import ratio_split >>> from decimal import Decimal >>> ratio_split(Decimal('10'), [Decimal('1'), Decimal('2')]) [Decimal('3.33'), Decimal('6.67')] Note the returned values sum to the original input of ``10``. If we were to do this calculation in a naive fashion then the returned values would likely be ``3.33`` and ``6.66``, which would sum to ``9.99``, thereby loosing ``0.01``. Args: amount (Decimal): The amount to be split ratios (list[Decimal]): The ratios that will determine the split Returns: list(Decimal)
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/utilities/money.py#L4-L49
null
from decimal import Decimal
adamcharnock/django-hordak
hordak/models/statement_csv_import.py
TransactionCsvImport.create_columns
python
def create_columns(self): reader = self._get_csv_reader() headings = six.next(reader) try: examples = six.next(reader) except StopIteration: examples = [] found_fields = set() for i, value in enumerate(headings): if i >= 20: break infer_field = self.has_headings and value not in found_fields to_field = ( { "date": "date", "amount": "amount", "description": "description", "memo": "description", "notes": "description", }.get(value.lower(), "") if infer_field else "" ) if to_field: found_fields.add(to_field) TransactionCsvImportColumn.objects.update_or_create( transaction_import=self, column_number=i + 1, column_heading=value if self.has_headings else "", to_field=to_field, example=examples[i].strip() if examples else "", )
For each column in file create a TransactionCsvImportColumn
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/statement_csv_import.py#L38-L75
[ "def _get_csv_reader(self):\n # TODO: Refactor to support multiple readers (xls, quickbooks, etc)\n csv_buffer = StringIO(self.file.read().decode())\n return csv.reader(csv_buffer)\n" ]
class TransactionCsvImport(models.Model): STATES = Choices( ("pending", "Pending"), ("uploaded", "Uploaded, ready to import"), ("done", "Import complete"), ) uuid = SmallUUIDField(default=uuid_default(), editable=False) timestamp = models.DateTimeField(default=timezone.now, editable=False) has_headings = models.BooleanField( default=True, verbose_name="First line of file contains headings" ) file = models.FileField(upload_to="transaction_imports", verbose_name="CSV file to import") state = models.CharField(max_length=20, choices=STATES, default="pending") date_format = models.CharField( choices=DATE_FORMATS, max_length=50, default="%d-%m-%Y", null=False ) hordak_import = models.ForeignKey("hordak.StatementImport", on_delete=models.CASCADE) def _get_csv_reader(self): # TODO: Refactor to support multiple readers (xls, quickbooks, etc) csv_buffer = StringIO(self.file.read().decode()) return csv.reader(csv_buffer) def get_dataset(self): reader = self._get_csv_reader() if self.has_headings: six.next(reader) data = list(reader) headers = [ column.to_field or "col_%s" % column.column_number for column in self.columns.all() ] return Dataset(*data, headers=headers)
adamcharnock/django-hordak
hordak/resources.py
StatementLineResource._get_num_similar_objects
python
def _get_num_similar_objects(self, obj): return StatementLine.objects.filter( date=obj.date, amount=obj.amount, description=obj.description ).count()
Get any statement lines which would be considered a duplicate of obj
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/resources.py#L74-L78
null
class StatementLineResource(resources.ModelResource): class Meta: model = StatementLine fields = ("date", "amount", "description") def __init__(self, date_format, statement_import): self.date_format = date_format self.statement_import = statement_import @classmethod def get_result_class(self): return Result def before_import(self, dataset, using_transactions, dry_run, **kwargs): def _strip(s): return s.strip() if isinstance(s, str) else s # Remove whitespace for index, values in enumerate(dataset): dataset[index] = tuple(map(_strip, values)) # We're going to need this to check for duplicates (because # there could be multiple identical transactions) self.dataset = dataset similar_totals = [0] * len(self.dataset) for i, row in enumerate(dataset): num_similar = self._get_num_similar_rows(row, until=i) similar_totals[i] = num_similar # Add a new 'similar_total' column. This is a integer of how many # identical rows precede this one. self.dataset.append_col(similar_totals, header="similar_total") def before_save_instance(self, instance, using_transactions, dry_run): # We need to record this statement line against the parent statement import # instance passed to the constructor instance.statement_import = self.statement_import def get_instance(self, instance_loader, row): # We never update, we either create or skip return None def init_instance(self, row=None): # Attach the row to the instance as we'll need it in skip_row() instance = super(StatementLineResource, self).init_instance(row) instance._row = row return instance def skip_row(self, instance, original): # Skip this row if the database already contains the requsite number of # rows identical to this one. return instance._row["similar_total"] < self._get_num_similar_objects(instance) def _get_num_similar_rows(self, row, until=None): """Get the number of rows similar to row which precede the index `until`""" return len(list(filter(lambda r: row == r, self.dataset[:until]))) def import_obj(self, obj, data, dry_run): F = TransactionCsvImportColumn.TO_FIELDS use_dual_amounts = F.amount_out in data and F.amount_in in data if F.date not in data: raise ValueError("No date column found") try: date = datetime.strptime(data[F.date], self.date_format).date() except ValueError: raise ValueError( "Invalid value for date. Expected {}".format(dict(DATE_FORMATS)[self.date_format]) ) description = data[F.description] # Do we have in/out columns, or just one amount column? if use_dual_amounts: amount_out = data[F.amount_out] amount_in = data[F.amount_in] if amount_in and amount_out: raise ValueError("Values found for both Amount In and Amount Out") if not amount_in and not amount_out: raise ValueError("Value required for either Amount In or Amount Out") if amount_out: try: amount = abs(Decimal(amount_out)) * -1 except DecimalException: raise ValueError("Invalid value found for Amount Out") else: try: amount = abs(Decimal(amount_in)) except DecimalException: raise ValueError("Invalid value found for Amount In") else: if F.amount not in data: raise ValueError("No amount column found") if not data[F.amount]: raise ValueError("No value found for amount") try: amount = Decimal(data[F.amount]) except: raise DecimalException("Invalid value found for Amount") if amount == Decimal("0"): raise ValueError("Amount of zero not allowed") data = dict(date=date, amount=amount, description=description) return super(StatementLineResource, self).import_obj(obj, data, dry_run)
adamcharnock/django-hordak
hordak/resources.py
StatementLineResource._get_num_similar_rows
python
def _get_num_similar_rows(self, row, until=None): return len(list(filter(lambda r: row == r, self.dataset[:until])))
Get the number of rows similar to row which precede the index `until`
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/resources.py#L80-L82
null
class StatementLineResource(resources.ModelResource): class Meta: model = StatementLine fields = ("date", "amount", "description") def __init__(self, date_format, statement_import): self.date_format = date_format self.statement_import = statement_import @classmethod def get_result_class(self): return Result def before_import(self, dataset, using_transactions, dry_run, **kwargs): def _strip(s): return s.strip() if isinstance(s, str) else s # Remove whitespace for index, values in enumerate(dataset): dataset[index] = tuple(map(_strip, values)) # We're going to need this to check for duplicates (because # there could be multiple identical transactions) self.dataset = dataset similar_totals = [0] * len(self.dataset) for i, row in enumerate(dataset): num_similar = self._get_num_similar_rows(row, until=i) similar_totals[i] = num_similar # Add a new 'similar_total' column. This is a integer of how many # identical rows precede this one. self.dataset.append_col(similar_totals, header="similar_total") def before_save_instance(self, instance, using_transactions, dry_run): # We need to record this statement line against the parent statement import # instance passed to the constructor instance.statement_import = self.statement_import def get_instance(self, instance_loader, row): # We never update, we either create or skip return None def init_instance(self, row=None): # Attach the row to the instance as we'll need it in skip_row() instance = super(StatementLineResource, self).init_instance(row) instance._row = row return instance def skip_row(self, instance, original): # Skip this row if the database already contains the requsite number of # rows identical to this one. return instance._row["similar_total"] < self._get_num_similar_objects(instance) def _get_num_similar_objects(self, obj): """Get any statement lines which would be considered a duplicate of obj""" return StatementLine.objects.filter( date=obj.date, amount=obj.amount, description=obj.description ).count() def import_obj(self, obj, data, dry_run): F = TransactionCsvImportColumn.TO_FIELDS use_dual_amounts = F.amount_out in data and F.amount_in in data if F.date not in data: raise ValueError("No date column found") try: date = datetime.strptime(data[F.date], self.date_format).date() except ValueError: raise ValueError( "Invalid value for date. Expected {}".format(dict(DATE_FORMATS)[self.date_format]) ) description = data[F.description] # Do we have in/out columns, or just one amount column? if use_dual_amounts: amount_out = data[F.amount_out] amount_in = data[F.amount_in] if amount_in and amount_out: raise ValueError("Values found for both Amount In and Amount Out") if not amount_in and not amount_out: raise ValueError("Value required for either Amount In or Amount Out") if amount_out: try: amount = abs(Decimal(amount_out)) * -1 except DecimalException: raise ValueError("Invalid value found for Amount Out") else: try: amount = abs(Decimal(amount_in)) except DecimalException: raise ValueError("Invalid value found for Amount In") else: if F.amount not in data: raise ValueError("No amount column found") if not data[F.amount]: raise ValueError("No value found for amount") try: amount = Decimal(data[F.amount]) except: raise DecimalException("Invalid value found for Amount") if amount == Decimal("0"): raise ValueError("Amount of zero not allowed") data = dict(date=date, amount=amount, description=description) return super(StatementLineResource, self).import_obj(obj, data, dry_run)
adamcharnock/django-hordak
hordak/data_sources/tellerio.py
do_import
python
def do_import(token, account_uuid, bank_account, since=None): response = requests.get( url="https://api.teller.io/accounts/{}/transactions".format(account_uuid), headers={"Authorization": "Bearer {}".format(token)}, ) response.raise_for_status() data = response.json() statement_import = StatementImport.objects.create( source="teller.io", extra={"account_uuid": account_uuid}, bank_account=bank_account ) for line_data in data: uuid = UUID(hex=line_data["id"]) if StatementLine.objects.filter(uuid=uuid): continue description = ", ".join(filter(bool, [line_data["counterparty"], line_data["description"]])) date = datetime.date(*map(int, line_data["date"].split("-"))) if not since or date >= since: StatementLine.objects.create( uuid=uuid, date=line_data["date"], statement_import=statement_import, amount=line_data["amount"], type=line_data["type"], description=description, source_data=line_data, )
Import data from teller.io Returns the created StatementImport
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/data_sources/tellerio.py#L11-L44
null
from uuid import UUID import datetime import requests from django.db import transaction from hordak.models.core import StatementImport, StatementLine @transaction.atomic()
adamcharnock/django-hordak
hordak/models/core.py
Account.validate_accounting_equation
python
def validate_accounting_equation(cls): balances = [account.balance(raw=True) for account in Account.objects.root_nodes()] if sum(balances, Balance()) != 0: raise exceptions.AccountingEquationViolationError( "Account balances do not sum to zero. They sum to {}".format(sum(balances)) )
Check that all accounts sum to 0
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L149-L155
null
class Account(MPTTModel): """ Represents an account An account may have a parent, and may have zero or more children. Only root accounts can have a type, all child accounts are assumed to have the same type as their parent. An account's balance is calculated as the sum of all of the transaction Leg's referencing the account. Attributes: uuid (SmallUUID): UUID for account. Use to prevent leaking of IDs (if desired). name (str): Name of the account. Required. parent (Account|None): Parent account, nonen if root account code (str): Account code. Must combine with account codes of parent accounts to get fully qualified account code. type (str): Type of account as defined by :attr:`Account.TYPES`. Can only be set on root accounts. Child accounts are assumed to have the same time as their parent. TYPES (Choices): Available account types. Uses ``Choices`` from ``django-model-utils``. Types can be accessed in the form ``Account.TYPES.asset``, ``Account.TYPES.expense``, etc. is_bank_account (bool): Is this a bank account. This implies we can import bank statements into it and that it only supports a single currency. """ TYPES = Choices( ("AS", "asset", "Asset"), # Eg. Cash in bank ("LI", "liability", "Liability"), # Eg. Loans, bills paid after the fact (in arrears) ("IN", "income", "Income"), # Eg. Sales, housemate contributions ("EX", "expense", "Expense"), # Eg. Office supplies, paying bills ("EQ", "equity", "Equity"), # Eg. Money from shares ("TR", "trading", "Currency Trading"), # Used to represent currency conversions ) uuid = SmallUUIDField(default=uuid_default(), editable=False) name = models.CharField(max_length=50) parent = TreeForeignKey( "self", null=True, blank=True, related_name="children", db_index=True, on_delete=models.CASCADE, ) code = models.CharField(max_length=3, null=True, blank=True) full_code = models.CharField(max_length=100, db_index=True, unique=True, null=True, blank=True) # TODO: Implement this child_code_width field, as it is probably a good idea # child_code_width = models.PositiveSmallIntegerField(default=1) type = models.CharField(max_length=2, choices=TYPES, blank=True) is_bank_account = models.BooleanField( default=False, blank=True, help_text="Is this a bank account. This implies we can import bank " "statements into it and that it only supports a single currency", ) currencies = ArrayField(models.CharField(max_length=3), db_index=True) objects = AccountManager.from_queryset(AccountQuerySet)() class MPTTMeta: order_insertion_by = ["code"] class Meta: unique_together = (("parent", "code"),) def __init__(self, *args, **kwargs): super(Account, self).__init__(*args, **kwargs) self._initial_code = self.code def save(self, *args, **kwargs): is_creating = not bool(self.pk) super(Account, self).save(*args, **kwargs) do_refresh = False # If we've just created a non-root node then we're going to need to load # the type back from the DB (as it is set by trigger) if is_creating and not self.is_root_node(): do_refresh = True # If we've just create this account or if the code has changed then we're # going to need to reload from the DB (full_code is set by trigger) if is_creating or self._initial_code != self.code: do_refresh = True if do_refresh: self.refresh_from_db() @classmethod def __str__(self): name = self.name or "Unnamed Account" if self.is_leaf_node(): try: balance = self.balance() except ValueError: if self.full_code: return "{} {}".format(self.full_code, name) else: return name else: if self.full_code: return "{} {} [{}]".format(self.full_code, name, balance) else: return "{} [{}]".format(name, balance) else: return name def natural_key(self): return (self.uuid,) @property def sign(self): """ Returns 1 if a credit should increase the value of the account, or -1 if a credit should decrease the value of the account. This is based on the account type as is standard accounting practice. The signs can be derrived from the following expanded form of the accounting equation: Assets = Liabilities + Equity + (Income - Expenses) Which can be rearranged as: 0 = Liabilities + Equity + Income - Expenses - Assets Further details here: https://en.wikipedia.org/wiki/Debits_and_credits """ return -1 if self.type in (Account.TYPES.asset, Account.TYPES.expense) else 1 def balance(self, as_of=None, raw=False, leg_query=None, **kwargs): """Get the balance for this account, including child accounts Args: as_of (Date): Only include transactions on or before this date raw (bool): If true the returned balance should not have its sign adjusted for display purposes. kwargs (dict): Will be used to filter the transaction legs Returns: Balance See Also: :meth:`simple_balance()` """ balances = [ account.simple_balance(as_of=as_of, raw=raw, leg_query=leg_query, **kwargs) for account in self.get_descendants(include_self=True) ] return sum(balances, Balance()) def simple_balance(self, as_of=None, raw=False, leg_query=None, **kwargs): """Get the balance for this account, ignoring all child accounts Args: as_of (Date): Only include transactions on or before this date raw (bool): If true the returned balance should not have its sign adjusted for display purposes. leg_query (models.Q): Django Q-expression, will be used to filter the transaction legs. allows for more complex filtering than that provided by **kwargs. kwargs (dict): Will be used to filter the transaction legs Returns: Balance """ legs = self.legs if as_of: legs = legs.filter(transaction__date__lte=as_of) if leg_query or kwargs: leg_query = leg_query or models.Q() legs = legs.filter(leg_query, **kwargs) return legs.sum_to_balance() * (1 if raw else self.sign) + self._zero_balance() def _zero_balance(self): """Get a balance for this account with all currencies set to zero""" return Balance([Money("0", currency) for currency in self.currencies]) @db_transaction.atomic() def transfer_to(self, to_account, amount, **transaction_kwargs): """Create a transaction which transfers amount to to_account This is a shortcut utility method which simplifies the process of transferring between accounts. This method attempts to perform the transaction in an intuitive manner. For example: * Transferring income -> income will result in the former decreasing and the latter increasing * Transferring asset (i.e. bank) -> income will result in the balance of both increasing * Transferring asset -> asset will result in the former decreasing and the latter increasing .. note:: Transfers in any direction between ``{asset | expense} <-> {income | liability | equity}`` will always result in both balances increasing. This may change in future if it is found to be unhelpful. Transfers to trading accounts will always behave as normal. Args: to_account (Account): The destination account. amount (Money): The amount to be transferred. transaction_kwargs: Passed through to transaction creation. Useful for setting the transaction `description` field. """ if not isinstance(amount, Money): raise TypeError("amount must be of type Money") if to_account.sign == 1 and to_account.type != self.TYPES.trading: # Transferring from two positive-signed accounts implies that # the caller wants to reduce the first account and increase the second # (which is opposite to the implicit behaviour) direction = -1 elif self.type == self.TYPES.liability and to_account.type == self.TYPES.expense: # Transfers from liability -> asset accounts should reduce both. # For example, moving money from Rent Payable (liability) to your Rent (expense) account # should use the funds you've built up in the liability account to pay off the expense account. direction = -1 else: direction = 1 transaction = Transaction.objects.create(**transaction_kwargs) Leg.objects.create(transaction=transaction, account=self, amount=+amount * direction) Leg.objects.create(transaction=transaction, account=to_account, amount=-amount * direction) return transaction
adamcharnock/django-hordak
hordak/models/core.py
Account.sign
python
def sign(self): return -1 if self.type in (Account.TYPES.asset, Account.TYPES.expense) else 1
Returns 1 if a credit should increase the value of the account, or -1 if a credit should decrease the value of the account. This is based on the account type as is standard accounting practice. The signs can be derrived from the following expanded form of the accounting equation: Assets = Liabilities + Equity + (Income - Expenses) Which can be rearranged as: 0 = Liabilities + Equity + Income - Expenses - Assets Further details here: https://en.wikipedia.org/wiki/Debits_and_credits
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L180-L199
null
class Account(MPTTModel): """ Represents an account An account may have a parent, and may have zero or more children. Only root accounts can have a type, all child accounts are assumed to have the same type as their parent. An account's balance is calculated as the sum of all of the transaction Leg's referencing the account. Attributes: uuid (SmallUUID): UUID for account. Use to prevent leaking of IDs (if desired). name (str): Name of the account. Required. parent (Account|None): Parent account, nonen if root account code (str): Account code. Must combine with account codes of parent accounts to get fully qualified account code. type (str): Type of account as defined by :attr:`Account.TYPES`. Can only be set on root accounts. Child accounts are assumed to have the same time as their parent. TYPES (Choices): Available account types. Uses ``Choices`` from ``django-model-utils``. Types can be accessed in the form ``Account.TYPES.asset``, ``Account.TYPES.expense``, etc. is_bank_account (bool): Is this a bank account. This implies we can import bank statements into it and that it only supports a single currency. """ TYPES = Choices( ("AS", "asset", "Asset"), # Eg. Cash in bank ("LI", "liability", "Liability"), # Eg. Loans, bills paid after the fact (in arrears) ("IN", "income", "Income"), # Eg. Sales, housemate contributions ("EX", "expense", "Expense"), # Eg. Office supplies, paying bills ("EQ", "equity", "Equity"), # Eg. Money from shares ("TR", "trading", "Currency Trading"), # Used to represent currency conversions ) uuid = SmallUUIDField(default=uuid_default(), editable=False) name = models.CharField(max_length=50) parent = TreeForeignKey( "self", null=True, blank=True, related_name="children", db_index=True, on_delete=models.CASCADE, ) code = models.CharField(max_length=3, null=True, blank=True) full_code = models.CharField(max_length=100, db_index=True, unique=True, null=True, blank=True) # TODO: Implement this child_code_width field, as it is probably a good idea # child_code_width = models.PositiveSmallIntegerField(default=1) type = models.CharField(max_length=2, choices=TYPES, blank=True) is_bank_account = models.BooleanField( default=False, blank=True, help_text="Is this a bank account. This implies we can import bank " "statements into it and that it only supports a single currency", ) currencies = ArrayField(models.CharField(max_length=3), db_index=True) objects = AccountManager.from_queryset(AccountQuerySet)() class MPTTMeta: order_insertion_by = ["code"] class Meta: unique_together = (("parent", "code"),) def __init__(self, *args, **kwargs): super(Account, self).__init__(*args, **kwargs) self._initial_code = self.code def save(self, *args, **kwargs): is_creating = not bool(self.pk) super(Account, self).save(*args, **kwargs) do_refresh = False # If we've just created a non-root node then we're going to need to load # the type back from the DB (as it is set by trigger) if is_creating and not self.is_root_node(): do_refresh = True # If we've just create this account or if the code has changed then we're # going to need to reload from the DB (full_code is set by trigger) if is_creating or self._initial_code != self.code: do_refresh = True if do_refresh: self.refresh_from_db() @classmethod def validate_accounting_equation(cls): """Check that all accounts sum to 0""" balances = [account.balance(raw=True) for account in Account.objects.root_nodes()] if sum(balances, Balance()) != 0: raise exceptions.AccountingEquationViolationError( "Account balances do not sum to zero. They sum to {}".format(sum(balances)) ) def __str__(self): name = self.name or "Unnamed Account" if self.is_leaf_node(): try: balance = self.balance() except ValueError: if self.full_code: return "{} {}".format(self.full_code, name) else: return name else: if self.full_code: return "{} {} [{}]".format(self.full_code, name, balance) else: return "{} [{}]".format(name, balance) else: return name def natural_key(self): return (self.uuid,) @property def balance(self, as_of=None, raw=False, leg_query=None, **kwargs): """Get the balance for this account, including child accounts Args: as_of (Date): Only include transactions on or before this date raw (bool): If true the returned balance should not have its sign adjusted for display purposes. kwargs (dict): Will be used to filter the transaction legs Returns: Balance See Also: :meth:`simple_balance()` """ balances = [ account.simple_balance(as_of=as_of, raw=raw, leg_query=leg_query, **kwargs) for account in self.get_descendants(include_self=True) ] return sum(balances, Balance()) def simple_balance(self, as_of=None, raw=False, leg_query=None, **kwargs): """Get the balance for this account, ignoring all child accounts Args: as_of (Date): Only include transactions on or before this date raw (bool): If true the returned balance should not have its sign adjusted for display purposes. leg_query (models.Q): Django Q-expression, will be used to filter the transaction legs. allows for more complex filtering than that provided by **kwargs. kwargs (dict): Will be used to filter the transaction legs Returns: Balance """ legs = self.legs if as_of: legs = legs.filter(transaction__date__lte=as_of) if leg_query or kwargs: leg_query = leg_query or models.Q() legs = legs.filter(leg_query, **kwargs) return legs.sum_to_balance() * (1 if raw else self.sign) + self._zero_balance() def _zero_balance(self): """Get a balance for this account with all currencies set to zero""" return Balance([Money("0", currency) for currency in self.currencies]) @db_transaction.atomic() def transfer_to(self, to_account, amount, **transaction_kwargs): """Create a transaction which transfers amount to to_account This is a shortcut utility method which simplifies the process of transferring between accounts. This method attempts to perform the transaction in an intuitive manner. For example: * Transferring income -> income will result in the former decreasing and the latter increasing * Transferring asset (i.e. bank) -> income will result in the balance of both increasing * Transferring asset -> asset will result in the former decreasing and the latter increasing .. note:: Transfers in any direction between ``{asset | expense} <-> {income | liability | equity}`` will always result in both balances increasing. This may change in future if it is found to be unhelpful. Transfers to trading accounts will always behave as normal. Args: to_account (Account): The destination account. amount (Money): The amount to be transferred. transaction_kwargs: Passed through to transaction creation. Useful for setting the transaction `description` field. """ if not isinstance(amount, Money): raise TypeError("amount must be of type Money") if to_account.sign == 1 and to_account.type != self.TYPES.trading: # Transferring from two positive-signed accounts implies that # the caller wants to reduce the first account and increase the second # (which is opposite to the implicit behaviour) direction = -1 elif self.type == self.TYPES.liability and to_account.type == self.TYPES.expense: # Transfers from liability -> asset accounts should reduce both. # For example, moving money from Rent Payable (liability) to your Rent (expense) account # should use the funds you've built up in the liability account to pay off the expense account. direction = -1 else: direction = 1 transaction = Transaction.objects.create(**transaction_kwargs) Leg.objects.create(transaction=transaction, account=self, amount=+amount * direction) Leg.objects.create(transaction=transaction, account=to_account, amount=-amount * direction) return transaction
adamcharnock/django-hordak
hordak/models/core.py
Account.balance
python
def balance(self, as_of=None, raw=False, leg_query=None, **kwargs): balances = [ account.simple_balance(as_of=as_of, raw=raw, leg_query=leg_query, **kwargs) for account in self.get_descendants(include_self=True) ] return sum(balances, Balance())
Get the balance for this account, including child accounts Args: as_of (Date): Only include transactions on or before this date raw (bool): If true the returned balance should not have its sign adjusted for display purposes. kwargs (dict): Will be used to filter the transaction legs Returns: Balance See Also: :meth:`simple_balance()`
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L201-L220
null
class Account(MPTTModel): """ Represents an account An account may have a parent, and may have zero or more children. Only root accounts can have a type, all child accounts are assumed to have the same type as their parent. An account's balance is calculated as the sum of all of the transaction Leg's referencing the account. Attributes: uuid (SmallUUID): UUID for account. Use to prevent leaking of IDs (if desired). name (str): Name of the account. Required. parent (Account|None): Parent account, nonen if root account code (str): Account code. Must combine with account codes of parent accounts to get fully qualified account code. type (str): Type of account as defined by :attr:`Account.TYPES`. Can only be set on root accounts. Child accounts are assumed to have the same time as their parent. TYPES (Choices): Available account types. Uses ``Choices`` from ``django-model-utils``. Types can be accessed in the form ``Account.TYPES.asset``, ``Account.TYPES.expense``, etc. is_bank_account (bool): Is this a bank account. This implies we can import bank statements into it and that it only supports a single currency. """ TYPES = Choices( ("AS", "asset", "Asset"), # Eg. Cash in bank ("LI", "liability", "Liability"), # Eg. Loans, bills paid after the fact (in arrears) ("IN", "income", "Income"), # Eg. Sales, housemate contributions ("EX", "expense", "Expense"), # Eg. Office supplies, paying bills ("EQ", "equity", "Equity"), # Eg. Money from shares ("TR", "trading", "Currency Trading"), # Used to represent currency conversions ) uuid = SmallUUIDField(default=uuid_default(), editable=False) name = models.CharField(max_length=50) parent = TreeForeignKey( "self", null=True, blank=True, related_name="children", db_index=True, on_delete=models.CASCADE, ) code = models.CharField(max_length=3, null=True, blank=True) full_code = models.CharField(max_length=100, db_index=True, unique=True, null=True, blank=True) # TODO: Implement this child_code_width field, as it is probably a good idea # child_code_width = models.PositiveSmallIntegerField(default=1) type = models.CharField(max_length=2, choices=TYPES, blank=True) is_bank_account = models.BooleanField( default=False, blank=True, help_text="Is this a bank account. This implies we can import bank " "statements into it and that it only supports a single currency", ) currencies = ArrayField(models.CharField(max_length=3), db_index=True) objects = AccountManager.from_queryset(AccountQuerySet)() class MPTTMeta: order_insertion_by = ["code"] class Meta: unique_together = (("parent", "code"),) def __init__(self, *args, **kwargs): super(Account, self).__init__(*args, **kwargs) self._initial_code = self.code def save(self, *args, **kwargs): is_creating = not bool(self.pk) super(Account, self).save(*args, **kwargs) do_refresh = False # If we've just created a non-root node then we're going to need to load # the type back from the DB (as it is set by trigger) if is_creating and not self.is_root_node(): do_refresh = True # If we've just create this account or if the code has changed then we're # going to need to reload from the DB (full_code is set by trigger) if is_creating or self._initial_code != self.code: do_refresh = True if do_refresh: self.refresh_from_db() @classmethod def validate_accounting_equation(cls): """Check that all accounts sum to 0""" balances = [account.balance(raw=True) for account in Account.objects.root_nodes()] if sum(balances, Balance()) != 0: raise exceptions.AccountingEquationViolationError( "Account balances do not sum to zero. They sum to {}".format(sum(balances)) ) def __str__(self): name = self.name or "Unnamed Account" if self.is_leaf_node(): try: balance = self.balance() except ValueError: if self.full_code: return "{} {}".format(self.full_code, name) else: return name else: if self.full_code: return "{} {} [{}]".format(self.full_code, name, balance) else: return "{} [{}]".format(name, balance) else: return name def natural_key(self): return (self.uuid,) @property def sign(self): """ Returns 1 if a credit should increase the value of the account, or -1 if a credit should decrease the value of the account. This is based on the account type as is standard accounting practice. The signs can be derrived from the following expanded form of the accounting equation: Assets = Liabilities + Equity + (Income - Expenses) Which can be rearranged as: 0 = Liabilities + Equity + Income - Expenses - Assets Further details here: https://en.wikipedia.org/wiki/Debits_and_credits """ return -1 if self.type in (Account.TYPES.asset, Account.TYPES.expense) else 1 def simple_balance(self, as_of=None, raw=False, leg_query=None, **kwargs): """Get the balance for this account, ignoring all child accounts Args: as_of (Date): Only include transactions on or before this date raw (bool): If true the returned balance should not have its sign adjusted for display purposes. leg_query (models.Q): Django Q-expression, will be used to filter the transaction legs. allows for more complex filtering than that provided by **kwargs. kwargs (dict): Will be used to filter the transaction legs Returns: Balance """ legs = self.legs if as_of: legs = legs.filter(transaction__date__lte=as_of) if leg_query or kwargs: leg_query = leg_query or models.Q() legs = legs.filter(leg_query, **kwargs) return legs.sum_to_balance() * (1 if raw else self.sign) + self._zero_balance() def _zero_balance(self): """Get a balance for this account with all currencies set to zero""" return Balance([Money("0", currency) for currency in self.currencies]) @db_transaction.atomic() def transfer_to(self, to_account, amount, **transaction_kwargs): """Create a transaction which transfers amount to to_account This is a shortcut utility method which simplifies the process of transferring between accounts. This method attempts to perform the transaction in an intuitive manner. For example: * Transferring income -> income will result in the former decreasing and the latter increasing * Transferring asset (i.e. bank) -> income will result in the balance of both increasing * Transferring asset -> asset will result in the former decreasing and the latter increasing .. note:: Transfers in any direction between ``{asset | expense} <-> {income | liability | equity}`` will always result in both balances increasing. This may change in future if it is found to be unhelpful. Transfers to trading accounts will always behave as normal. Args: to_account (Account): The destination account. amount (Money): The amount to be transferred. transaction_kwargs: Passed through to transaction creation. Useful for setting the transaction `description` field. """ if not isinstance(amount, Money): raise TypeError("amount must be of type Money") if to_account.sign == 1 and to_account.type != self.TYPES.trading: # Transferring from two positive-signed accounts implies that # the caller wants to reduce the first account and increase the second # (which is opposite to the implicit behaviour) direction = -1 elif self.type == self.TYPES.liability and to_account.type == self.TYPES.expense: # Transfers from liability -> asset accounts should reduce both. # For example, moving money from Rent Payable (liability) to your Rent (expense) account # should use the funds you've built up in the liability account to pay off the expense account. direction = -1 else: direction = 1 transaction = Transaction.objects.create(**transaction_kwargs) Leg.objects.create(transaction=transaction, account=self, amount=+amount * direction) Leg.objects.create(transaction=transaction, account=to_account, amount=-amount * direction) return transaction
adamcharnock/django-hordak
hordak/models/core.py
Account.simple_balance
python
def simple_balance(self, as_of=None, raw=False, leg_query=None, **kwargs): legs = self.legs if as_of: legs = legs.filter(transaction__date__lte=as_of) if leg_query or kwargs: leg_query = leg_query or models.Q() legs = legs.filter(leg_query, **kwargs) return legs.sum_to_balance() * (1 if raw else self.sign) + self._zero_balance()
Get the balance for this account, ignoring all child accounts Args: as_of (Date): Only include transactions on or before this date raw (bool): If true the returned balance should not have its sign adjusted for display purposes. leg_query (models.Q): Django Q-expression, will be used to filter the transaction legs. allows for more complex filtering than that provided by **kwargs. kwargs (dict): Will be used to filter the transaction legs Returns: Balance
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L222-L244
null
class Account(MPTTModel): """ Represents an account An account may have a parent, and may have zero or more children. Only root accounts can have a type, all child accounts are assumed to have the same type as their parent. An account's balance is calculated as the sum of all of the transaction Leg's referencing the account. Attributes: uuid (SmallUUID): UUID for account. Use to prevent leaking of IDs (if desired). name (str): Name of the account. Required. parent (Account|None): Parent account, nonen if root account code (str): Account code. Must combine with account codes of parent accounts to get fully qualified account code. type (str): Type of account as defined by :attr:`Account.TYPES`. Can only be set on root accounts. Child accounts are assumed to have the same time as their parent. TYPES (Choices): Available account types. Uses ``Choices`` from ``django-model-utils``. Types can be accessed in the form ``Account.TYPES.asset``, ``Account.TYPES.expense``, etc. is_bank_account (bool): Is this a bank account. This implies we can import bank statements into it and that it only supports a single currency. """ TYPES = Choices( ("AS", "asset", "Asset"), # Eg. Cash in bank ("LI", "liability", "Liability"), # Eg. Loans, bills paid after the fact (in arrears) ("IN", "income", "Income"), # Eg. Sales, housemate contributions ("EX", "expense", "Expense"), # Eg. Office supplies, paying bills ("EQ", "equity", "Equity"), # Eg. Money from shares ("TR", "trading", "Currency Trading"), # Used to represent currency conversions ) uuid = SmallUUIDField(default=uuid_default(), editable=False) name = models.CharField(max_length=50) parent = TreeForeignKey( "self", null=True, blank=True, related_name="children", db_index=True, on_delete=models.CASCADE, ) code = models.CharField(max_length=3, null=True, blank=True) full_code = models.CharField(max_length=100, db_index=True, unique=True, null=True, blank=True) # TODO: Implement this child_code_width field, as it is probably a good idea # child_code_width = models.PositiveSmallIntegerField(default=1) type = models.CharField(max_length=2, choices=TYPES, blank=True) is_bank_account = models.BooleanField( default=False, blank=True, help_text="Is this a bank account. This implies we can import bank " "statements into it and that it only supports a single currency", ) currencies = ArrayField(models.CharField(max_length=3), db_index=True) objects = AccountManager.from_queryset(AccountQuerySet)() class MPTTMeta: order_insertion_by = ["code"] class Meta: unique_together = (("parent", "code"),) def __init__(self, *args, **kwargs): super(Account, self).__init__(*args, **kwargs) self._initial_code = self.code def save(self, *args, **kwargs): is_creating = not bool(self.pk) super(Account, self).save(*args, **kwargs) do_refresh = False # If we've just created a non-root node then we're going to need to load # the type back from the DB (as it is set by trigger) if is_creating and not self.is_root_node(): do_refresh = True # If we've just create this account or if the code has changed then we're # going to need to reload from the DB (full_code is set by trigger) if is_creating or self._initial_code != self.code: do_refresh = True if do_refresh: self.refresh_from_db() @classmethod def validate_accounting_equation(cls): """Check that all accounts sum to 0""" balances = [account.balance(raw=True) for account in Account.objects.root_nodes()] if sum(balances, Balance()) != 0: raise exceptions.AccountingEquationViolationError( "Account balances do not sum to zero. They sum to {}".format(sum(balances)) ) def __str__(self): name = self.name or "Unnamed Account" if self.is_leaf_node(): try: balance = self.balance() except ValueError: if self.full_code: return "{} {}".format(self.full_code, name) else: return name else: if self.full_code: return "{} {} [{}]".format(self.full_code, name, balance) else: return "{} [{}]".format(name, balance) else: return name def natural_key(self): return (self.uuid,) @property def sign(self): """ Returns 1 if a credit should increase the value of the account, or -1 if a credit should decrease the value of the account. This is based on the account type as is standard accounting practice. The signs can be derrived from the following expanded form of the accounting equation: Assets = Liabilities + Equity + (Income - Expenses) Which can be rearranged as: 0 = Liabilities + Equity + Income - Expenses - Assets Further details here: https://en.wikipedia.org/wiki/Debits_and_credits """ return -1 if self.type in (Account.TYPES.asset, Account.TYPES.expense) else 1 def balance(self, as_of=None, raw=False, leg_query=None, **kwargs): """Get the balance for this account, including child accounts Args: as_of (Date): Only include transactions on or before this date raw (bool): If true the returned balance should not have its sign adjusted for display purposes. kwargs (dict): Will be used to filter the transaction legs Returns: Balance See Also: :meth:`simple_balance()` """ balances = [ account.simple_balance(as_of=as_of, raw=raw, leg_query=leg_query, **kwargs) for account in self.get_descendants(include_self=True) ] return sum(balances, Balance()) def _zero_balance(self): """Get a balance for this account with all currencies set to zero""" return Balance([Money("0", currency) for currency in self.currencies]) @db_transaction.atomic() def transfer_to(self, to_account, amount, **transaction_kwargs): """Create a transaction which transfers amount to to_account This is a shortcut utility method which simplifies the process of transferring between accounts. This method attempts to perform the transaction in an intuitive manner. For example: * Transferring income -> income will result in the former decreasing and the latter increasing * Transferring asset (i.e. bank) -> income will result in the balance of both increasing * Transferring asset -> asset will result in the former decreasing and the latter increasing .. note:: Transfers in any direction between ``{asset | expense} <-> {income | liability | equity}`` will always result in both balances increasing. This may change in future if it is found to be unhelpful. Transfers to trading accounts will always behave as normal. Args: to_account (Account): The destination account. amount (Money): The amount to be transferred. transaction_kwargs: Passed through to transaction creation. Useful for setting the transaction `description` field. """ if not isinstance(amount, Money): raise TypeError("amount must be of type Money") if to_account.sign == 1 and to_account.type != self.TYPES.trading: # Transferring from two positive-signed accounts implies that # the caller wants to reduce the first account and increase the second # (which is opposite to the implicit behaviour) direction = -1 elif self.type == self.TYPES.liability and to_account.type == self.TYPES.expense: # Transfers from liability -> asset accounts should reduce both. # For example, moving money from Rent Payable (liability) to your Rent (expense) account # should use the funds you've built up in the liability account to pay off the expense account. direction = -1 else: direction = 1 transaction = Transaction.objects.create(**transaction_kwargs) Leg.objects.create(transaction=transaction, account=self, amount=+amount * direction) Leg.objects.create(transaction=transaction, account=to_account, amount=-amount * direction) return transaction
adamcharnock/django-hordak
hordak/models/core.py
Account.transfer_to
python
def transfer_to(self, to_account, amount, **transaction_kwargs): if not isinstance(amount, Money): raise TypeError("amount must be of type Money") if to_account.sign == 1 and to_account.type != self.TYPES.trading: # Transferring from two positive-signed accounts implies that # the caller wants to reduce the first account and increase the second # (which is opposite to the implicit behaviour) direction = -1 elif self.type == self.TYPES.liability and to_account.type == self.TYPES.expense: # Transfers from liability -> asset accounts should reduce both. # For example, moving money from Rent Payable (liability) to your Rent (expense) account # should use the funds you've built up in the liability account to pay off the expense account. direction = -1 else: direction = 1 transaction = Transaction.objects.create(**transaction_kwargs) Leg.objects.create(transaction=transaction, account=self, amount=+amount * direction) Leg.objects.create(transaction=transaction, account=to_account, amount=-amount * direction) return transaction
Create a transaction which transfers amount to to_account This is a shortcut utility method which simplifies the process of transferring between accounts. This method attempts to perform the transaction in an intuitive manner. For example: * Transferring income -> income will result in the former decreasing and the latter increasing * Transferring asset (i.e. bank) -> income will result in the balance of both increasing * Transferring asset -> asset will result in the former decreasing and the latter increasing .. note:: Transfers in any direction between ``{asset | expense} <-> {income | liability | equity}`` will always result in both balances increasing. This may change in future if it is found to be unhelpful. Transfers to trading accounts will always behave as normal. Args: to_account (Account): The destination account. amount (Money): The amount to be transferred. transaction_kwargs: Passed through to transaction creation. Useful for setting the transaction `description` field.
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L251-L298
null
class Account(MPTTModel): """ Represents an account An account may have a parent, and may have zero or more children. Only root accounts can have a type, all child accounts are assumed to have the same type as their parent. An account's balance is calculated as the sum of all of the transaction Leg's referencing the account. Attributes: uuid (SmallUUID): UUID for account. Use to prevent leaking of IDs (if desired). name (str): Name of the account. Required. parent (Account|None): Parent account, nonen if root account code (str): Account code. Must combine with account codes of parent accounts to get fully qualified account code. type (str): Type of account as defined by :attr:`Account.TYPES`. Can only be set on root accounts. Child accounts are assumed to have the same time as their parent. TYPES (Choices): Available account types. Uses ``Choices`` from ``django-model-utils``. Types can be accessed in the form ``Account.TYPES.asset``, ``Account.TYPES.expense``, etc. is_bank_account (bool): Is this a bank account. This implies we can import bank statements into it and that it only supports a single currency. """ TYPES = Choices( ("AS", "asset", "Asset"), # Eg. Cash in bank ("LI", "liability", "Liability"), # Eg. Loans, bills paid after the fact (in arrears) ("IN", "income", "Income"), # Eg. Sales, housemate contributions ("EX", "expense", "Expense"), # Eg. Office supplies, paying bills ("EQ", "equity", "Equity"), # Eg. Money from shares ("TR", "trading", "Currency Trading"), # Used to represent currency conversions ) uuid = SmallUUIDField(default=uuid_default(), editable=False) name = models.CharField(max_length=50) parent = TreeForeignKey( "self", null=True, blank=True, related_name="children", db_index=True, on_delete=models.CASCADE, ) code = models.CharField(max_length=3, null=True, blank=True) full_code = models.CharField(max_length=100, db_index=True, unique=True, null=True, blank=True) # TODO: Implement this child_code_width field, as it is probably a good idea # child_code_width = models.PositiveSmallIntegerField(default=1) type = models.CharField(max_length=2, choices=TYPES, blank=True) is_bank_account = models.BooleanField( default=False, blank=True, help_text="Is this a bank account. This implies we can import bank " "statements into it and that it only supports a single currency", ) currencies = ArrayField(models.CharField(max_length=3), db_index=True) objects = AccountManager.from_queryset(AccountQuerySet)() class MPTTMeta: order_insertion_by = ["code"] class Meta: unique_together = (("parent", "code"),) def __init__(self, *args, **kwargs): super(Account, self).__init__(*args, **kwargs) self._initial_code = self.code def save(self, *args, **kwargs): is_creating = not bool(self.pk) super(Account, self).save(*args, **kwargs) do_refresh = False # If we've just created a non-root node then we're going to need to load # the type back from the DB (as it is set by trigger) if is_creating and not self.is_root_node(): do_refresh = True # If we've just create this account or if the code has changed then we're # going to need to reload from the DB (full_code is set by trigger) if is_creating or self._initial_code != self.code: do_refresh = True if do_refresh: self.refresh_from_db() @classmethod def validate_accounting_equation(cls): """Check that all accounts sum to 0""" balances = [account.balance(raw=True) for account in Account.objects.root_nodes()] if sum(balances, Balance()) != 0: raise exceptions.AccountingEquationViolationError( "Account balances do not sum to zero. They sum to {}".format(sum(balances)) ) def __str__(self): name = self.name or "Unnamed Account" if self.is_leaf_node(): try: balance = self.balance() except ValueError: if self.full_code: return "{} {}".format(self.full_code, name) else: return name else: if self.full_code: return "{} {} [{}]".format(self.full_code, name, balance) else: return "{} [{}]".format(name, balance) else: return name def natural_key(self): return (self.uuid,) @property def sign(self): """ Returns 1 if a credit should increase the value of the account, or -1 if a credit should decrease the value of the account. This is based on the account type as is standard accounting practice. The signs can be derrived from the following expanded form of the accounting equation: Assets = Liabilities + Equity + (Income - Expenses) Which can be rearranged as: 0 = Liabilities + Equity + Income - Expenses - Assets Further details here: https://en.wikipedia.org/wiki/Debits_and_credits """ return -1 if self.type in (Account.TYPES.asset, Account.TYPES.expense) else 1 def balance(self, as_of=None, raw=False, leg_query=None, **kwargs): """Get the balance for this account, including child accounts Args: as_of (Date): Only include transactions on or before this date raw (bool): If true the returned balance should not have its sign adjusted for display purposes. kwargs (dict): Will be used to filter the transaction legs Returns: Balance See Also: :meth:`simple_balance()` """ balances = [ account.simple_balance(as_of=as_of, raw=raw, leg_query=leg_query, **kwargs) for account in self.get_descendants(include_self=True) ] return sum(balances, Balance()) def simple_balance(self, as_of=None, raw=False, leg_query=None, **kwargs): """Get the balance for this account, ignoring all child accounts Args: as_of (Date): Only include transactions on or before this date raw (bool): If true the returned balance should not have its sign adjusted for display purposes. leg_query (models.Q): Django Q-expression, will be used to filter the transaction legs. allows for more complex filtering than that provided by **kwargs. kwargs (dict): Will be used to filter the transaction legs Returns: Balance """ legs = self.legs if as_of: legs = legs.filter(transaction__date__lte=as_of) if leg_query or kwargs: leg_query = leg_query or models.Q() legs = legs.filter(leg_query, **kwargs) return legs.sum_to_balance() * (1 if raw else self.sign) + self._zero_balance() def _zero_balance(self): """Get a balance for this account with all currencies set to zero""" return Balance([Money("0", currency) for currency in self.currencies]) @db_transaction.atomic()
adamcharnock/django-hordak
hordak/models/core.py
LegQuerySet.sum_to_balance
python
def sum_to_balance(self): result = self.values("amount_currency").annotate(total=models.Sum("amount")) return Balance([Money(r["total"], r["amount_currency"]) for r in result])
Sum the Legs of the QuerySet to get a `Balance`_ object
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L366-L370
null
class LegQuerySet(models.QuerySet):
adamcharnock/django-hordak
hordak/models/core.py
Leg.account_balance_after
python
def account_balance_after(self): # TODO: Consider moving to annotation, particularly once we can count on Django 1.11's subquery support transaction_date = self.transaction.date return self.account.balance( leg_query=( models.Q(transaction__date__lt=transaction_date) | ( models.Q(transaction__date=transaction_date) & models.Q(transaction_id__lte=self.transaction_id) ) ) )
Get the balance of the account associated with this leg following the transaction
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L441-L453
null
class Leg(models.Model): """ The leg of a transaction Represents a single amount either into or out of a transaction. All legs for a transaction must sum to zero, all legs must be of the same currency. Attributes: uuid (SmallUUID): UUID for transaction leg. Use to prevent leaking of IDs (if desired). transaction (Transaction): Transaction to which the Leg belongs. account (Account): Account the leg is transferring to/from. amount (Money): The amount being transferred description (str): Optional user-provided description type (str): :attr:`hordak.models.DEBIT` or :attr:`hordak.models.CREDIT`. """ uuid = SmallUUIDField(default=uuid_default(), editable=False) transaction = models.ForeignKey(Transaction, related_name="legs", on_delete=models.CASCADE) account = models.ForeignKey(Account, related_name="legs", on_delete=models.CASCADE) amount = MoneyField( max_digits=MAX_DIGITS, decimal_places=DECIMAL_PLACES, help_text="Record debits as positive, credits as negative", default_currency=defaults.INTERNAL_CURRENCY, ) description = models.TextField(default="", blank=True) objects = LegManager.from_queryset(LegQuerySet)() def save(self, *args, **kwargs): if self.amount.amount == 0: raise exceptions.ZeroAmountError() return super(Leg, self).save(*args, **kwargs) def natural_key(self): return (self.uuid,) @property def type(self): if self.amount.amount < 0: return DEBIT elif self.amount.amount > 0: return CREDIT else: # This should have been caught earlier by the database integrity check. # If you are seeing this then something is wrong with your DB checks. raise exceptions.ZeroAmountError() def is_debit(self): return self.type == DEBIT def is_credit(self): return self.type == CREDIT def account_balance_before(self): """Get the balance of the account associated with this leg before the transaction""" # TODO: Consider moving to annotation, particularly once we can count on Django 1.11's subquery support transaction_date = self.transaction.date return self.account.balance( leg_query=( models.Q(transaction__date__lt=transaction_date) | ( models.Q(transaction__date=transaction_date) & models.Q(transaction_id__lt=self.transaction_id) ) ) )
adamcharnock/django-hordak
hordak/models/core.py
Leg.account_balance_before
python
def account_balance_before(self): # TODO: Consider moving to annotation, particularly once we can count on Django 1.11's subquery support transaction_date = self.transaction.date return self.account.balance( leg_query=( models.Q(transaction__date__lt=transaction_date) | ( models.Q(transaction__date=transaction_date) & models.Q(transaction_id__lt=self.transaction_id) ) ) )
Get the balance of the account associated with this leg before the transaction
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L455-L467
null
class Leg(models.Model): """ The leg of a transaction Represents a single amount either into or out of a transaction. All legs for a transaction must sum to zero, all legs must be of the same currency. Attributes: uuid (SmallUUID): UUID for transaction leg. Use to prevent leaking of IDs (if desired). transaction (Transaction): Transaction to which the Leg belongs. account (Account): Account the leg is transferring to/from. amount (Money): The amount being transferred description (str): Optional user-provided description type (str): :attr:`hordak.models.DEBIT` or :attr:`hordak.models.CREDIT`. """ uuid = SmallUUIDField(default=uuid_default(), editable=False) transaction = models.ForeignKey(Transaction, related_name="legs", on_delete=models.CASCADE) account = models.ForeignKey(Account, related_name="legs", on_delete=models.CASCADE) amount = MoneyField( max_digits=MAX_DIGITS, decimal_places=DECIMAL_PLACES, help_text="Record debits as positive, credits as negative", default_currency=defaults.INTERNAL_CURRENCY, ) description = models.TextField(default="", blank=True) objects = LegManager.from_queryset(LegQuerySet)() def save(self, *args, **kwargs): if self.amount.amount == 0: raise exceptions.ZeroAmountError() return super(Leg, self).save(*args, **kwargs) def natural_key(self): return (self.uuid,) @property def type(self): if self.amount.amount < 0: return DEBIT elif self.amount.amount > 0: return CREDIT else: # This should have been caught earlier by the database integrity check. # If you are seeing this then something is wrong with your DB checks. raise exceptions.ZeroAmountError() def is_debit(self): return self.type == DEBIT def is_credit(self): return self.type == CREDIT def account_balance_after(self): """Get the balance of the account associated with this leg following the transaction""" # TODO: Consider moving to annotation, particularly once we can count on Django 1.11's subquery support transaction_date = self.transaction.date return self.account.balance( leg_query=( models.Q(transaction__date__lt=transaction_date) | ( models.Q(transaction__date=transaction_date) & models.Q(transaction_id__lte=self.transaction_id) ) ) )
adamcharnock/django-hordak
hordak/models/core.py
StatementLine.create_transaction
python
def create_transaction(self, to_account): from_account = self.statement_import.bank_account transaction = Transaction.objects.create() Leg.objects.create( transaction=transaction, account=from_account, amount=+(self.amount * -1) ) Leg.objects.create(transaction=transaction, account=to_account, amount=-(self.amount * -1)) transaction.date = self.date transaction.save() self.transaction = transaction self.save() return transaction
Create a transaction for this statement amount and account, into to_account This will also set this StatementLine's ``transaction`` attribute to the newly created transaction. Args: to_account (Account): The account the transaction is into / out of. Returns: Transaction: The newly created (and committed) transaction.
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L574-L600
null
class StatementLine(models.Model): """ Records an single imported bank statement line A StatementLine is purely a utility to aid in the creation of transactions (in the process known as reconciliation). StatementLines have no impact on account balances. However, the :meth:`StatementLine.create_transaction()` method can be used to create a transaction based on the information in the StatementLine. Attributes: uuid (SmallUUID): UUID for statement line. Use to prevent leaking of IDs (if desired). timestamp (datetime): The datetime when the object was created. date (date): The date given by the statement line statement_import (StatementImport): The import to which the line belongs amount (Decimal): The amount for the statement line, positive or nagative. description (str): Any description/memo information provided transaction (Transaction): Optionally, the transaction created for this statement line. This normally occurs during reconciliation. See also :meth:`StatementLine.create_transaction()`. """ uuid = SmallUUIDField(default=uuid_default(), editable=False) timestamp = models.DateTimeField(default=timezone.now) date = models.DateField() statement_import = models.ForeignKey( StatementImport, related_name="lines", on_delete=models.CASCADE ) amount = models.DecimalField(max_digits=MAX_DIGITS, decimal_places=DECIMAL_PLACES) description = models.TextField(default="", blank=True) type = models.CharField(max_length=50, default="") # TODO: Add constraint to ensure transaction amount = statement line amount # TODO: Add constraint to ensure one statement line per transaction transaction = models.ForeignKey( Transaction, default=None, blank=True, null=True, help_text="Reconcile this statement line to this transaction", on_delete=models.SET_NULL, ) source_data = JSONField( default=json_default, help_text="Original data received from the data source." ) objects = StatementLineManager() def natural_key(self): return (self.uuid,) @property def is_reconciled(self): """Has this statement line been reconciled? Determined as ``True`` if :attr:`transaction` has been set. Returns: bool: ``True`` if reconciled, ``False`` if not. """ return bool(self.transaction) @db_transaction.atomic()
adamcharnock/django-hordak
hordak/utilities/currency.py
currency_exchange
python
def currency_exchange( source, source_amount, destination, destination_amount, trading_account, fee_destination=None, fee_amount=None, date=None, description=None, ): from hordak.models import Account, Transaction, Leg if trading_account.type != Account.TYPES.trading: raise TradingAccountRequiredError( "Account {} must be a trading account".format(trading_account) ) if (fee_destination or fee_amount) and not (fee_destination and fee_amount): raise RuntimeError( "You must specify either neither or both fee_destination and fee_amount." ) if fee_amount is None: # If fees are not specified then set fee_amount to be zero fee_amount = Money(0, source_amount.currency) else: # If we do have fees then make sure the fee currency matches the source currency if fee_amount.currency != source_amount.currency: raise InvalidFeeCurrency( "Fee amount currency ({}) must match source amount currency ({})".format( fee_amount.currency, source_amount.currency ) ) # Checks over and done now. Let's create the transaction with db_transaction.atomic(): transaction = Transaction.objects.create( date=date or datetime.date.today(), description=description or "Exchange of {} to {}, incurring {} fees".format( source_amount, destination_amount, "no" if fee_amount is None else fee_amount ), ) # Source currency into trading account Leg.objects.create(transaction=transaction, account=source, amount=source_amount) Leg.objects.create( transaction=transaction, account=trading_account, amount=-(source_amount - fee_amount) ) # Any fees if fee_amount and fee_destination: Leg.objects.create( transaction=transaction, account=fee_destination, amount=-fee_amount, description="Fees", ) # Destination currency out of trading account Leg.objects.create( transaction=transaction, account=trading_account, amount=destination_amount ) Leg.objects.create(transaction=transaction, account=destination, amount=-destination_amount) return transaction
Exchange funds from one currency to another Use this method to represent a real world currency transfer. Note this process doesn't care about exchange rates, only about the value of currency going in and out of the transaction. You can also record any exchange fees by syphoning off funds to ``fee_account`` of amount ``fee_amount``. Note that the free currency must be the same as the source currency. Examples: For example, imagine our Canadian bank has obligingly transferred 120 CAD into our US bank account. We sent CAD 120, and received USD 100. We were also changed 1.50 CAD in fees. We can represent this exchange in Hordak as follows:: from hordak.utilities.currency import currency_exchange currency_exchange( # Source account and amount source=cad_cash, source_amount=Money(120, 'CAD'), # Destination account and amount destination=usd_cash, destination_amount=Money(100, 'USD'), # Trading account the exchange will be done through trading_account=trading, # We also incur some fees fee_destination=banking_fees, fee_amount=Money(1.50, 'CAD') ) We should now find that: 1. ``cad_cash.balance()`` has decreased by ``CAD 120`` 2. ``usd_cash.balance()`` has increased by ``USD 100`` 3. ``banking_fees.balance()`` is ``CAD 1.50`` 4. ``trading_account.balance()`` is ``USD 100, CAD -120`` You can perform ``trading_account.normalise()`` to discover your unrealised gains/losses on currency traded through that account. Args: source (Account): The account the funds will be taken from source_amount (Money): A ``Money`` instance containing the inbound amount and currency. destination (Account): The account the funds will be placed into destination_amount (Money): A ``Money`` instance containing the outbound amount and currency trading_account (Account): The trading account to be used. The normalised balance of this account will indicate gains/losses you have made as part of your activity via this account. Note that the normalised balance fluctuates with the current exchange rate. fee_destination (Account): Your exchange may incur fees. Specifying this will move incurred fees into this account (optional). fee_amount (Money): The amount and currency of any incurred fees (optional). description (str): Description for the transaction. Will default to describing funds in/out & fees (optional). date (datetime.date): The date on which the transaction took place. Defaults to today (optional). Returns: (Transaction): The transaction created See Also: You can see the above example in practice in ``CurrencyExchangeTestCase.test_fees`` in `test_currency.py`_. .. _test_currency.py: https://github.com/adamcharnock/django-hordak/blob/master/hordak/tests/utilities/test_currency.py
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/utilities/currency.py#L88-L218
null
# -*- coding: utf-8 -*- """ Overview -------- Hordak features multi currency support. Each account in Hordak can support one or more currencies. Hordak does provide currency conversion functionality, but should be as part of the display logic only. It is also a good idea to make it clear to users that you are showing converted values. The preference for Hordak internals is to always store & process values in the intended currency. This is because currency conversion is an inherently lossy process. Exchange rates vary over time, and rounding errors mean that currency conversions are not reversible without data loss (e.g. ¥176.51 -> $1.54 -> ¥176.20). Classes ------- ``Money`` **instances**: The ``Money`` class is provided by `moneyd`_ and combines both an amount and a currency into a single value. Hordak uses these these as the core unit of monetary value. ``Balance`` **instances (see below for more details)**: An account can hold multiple currencies, and a `Balance`_ instance is how we represent this. A `Balance`_ may contain one or more ``Money`` objects. There will be precisely one ``Money`` object for each currency which the account holds. Balance objects may be added, subtracted etc. This will produce a new `Balance`_ object containing a union of all the currencies involved in the calculation, even where the result was zero. Accounts with ``is_bank_account=True`` may only support a single currency. Caching ------- Currency conversion makes use of Django's cache. It is therefore recommended that you `setup your Django cache`_ to something other than the default in-memory store. .. _moneyd: https://github.com/limist/py-moneyed .. _setup your Django cache: https://docs.djangoproject.com/en/1.10/topics/cache/ """ from __future__ import division import logging from decimal import Decimal import babel.numbers import requests import datetime import six import copy from django.core.cache import cache from django.db import transaction as db_transaction from django.utils.translation import get_language from django.utils.translation import to_locale from moneyed import Money from moneyed.localization import format_money from hordak import defaults from hordak.exceptions import ( LossyCalculationError, BalanceComparisonError, TradingAccountRequiredError, InvalidFeeCurrency, CannotSimplifyError, ) logger = logging.getLogger(__name__) def _cache_key(currency, date): return "{}-{}-{}".format(defaults.INTERNAL_CURRENCY, currency, date) def _cache_timeout(date_): if date_ == datetime.date.today(): # Cache today's rates for 24 hours only, as we will # want to get average dates again once trading is over return 3600 * 24 else: # None = cache forever return None class BaseBackend(object): """ Top-level exchange rate backend This should be extended to hook into your preferred exchange rate service. The primary method which needs defining is :meth:`_get_rate()`. """ supported_currencies = [] def __init__(self): if not self.is_supported(defaults.INTERNAL_CURRENCY): raise ValueError( "Currency specified by INTERNAL_CURRENCY " "is not supported by this backend: ".format(defaults.INTERNAL_CURRENCY) ) def cache_rate(self, currency, date, rate): """ Cache a rate for future use """ if not self.is_supported(defaults.INTERNAL_CURRENCY): logger.info('Tried to cache unsupported currency "{}". Ignoring.'.format(currency)) else: cache.set(_cache_key(currency, date), str(rate), _cache_timeout(date)) def get_rate(self, currency, date): """Get the exchange rate for ``currency`` against ``_INTERNAL_CURRENCY`` If implementing your own backend, you should probably override :meth:`_get_rate()` rather than this. """ if str(currency) == defaults.INTERNAL_CURRENCY: return Decimal(1) cached = cache.get(_cache_key(currency, date)) if cached: return Decimal(cached) else: # Expect self._get_rate() to implement caching return Decimal(self._get_rate(currency, date)) def _get_rate(self, currency, date): """Get the exchange rate for ``currency`` against ``INTERNAL_CURRENCY`` You should implement this in any custom backend. For each rate you should call :meth:`cache_rate()`. Normally you will only need to call :meth:`cache_rate()` once. However, some services provide multiple exchange rates in a single response, in which it will likely be expedient to cache them all. .. important:: Not calling :meth:`cache_rate()` will result in your backend service being called for every currency conversion. This could be very slow and may result in your software being rate limited (or, if you pay for your exchange rates, you may get a big bill). """ raise NotImplementedError() def ensure_supported(self, currency): if not self.is_supported(currency): raise ValueError("Currency not supported by backend: {}".format(currency)) def is_supported(self, currency): return str(currency) in self.supported_currencies class FixerBackend(BaseBackend): """Use fixer.io for currency conversions""" supported_currencies = [ "AUD", "BGN", "BRL", "CAD", "CHF", "CNY", "CZK", "DKK", "GBP", "HKD", "HRK", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PLN", "RON", "RUB", "SEK", "SGD", "THB", "TRY", "ZAR", "EUR", "USD", ] def _get_rate(self, currency, date_): self.ensure_supported(currency) response = requests.get( "https://api.fixer.io/{date}?base={base}".format( base=defaults.INTERNAL_CURRENCY, date=date_.strftime("%Y-%m-%d") ) ) response.raise_for_status() data = response.json(parse_float=Decimal) rates = data["rates"] returned_date = datetime.date(*map(int, data["date"].split("-"))) requested_rate = rates[str(currency)] for currency, rate in rates.items(): self.cache_rate(currency, returned_date, rate) return requested_rate class Converter(object): # TODO: Make configurable def __init__(self, base_currency=defaults.INTERNAL_CURRENCY, backend=FixerBackend()): self.base_currency = base_currency self.backend = backend def convert(self, money, to_currency, date=None): """Convert the given ``money`` to ``to_currency`` using exchange rate on ``date`` If ``date`` is omitted then the date given by ``money.date`` will be used. """ if str(money.currency) == str(to_currency): return copy.copy(money) return Money( amount=money.amount * self.rate(money.currency, to_currency, date or datetime.date.today()), currency=to_currency, ) def rate(self, from_currency, to_currency, date): """Get the exchange rate between the specified currencies""" return (1 / self.backend.get_rate(from_currency, date)) * self.backend.get_rate( to_currency, date ) converter = Converter() class Balance(object): """An account balance Accounts may have multiple currencies. This class represents these multi-currency balances and provides math functionality. Balances can be added, subtracted, multiplied, divided, absolute'ed, and have their sign changed. Examples: Example use:: Balance([Money(100, 'USD'), Money(200, 'EUR')]) # Or in short form Balance(100, 'USD', 200, 'EUR') .. important:: Balances can also be compared, but note that this requires a currency conversion step. Therefore it is possible that balances will compare differently as exchange rates change over time. """ def __init__(self, _money_obs=None, *args): all_args = [_money_obs] + list(args) if len(all_args) % 2 == 0: _money_obs = [] for i in range(0, len(all_args) - 1, 2): _money_obs.append(Money(all_args[i], all_args[i + 1])) self._money_obs = tuple(_money_obs or []) self._by_currency = {m.currency.code: m for m in self._money_obs} if len(self._by_currency) != len(self._money_obs): raise ValueError( "Duplicate currency provided. All Money instances must have a unique currency." ) def __str__(self): def fmt(money): return babel.numbers.format_currency(money.amount, currency=money.currency.code) return ", ".join(map(fmt, self._money_obs)) or "No values" def __repr__(self): return "Balance: {}".format(self.__str__()) def __getitem__(self, currency): if hasattr(currency, "code"): currency = currency.code elif not isinstance(currency, six.string_types) or len(currency) != 3: raise ValueError("Currencies must be a string of length three, not {}".format(currency)) try: return self._by_currency[currency] except KeyError: return Money(0, currency) def __add__(self, other): if not isinstance(other, Balance): raise TypeError( "Can only add/subtract Balance instances, not Balance and {}.".format(type(other)) ) by_currency = copy.deepcopy(self._by_currency) for other_currency, other_money in other._by_currency.items(): by_currency[other_currency] = other_money + self[other_currency] return self.__class__(by_currency.values()) def __sub__(self, other): return self.__add__(-other) def __neg__(self): return self.__class__([-m for m in self._money_obs]) def __pos__(self): return self.__class__([+m for m in self._money_obs]) def __mul__(self, other): if isinstance(other, Balance): raise TypeError("Cannot multiply two Balance instances.") elif isinstance(other, float): raise LossyCalculationError( "Cannot multiply a Balance by a float. Use a Decimal or an int." ) return self.__class__([m * other for m in self._money_obs]) def __truediv__(self, other): if isinstance(other, Balance): raise TypeError("Cannot multiply two Balance instances.") elif isinstance(other, float): raise LossyCalculationError( "Cannot divide a Balance by a float. Use a Decimal or an int." ) return self.__class__([m / other for m in self._money_obs]) def __abs__(self): return self.__class__([abs(m) for m in self._money_obs]) def __bool__(self): return any([bool(m) for m in self._money_obs]) if six.PY2: __nonzero__ = __bool__ def __eq__(self, other): if other == 0: # Support comparing to integer/Decimal zero as it is useful return not self.__bool__() elif not isinstance(other, Balance): raise TypeError( "Can only compare Balance objects to other " "Balance objects, not to type {}".format(type(other)) ) return not self - other def __ne__(self, other): return not self.__eq__(other) def __lt__(self, other): if isinstance(other, Money): other = self.__class__([other]) # We can compare against non-balance 0-values, but otherwise we have to # compare against a Balance (otherwise we won't know what currency we are # dealing with) if isinstance(other, (float, int, Decimal)) and other == 0: other = self.__class__() if not isinstance(other, Balance): raise BalanceComparisonError(other) # If we can confidently simplify the values to # -1, 0, and 1, and the values are different, then # just compare those. try: self_simplified = self._simplify() other_simplified = other._simplify() if self_simplified != other_simplified: return self_simplified < other_simplified except CannotSimplifyError: pass if len(self._money_obs) == 1 and self.currencies() == other.currencies(): # Shortcut if we have a single value with the same currency return self._money_obs[0] < other._money_obs[0] else: money = self.normalise(defaults.INTERNAL_CURRENCY)._money_obs[0] other_money = other.normalise(defaults.INTERNAL_CURRENCY)._money_obs[0] return money < other_money def __gt__(self, other): return not self < other and not self == other def __le__(self, other): return self < other or self == other def __ge__(self, other): return self > other or self == other def monies(self): """Get a list of the underlying ``Money`` instances Returns: ([Money]): A list of zero or money money instances. Currencies will be unique. """ return [copy.copy(m) for m in self._money_obs] def currencies(self): """Get all currencies with non-zero values""" return [m.currency.code for m in self.monies() if m.amount] def normalise(self, to_currency): """Normalise this balance into a single currency Args: to_currency (str): Destination currency Returns: (Balance): A new balance object containing a single Money value in the specified currency """ out = Money(currency=to_currency) for money in self._money_obs: out += converter.convert(money, to_currency) return Balance([out]) def _is_positive(self): return all([m.amount > 0 for m in self.monies()]) and self.monies() def _is_negative(self): return all([m.amount < 0 for m in self.monies()]) and self.monies() def _is_zero(self): return not self.monies() or all([m.amount == 0 for m in self.monies()]) def _simplify(self): if self._is_positive(): return 1 elif self._is_negative(): return -1 elif self._is_zero(): return 0 else: raise CannotSimplifyError()
adamcharnock/django-hordak
hordak/utilities/currency.py
BaseBackend.cache_rate
python
def cache_rate(self, currency, date, rate): if not self.is_supported(defaults.INTERNAL_CURRENCY): logger.info('Tried to cache unsupported currency "{}". Ignoring.'.format(currency)) else: cache.set(_cache_key(currency, date), str(rate), _cache_timeout(date))
Cache a rate for future use
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/utilities/currency.py#L237-L244
[ "def _cache_key(currency, date):\n return \"{}-{}-{}\".format(defaults.INTERNAL_CURRENCY, currency, date)\n", "def _cache_timeout(date_):\n if date_ == datetime.date.today():\n # Cache today's rates for 24 hours only, as we will\n # want to get average dates again once trading is over\n return 3600 * 24\n else:\n # None = cache forever\n return None\n", "def is_supported(self, currency):\n return str(currency) in self.supported_currencies\n" ]
class BaseBackend(object): """ Top-level exchange rate backend This should be extended to hook into your preferred exchange rate service. The primary method which needs defining is :meth:`_get_rate()`. """ supported_currencies = [] def __init__(self): if not self.is_supported(defaults.INTERNAL_CURRENCY): raise ValueError( "Currency specified by INTERNAL_CURRENCY " "is not supported by this backend: ".format(defaults.INTERNAL_CURRENCY) ) def get_rate(self, currency, date): """Get the exchange rate for ``currency`` against ``_INTERNAL_CURRENCY`` If implementing your own backend, you should probably override :meth:`_get_rate()` rather than this. """ if str(currency) == defaults.INTERNAL_CURRENCY: return Decimal(1) cached = cache.get(_cache_key(currency, date)) if cached: return Decimal(cached) else: # Expect self._get_rate() to implement caching return Decimal(self._get_rate(currency, date)) def _get_rate(self, currency, date): """Get the exchange rate for ``currency`` against ``INTERNAL_CURRENCY`` You should implement this in any custom backend. For each rate you should call :meth:`cache_rate()`. Normally you will only need to call :meth:`cache_rate()` once. However, some services provide multiple exchange rates in a single response, in which it will likely be expedient to cache them all. .. important:: Not calling :meth:`cache_rate()` will result in your backend service being called for every currency conversion. This could be very slow and may result in your software being rate limited (or, if you pay for your exchange rates, you may get a big bill). """ raise NotImplementedError() def ensure_supported(self, currency): if not self.is_supported(currency): raise ValueError("Currency not supported by backend: {}".format(currency)) def is_supported(self, currency): return str(currency) in self.supported_currencies
adamcharnock/django-hordak
hordak/utilities/currency.py
BaseBackend.get_rate
python
def get_rate(self, currency, date): if str(currency) == defaults.INTERNAL_CURRENCY: return Decimal(1) cached = cache.get(_cache_key(currency, date)) if cached: return Decimal(cached) else: # Expect self._get_rate() to implement caching return Decimal(self._get_rate(currency, date))
Get the exchange rate for ``currency`` against ``_INTERNAL_CURRENCY`` If implementing your own backend, you should probably override :meth:`_get_rate()` rather than this.
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/utilities/currency.py#L246-L260
[ "def _cache_key(currency, date):\n return \"{}-{}-{}\".format(defaults.INTERNAL_CURRENCY, currency, date)\n", "def _get_rate(self, currency, date):\n \"\"\"Get the exchange rate for ``currency`` against ``INTERNAL_CURRENCY``\n\n You should implement this in any custom backend. For each rate\n you should call :meth:`cache_rate()`.\n\n Normally you will only need to call :meth:`cache_rate()` once. However, some\n services provide multiple exchange rates in a single response,\n in which it will likely be expedient to cache them all.\n\n .. important::\n\n Not calling :meth:`cache_rate()` will result in your backend service being called for\n every currency conversion. This could be very slow and may result in your\n software being rate limited (or, if you pay for your exchange rates, you may\n get a big bill).\n \"\"\"\n raise NotImplementedError()\n", "def _get_rate(self, currency, date_):\n self.ensure_supported(currency)\n response = requests.get(\n \"https://api.fixer.io/{date}?base={base}\".format(\n base=defaults.INTERNAL_CURRENCY, date=date_.strftime(\"%Y-%m-%d\")\n )\n )\n response.raise_for_status()\n\n data = response.json(parse_float=Decimal)\n rates = data[\"rates\"]\n returned_date = datetime.date(*map(int, data[\"date\"].split(\"-\")))\n requested_rate = rates[str(currency)]\n\n for currency, rate in rates.items():\n self.cache_rate(currency, returned_date, rate)\n\n return requested_rate\n", "def _get_rate(self, currency, date_):\n if date_ < date(2010, 1, 1):\n rates = dict(GBP=Decimal(2), USD=Decimal(3))\n else:\n rates = dict(GBP=Decimal(10), USD=Decimal(20))\n rate = rates[str(currency)]\n self.cache_rate(currency, date_, rate)\n return rate\n" ]
class BaseBackend(object): """ Top-level exchange rate backend This should be extended to hook into your preferred exchange rate service. The primary method which needs defining is :meth:`_get_rate()`. """ supported_currencies = [] def __init__(self): if not self.is_supported(defaults.INTERNAL_CURRENCY): raise ValueError( "Currency specified by INTERNAL_CURRENCY " "is not supported by this backend: ".format(defaults.INTERNAL_CURRENCY) ) def cache_rate(self, currency, date, rate): """ Cache a rate for future use """ if not self.is_supported(defaults.INTERNAL_CURRENCY): logger.info('Tried to cache unsupported currency "{}". Ignoring.'.format(currency)) else: cache.set(_cache_key(currency, date), str(rate), _cache_timeout(date)) def _get_rate(self, currency, date): """Get the exchange rate for ``currency`` against ``INTERNAL_CURRENCY`` You should implement this in any custom backend. For each rate you should call :meth:`cache_rate()`. Normally you will only need to call :meth:`cache_rate()` once. However, some services provide multiple exchange rates in a single response, in which it will likely be expedient to cache them all. .. important:: Not calling :meth:`cache_rate()` will result in your backend service being called for every currency conversion. This could be very slow and may result in your software being rate limited (or, if you pay for your exchange rates, you may get a big bill). """ raise NotImplementedError() def ensure_supported(self, currency): if not self.is_supported(currency): raise ValueError("Currency not supported by backend: {}".format(currency)) def is_supported(self, currency): return str(currency) in self.supported_currencies
adamcharnock/django-hordak
hordak/utilities/currency.py
Converter.convert
python
def convert(self, money, to_currency, date=None): if str(money.currency) == str(to_currency): return copy.copy(money) return Money( amount=money.amount * self.rate(money.currency, to_currency, date or datetime.date.today()), currency=to_currency, )
Convert the given ``money`` to ``to_currency`` using exchange rate on ``date`` If ``date`` is omitted then the date given by ``money.date`` will be used.
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/utilities/currency.py#L354-L365
[ "def rate(self, from_currency, to_currency, date):\n \"\"\"Get the exchange rate between the specified currencies\"\"\"\n return (1 / self.backend.get_rate(from_currency, date)) * self.backend.get_rate(\n to_currency, date\n )\n" ]
class Converter(object): # TODO: Make configurable def __init__(self, base_currency=defaults.INTERNAL_CURRENCY, backend=FixerBackend()): self.base_currency = base_currency self.backend = backend def rate(self, from_currency, to_currency, date): """Get the exchange rate between the specified currencies""" return (1 / self.backend.get_rate(from_currency, date)) * self.backend.get_rate( to_currency, date )
adamcharnock/django-hordak
hordak/utilities/currency.py
Converter.rate
python
def rate(self, from_currency, to_currency, date): return (1 / self.backend.get_rate(from_currency, date)) * self.backend.get_rate( to_currency, date )
Get the exchange rate between the specified currencies
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/utilities/currency.py#L367-L371
null
class Converter(object): # TODO: Make configurable def __init__(self, base_currency=defaults.INTERNAL_CURRENCY, backend=FixerBackend()): self.base_currency = base_currency self.backend = backend def convert(self, money, to_currency, date=None): """Convert the given ``money`` to ``to_currency`` using exchange rate on ``date`` If ``date`` is omitted then the date given by ``money.date`` will be used. """ if str(money.currency) == str(to_currency): return copy.copy(money) return Money( amount=money.amount * self.rate(money.currency, to_currency, date or datetime.date.today()), currency=to_currency, )
adamcharnock/django-hordak
hordak/utilities/currency.py
Balance.currencies
python
def currencies(self): return [m.currency.code for m in self.monies() if m.amount]
Get all currencies with non-zero values
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/utilities/currency.py#L542-L544
[ "def monies(self):\n \"\"\"Get a list of the underlying ``Money`` instances\n\n Returns:\n ([Money]): A list of zero or money money instances. Currencies will be unique.\n \"\"\"\n return [copy.copy(m) for m in self._money_obs]\n" ]
class Balance(object): """An account balance Accounts may have multiple currencies. This class represents these multi-currency balances and provides math functionality. Balances can be added, subtracted, multiplied, divided, absolute'ed, and have their sign changed. Examples: Example use:: Balance([Money(100, 'USD'), Money(200, 'EUR')]) # Or in short form Balance(100, 'USD', 200, 'EUR') .. important:: Balances can also be compared, but note that this requires a currency conversion step. Therefore it is possible that balances will compare differently as exchange rates change over time. """ def __init__(self, _money_obs=None, *args): all_args = [_money_obs] + list(args) if len(all_args) % 2 == 0: _money_obs = [] for i in range(0, len(all_args) - 1, 2): _money_obs.append(Money(all_args[i], all_args[i + 1])) self._money_obs = tuple(_money_obs or []) self._by_currency = {m.currency.code: m for m in self._money_obs} if len(self._by_currency) != len(self._money_obs): raise ValueError( "Duplicate currency provided. All Money instances must have a unique currency." ) def __str__(self): def fmt(money): return babel.numbers.format_currency(money.amount, currency=money.currency.code) return ", ".join(map(fmt, self._money_obs)) or "No values" def __repr__(self): return "Balance: {}".format(self.__str__()) def __getitem__(self, currency): if hasattr(currency, "code"): currency = currency.code elif not isinstance(currency, six.string_types) or len(currency) != 3: raise ValueError("Currencies must be a string of length three, not {}".format(currency)) try: return self._by_currency[currency] except KeyError: return Money(0, currency) def __add__(self, other): if not isinstance(other, Balance): raise TypeError( "Can only add/subtract Balance instances, not Balance and {}.".format(type(other)) ) by_currency = copy.deepcopy(self._by_currency) for other_currency, other_money in other._by_currency.items(): by_currency[other_currency] = other_money + self[other_currency] return self.__class__(by_currency.values()) def __sub__(self, other): return self.__add__(-other) def __neg__(self): return self.__class__([-m for m in self._money_obs]) def __pos__(self): return self.__class__([+m for m in self._money_obs]) def __mul__(self, other): if isinstance(other, Balance): raise TypeError("Cannot multiply two Balance instances.") elif isinstance(other, float): raise LossyCalculationError( "Cannot multiply a Balance by a float. Use a Decimal or an int." ) return self.__class__([m * other for m in self._money_obs]) def __truediv__(self, other): if isinstance(other, Balance): raise TypeError("Cannot multiply two Balance instances.") elif isinstance(other, float): raise LossyCalculationError( "Cannot divide a Balance by a float. Use a Decimal or an int." ) return self.__class__([m / other for m in self._money_obs]) def __abs__(self): return self.__class__([abs(m) for m in self._money_obs]) def __bool__(self): return any([bool(m) for m in self._money_obs]) if six.PY2: __nonzero__ = __bool__ def __eq__(self, other): if other == 0: # Support comparing to integer/Decimal zero as it is useful return not self.__bool__() elif not isinstance(other, Balance): raise TypeError( "Can only compare Balance objects to other " "Balance objects, not to type {}".format(type(other)) ) return not self - other def __ne__(self, other): return not self.__eq__(other) def __lt__(self, other): if isinstance(other, Money): other = self.__class__([other]) # We can compare against non-balance 0-values, but otherwise we have to # compare against a Balance (otherwise we won't know what currency we are # dealing with) if isinstance(other, (float, int, Decimal)) and other == 0: other = self.__class__() if not isinstance(other, Balance): raise BalanceComparisonError(other) # If we can confidently simplify the values to # -1, 0, and 1, and the values are different, then # just compare those. try: self_simplified = self._simplify() other_simplified = other._simplify() if self_simplified != other_simplified: return self_simplified < other_simplified except CannotSimplifyError: pass if len(self._money_obs) == 1 and self.currencies() == other.currencies(): # Shortcut if we have a single value with the same currency return self._money_obs[0] < other._money_obs[0] else: money = self.normalise(defaults.INTERNAL_CURRENCY)._money_obs[0] other_money = other.normalise(defaults.INTERNAL_CURRENCY)._money_obs[0] return money < other_money def __gt__(self, other): return not self < other and not self == other def __le__(self, other): return self < other or self == other def __ge__(self, other): return self > other or self == other def monies(self): """Get a list of the underlying ``Money`` instances Returns: ([Money]): A list of zero or money money instances. Currencies will be unique. """ return [copy.copy(m) for m in self._money_obs] def normalise(self, to_currency): """Normalise this balance into a single currency Args: to_currency (str): Destination currency Returns: (Balance): A new balance object containing a single Money value in the specified currency """ out = Money(currency=to_currency) for money in self._money_obs: out += converter.convert(money, to_currency) return Balance([out]) def _is_positive(self): return all([m.amount > 0 for m in self.monies()]) and self.monies() def _is_negative(self): return all([m.amount < 0 for m in self.monies()]) and self.monies() def _is_zero(self): return not self.monies() or all([m.amount == 0 for m in self.monies()]) def _simplify(self): if self._is_positive(): return 1 elif self._is_negative(): return -1 elif self._is_zero(): return 0 else: raise CannotSimplifyError()
adamcharnock/django-hordak
hordak/utilities/currency.py
Balance.normalise
python
def normalise(self, to_currency): out = Money(currency=to_currency) for money in self._money_obs: out += converter.convert(money, to_currency) return Balance([out])
Normalise this balance into a single currency Args: to_currency (str): Destination currency Returns: (Balance): A new balance object containing a single Money value in the specified currency
train
https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/utilities/currency.py#L546-L558
[ "def convert(self, money, to_currency, date=None):\n \"\"\"Convert the given ``money`` to ``to_currency`` using exchange rate on ``date``\n\n If ``date`` is omitted then the date given by ``money.date`` will be used.\n \"\"\"\n if str(money.currency) == str(to_currency):\n return copy.copy(money)\n return Money(\n amount=money.amount\n * self.rate(money.currency, to_currency, date or datetime.date.today()),\n currency=to_currency,\n )\n" ]
class Balance(object): """An account balance Accounts may have multiple currencies. This class represents these multi-currency balances and provides math functionality. Balances can be added, subtracted, multiplied, divided, absolute'ed, and have their sign changed. Examples: Example use:: Balance([Money(100, 'USD'), Money(200, 'EUR')]) # Or in short form Balance(100, 'USD', 200, 'EUR') .. important:: Balances can also be compared, but note that this requires a currency conversion step. Therefore it is possible that balances will compare differently as exchange rates change over time. """ def __init__(self, _money_obs=None, *args): all_args = [_money_obs] + list(args) if len(all_args) % 2 == 0: _money_obs = [] for i in range(0, len(all_args) - 1, 2): _money_obs.append(Money(all_args[i], all_args[i + 1])) self._money_obs = tuple(_money_obs or []) self._by_currency = {m.currency.code: m for m in self._money_obs} if len(self._by_currency) != len(self._money_obs): raise ValueError( "Duplicate currency provided. All Money instances must have a unique currency." ) def __str__(self): def fmt(money): return babel.numbers.format_currency(money.amount, currency=money.currency.code) return ", ".join(map(fmt, self._money_obs)) or "No values" def __repr__(self): return "Balance: {}".format(self.__str__()) def __getitem__(self, currency): if hasattr(currency, "code"): currency = currency.code elif not isinstance(currency, six.string_types) or len(currency) != 3: raise ValueError("Currencies must be a string of length three, not {}".format(currency)) try: return self._by_currency[currency] except KeyError: return Money(0, currency) def __add__(self, other): if not isinstance(other, Balance): raise TypeError( "Can only add/subtract Balance instances, not Balance and {}.".format(type(other)) ) by_currency = copy.deepcopy(self._by_currency) for other_currency, other_money in other._by_currency.items(): by_currency[other_currency] = other_money + self[other_currency] return self.__class__(by_currency.values()) def __sub__(self, other): return self.__add__(-other) def __neg__(self): return self.__class__([-m for m in self._money_obs]) def __pos__(self): return self.__class__([+m for m in self._money_obs]) def __mul__(self, other): if isinstance(other, Balance): raise TypeError("Cannot multiply two Balance instances.") elif isinstance(other, float): raise LossyCalculationError( "Cannot multiply a Balance by a float. Use a Decimal or an int." ) return self.__class__([m * other for m in self._money_obs]) def __truediv__(self, other): if isinstance(other, Balance): raise TypeError("Cannot multiply two Balance instances.") elif isinstance(other, float): raise LossyCalculationError( "Cannot divide a Balance by a float. Use a Decimal or an int." ) return self.__class__([m / other for m in self._money_obs]) def __abs__(self): return self.__class__([abs(m) for m in self._money_obs]) def __bool__(self): return any([bool(m) for m in self._money_obs]) if six.PY2: __nonzero__ = __bool__ def __eq__(self, other): if other == 0: # Support comparing to integer/Decimal zero as it is useful return not self.__bool__() elif not isinstance(other, Balance): raise TypeError( "Can only compare Balance objects to other " "Balance objects, not to type {}".format(type(other)) ) return not self - other def __ne__(self, other): return not self.__eq__(other) def __lt__(self, other): if isinstance(other, Money): other = self.__class__([other]) # We can compare against non-balance 0-values, but otherwise we have to # compare against a Balance (otherwise we won't know what currency we are # dealing with) if isinstance(other, (float, int, Decimal)) and other == 0: other = self.__class__() if not isinstance(other, Balance): raise BalanceComparisonError(other) # If we can confidently simplify the values to # -1, 0, and 1, and the values are different, then # just compare those. try: self_simplified = self._simplify() other_simplified = other._simplify() if self_simplified != other_simplified: return self_simplified < other_simplified except CannotSimplifyError: pass if len(self._money_obs) == 1 and self.currencies() == other.currencies(): # Shortcut if we have a single value with the same currency return self._money_obs[0] < other._money_obs[0] else: money = self.normalise(defaults.INTERNAL_CURRENCY)._money_obs[0] other_money = other.normalise(defaults.INTERNAL_CURRENCY)._money_obs[0] return money < other_money def __gt__(self, other): return not self < other and not self == other def __le__(self, other): return self < other or self == other def __ge__(self, other): return self > other or self == other def monies(self): """Get a list of the underlying ``Money`` instances Returns: ([Money]): A list of zero or money money instances. Currencies will be unique. """ return [copy.copy(m) for m in self._money_obs] def currencies(self): """Get all currencies with non-zero values""" return [m.currency.code for m in self.monies() if m.amount] def _is_positive(self): return all([m.amount > 0 for m in self.monies()]) and self.monies() def _is_negative(self): return all([m.amount < 0 for m in self.monies()]) and self.monies() def _is_zero(self): return not self.monies() or all([m.amount == 0 for m in self.monies()]) def _simplify(self): if self._is_positive(): return 1 elif self._is_negative(): return -1 elif self._is_zero(): return 0 else: raise CannotSimplifyError()
joowani/binarytree
binarytree/__init__.py
_is_balanced
python
def _is_balanced(root): if root is None: return 0 left = _is_balanced(root.left) if left < 0: return -1 right = _is_balanced(root.right) if right < 0: return -1 return -1 if abs(left - right) > 1 else max(left, right) + 1
Return the height if the binary tree is balanced, -1 otherwise. :param root: Root node of the binary tree. :type root: binarytree.Node | None :return: Height if the binary tree is balanced, -1 otherwise. :rtype: int
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L20-L36
[ "def _is_balanced(root):\n \"\"\"Return the height if the binary tree is balanced, -1 otherwise.\n\n :param root: Root node of the binary tree.\n :type root: binarytree.Node | None\n :return: Height if the binary tree is balanced, -1 otherwise.\n :rtype: int\n \"\"\"\n if root is None:\n return 0\n left = _is_balanced(root.left)\n if left < 0:\n return -1\n right = _is_balanced(root.right)\n if right < 0:\n return -1\n return -1 if abs(left - right) > 1 else max(left, right) + 1\n" ]
from __future__ import absolute_import, unicode_literals, division __all__ = ['Node', 'tree', 'bst', 'heap', 'build'] import heapq import random import numbers from binarytree.exceptions import ( TreeHeightError, NodeValueError, NodeIndexError, NodeTypeError, NodeModifyError, NodeNotFoundError, NodeReferenceError, ) def _is_bst(root, min_value=float('-inf'), max_value=float('inf')): """Check if the binary tree is a BST (binary search tree). :param root: Root node of the binary tree. :type root: binarytree.Node | None :param min_value: Minimum node value seen. :type min_value: int | float :param max_value: Maximum node value seen. :type max_value: int | float :return: True if the binary tree is a BST, False otherwise. :rtype: bool """ if root is None: return True return ( min_value < root.value < max_value and _is_bst(root.left, min_value, root.value) and _is_bst(root.right, root.value, max_value) ) def _validate_tree_height(height): """Check if the height of the binary tree is valid. :param height: Height of the binary tree (must be 0 - 9 inclusive). :type height: int :raise binarytree.exceptions.TreeHeightError: If height is invalid. """ if not (isinstance(height, int) and 0 <= height <= 9): raise TreeHeightError('height must be an int between 0 - 9') def _generate_perfect_bst(height): """Generate a perfect BST (binary search tree) and return its root. :param height: Height of the BST. :type height: int :return: Root node of the BST. :rtype: binarytree.Node """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) return _build_bst_from_sorted_values(node_values) def _build_bst_from_sorted_values(sorted_values): """Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node """ if len(sorted_values) == 0: return None mid_index = len(sorted_values) // 2 root = Node(sorted_values[mid_index]) root.left = _build_bst_from_sorted_values(sorted_values[:mid_index]) root.right = _build_bst_from_sorted_values(sorted_values[mid_index + 1:]) return root def _generate_random_leaf_count(height): """Return a random leaf count for building binary trees. :param height: Height of the binary tree. :type height: int :return: Random leaf count. :rtype: int """ max_leaf_count = 2 ** height half_leaf_count = max_leaf_count // 2 # A very naive way of mimicking normal distribution roll_1 = random.randint(0, half_leaf_count) roll_2 = random.randint(0, max_leaf_count - half_leaf_count) return roll_1 + roll_2 or half_leaf_count def _generate_random_node_values(height): """Return random node values for building binary trees. :param height: Height of the binary tree. :type height: int :return: Randomly generated node values. :rtype: [int] """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) random.shuffle(node_values) return node_values def _build_tree_string(root, curr_index, index=False, delimiter='-'): """Recursively walk down the binary tree and build a pretty-print string. In each recursive call, a "box" of characters visually representing the current (sub)tree is constructed line by line. Each line is padded with whitespaces to ensure all lines in the box have the same length. Then the box, its width, and start-end positions of its root node value repr string (required for drawing branches) are sent up to the parent call. The parent call then combines its left and right sub-boxes to build a larger box etc. :param root: Root node of the binary tree. :type root: binarytree.Node | None :param curr_index: Level-order_ index of the current node (root node is 0). :type curr_index: int :param index: If set to True, include the level-order_ node indexes using the following format: ``{index}{delimiter}{value}`` (default: False). :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: :return: Box of characters visually representing the current subtree, width of the box, and start-end positions of the repr string of the new root node value. :rtype: ([str], int, int, int) .. _Level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ if root is None: return [], 0, 0, 0 line1 = [] line2 = [] if index: node_repr = '{}{}{}'.format(curr_index, delimiter, root.value) else: node_repr = str(root.value) new_root_width = gap_size = len(node_repr) # Get the left and right sub-boxes, their widths, and root repr positions l_box, l_box_width, l_root_start, l_root_end = \ _build_tree_string(root.left, 2 * curr_index + 1, index, delimiter) r_box, r_box_width, r_root_start, r_root_end = \ _build_tree_string(root.right, 2 * curr_index + 2, index, delimiter) # Draw the branch connecting the current root node to the left sub-box # Pad the line with whitespaces where necessary if l_box_width > 0: l_root = (l_root_start + l_root_end) // 2 + 1 line1.append(' ' * (l_root + 1)) line1.append('_' * (l_box_width - l_root)) line2.append(' ' * l_root + '/') line2.append(' ' * (l_box_width - l_root)) new_root_start = l_box_width + 1 gap_size += 1 else: new_root_start = 0 # Draw the representation of the current root node line1.append(node_repr) line2.append(' ' * new_root_width) # Draw the branch connecting the current root node to the right sub-box # Pad the line with whitespaces where necessary if r_box_width > 0: r_root = (r_root_start + r_root_end) // 2 line1.append('_' * r_root) line1.append(' ' * (r_box_width - r_root + 1)) line2.append(' ' * r_root + '\\') line2.append(' ' * (r_box_width - r_root)) gap_size += 1 new_root_end = new_root_start + new_root_width - 1 # Combine the left and right sub-boxes with the branches drawn above gap = ' ' * gap_size new_box = [''.join(line1), ''.join(line2)] for i in range(max(len(l_box), len(r_box))): l_line = l_box[i] if i < len(l_box) else ' ' * l_box_width r_line = r_box[i] if i < len(r_box) else ' ' * r_box_width new_box.append(l_line + gap + r_line) # Return the new box, its width and its root repr positions return new_box, len(new_box[0]), new_root_start, new_root_end def _get_tree_properties(root): """Inspect the binary tree and return its properties (e.g. height). :param root: Root node of the binary tree. :rtype: binarytree.Node :return: Binary tree properties. :rtype: dict """ is_descending = True is_ascending = True min_node_value = root.value max_node_value = root.value size = 0 leaf_count = 0 min_leaf_depth = 0 max_leaf_depth = -1 is_strict = True is_complete = True current_nodes = [root] non_full_node_seen = False while len(current_nodes) > 0: max_leaf_depth += 1 next_nodes = [] for node in current_nodes: size += 1 value = node.value min_node_value = min(value, min_node_value) max_node_value = max(value, max_node_value) # Node is a leaf. if node.left is None and node.right is None: if min_leaf_depth == 0: min_leaf_depth = max_leaf_depth leaf_count += 1 if node.left is not None: if node.left.value > value: is_descending = False elif node.left.value < value: is_ascending = False next_nodes.append(node.left) is_complete = not non_full_node_seen else: non_full_node_seen = True if node.right is not None: if node.right.value > value: is_descending = False elif node.right.value < value: is_ascending = False next_nodes.append(node.right) is_complete = not non_full_node_seen else: non_full_node_seen = True # If we see a node with only one child, it is not strict is_strict &= (node.left is None) == (node.right is None) current_nodes = next_nodes return { 'height': max_leaf_depth, 'size': size, 'is_max_heap': is_complete and is_descending, 'is_min_heap': is_complete and is_ascending, 'is_perfect': leaf_count == 2 ** max_leaf_depth, 'is_strict': is_strict, 'is_complete': is_complete, 'leaf_count': leaf_count, 'min_node_value': min_node_value, 'max_node_value': max_node_value, 'min_leaf_depth': min_leaf_depth, 'max_leaf_depth': max_leaf_depth, } class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result def build(values): """Build a tree from `list representation`_ and return its root node. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :param values: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :type values: [int | float | None] :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.NodeNotFoundError: If the list representation is malformed (e.g. a parent node is missing). **Example**: .. doctest:: >>> from binarytree import build >>> >>> root = build([1, 2, 3, None, 4]) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. doctest:: >>> from binarytree import build >>> >>> root = build([None, 2, 3]) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 0 """ nodes = [None if v is None else Node(v) for v in values] for index in range(1, len(nodes)): node = nodes[index] if node is not None: parent_index = (index - 1) // 2 parent = nodes[parent_index] if parent is None: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) return nodes[0] if nodes else None def tree(height=3, is_perfect=False): """Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary tree may still be generated by chance. :type is_perfect: bool :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import tree >>> >>> root = tree() >>> >>> root.height 3 .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=5, is_perfect=True) >>> >>> root.height 5 >>> root.is_perfect True .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if is_perfect: return build(values) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = random.choice(('left', 'right')) if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def bst(height=3, is_perfect=False): """Generate a random BST (binary search tree) and return its root node. :param height: Height of the BST (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect BST with all levels filled is returned. If set to False, a perfect BST may still be generated by chance. :type is_perfect: bool :return: Root node of the BST. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import bst >>> >>> root = bst() >>> >>> root.height 3 >>> root.is_bst True .. doctest:: >>> from binarytree import bst >>> >>> root = bst(10) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) if is_perfect: return _generate_perfect_bst(height) values = _generate_random_node_values(height) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = 'left' if node.value > value else 'right' if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def heap(height=3, is_max=True, is_perfect=False): """Generate a random heap and return its root node. :param height: Height of the heap (default: 3, range: 0 - 9 inclusive). :type height: int :param is_max: If set to True (default: True), generate a max heap. If set to False, generate a min heap. A binary tree with only the root node is considered both a min and max heap. :type is_max: bool :param is_perfect: If set to True (default: False), a perfect heap with all levels filled is returned. If set to False, a perfect heap may still be generated by chance. :type is_perfect: bool :return: Root node of the heap. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import heap >>> >>> root = heap() >>> >>> root.height 3 >>> root.is_max_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(4, is_max=False) >>> >>> root.height 4 >>> root.is_min_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(5, is_max=False, is_perfect=True) >>> >>> root.height 5 >>> root.is_min_heap True >>> root.is_perfect True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(-1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if not is_perfect: # Randomly cut some of the leaf nodes away random_cut = random.randint(2 ** height, len(values)) values = values[:random_cut] if is_max: negated = [-v for v in values] heapq.heapify(negated) return build([-v for v in negated]) else: heapq.heapify(values) return build(values)
joowani/binarytree
binarytree/__init__.py
_is_bst
python
def _is_bst(root, min_value=float('-inf'), max_value=float('inf')): if root is None: return True return ( min_value < root.value < max_value and _is_bst(root.left, min_value, root.value) and _is_bst(root.right, root.value, max_value) )
Check if the binary tree is a BST (binary search tree). :param root: Root node of the binary tree. :type root: binarytree.Node | None :param min_value: Minimum node value seen. :type min_value: int | float :param max_value: Maximum node value seen. :type max_value: int | float :return: True if the binary tree is a BST, False otherwise. :rtype: bool
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L39-L57
[ "def _is_bst(root, min_value=float('-inf'), max_value=float('inf')):\n \"\"\"Check if the binary tree is a BST (binary search tree).\n\n :param root: Root node of the binary tree.\n :type root: binarytree.Node | None\n :param min_value: Minimum node value seen.\n :type min_value: int | float\n :param max_value: Maximum node value seen.\n :type max_value: int | float\n :return: True if the binary tree is a BST, False otherwise.\n :rtype: bool\n \"\"\"\n if root is None:\n return True\n return (\n min_value < root.value < max_value and\n _is_bst(root.left, min_value, root.value) and\n _is_bst(root.right, root.value, max_value)\n )\n" ]
from __future__ import absolute_import, unicode_literals, division __all__ = ['Node', 'tree', 'bst', 'heap', 'build'] import heapq import random import numbers from binarytree.exceptions import ( TreeHeightError, NodeValueError, NodeIndexError, NodeTypeError, NodeModifyError, NodeNotFoundError, NodeReferenceError, ) def _is_balanced(root): """Return the height if the binary tree is balanced, -1 otherwise. :param root: Root node of the binary tree. :type root: binarytree.Node | None :return: Height if the binary tree is balanced, -1 otherwise. :rtype: int """ if root is None: return 0 left = _is_balanced(root.left) if left < 0: return -1 right = _is_balanced(root.right) if right < 0: return -1 return -1 if abs(left - right) > 1 else max(left, right) + 1 def _validate_tree_height(height): """Check if the height of the binary tree is valid. :param height: Height of the binary tree (must be 0 - 9 inclusive). :type height: int :raise binarytree.exceptions.TreeHeightError: If height is invalid. """ if not (isinstance(height, int) and 0 <= height <= 9): raise TreeHeightError('height must be an int between 0 - 9') def _generate_perfect_bst(height): """Generate a perfect BST (binary search tree) and return its root. :param height: Height of the BST. :type height: int :return: Root node of the BST. :rtype: binarytree.Node """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) return _build_bst_from_sorted_values(node_values) def _build_bst_from_sorted_values(sorted_values): """Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node """ if len(sorted_values) == 0: return None mid_index = len(sorted_values) // 2 root = Node(sorted_values[mid_index]) root.left = _build_bst_from_sorted_values(sorted_values[:mid_index]) root.right = _build_bst_from_sorted_values(sorted_values[mid_index + 1:]) return root def _generate_random_leaf_count(height): """Return a random leaf count for building binary trees. :param height: Height of the binary tree. :type height: int :return: Random leaf count. :rtype: int """ max_leaf_count = 2 ** height half_leaf_count = max_leaf_count // 2 # A very naive way of mimicking normal distribution roll_1 = random.randint(0, half_leaf_count) roll_2 = random.randint(0, max_leaf_count - half_leaf_count) return roll_1 + roll_2 or half_leaf_count def _generate_random_node_values(height): """Return random node values for building binary trees. :param height: Height of the binary tree. :type height: int :return: Randomly generated node values. :rtype: [int] """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) random.shuffle(node_values) return node_values def _build_tree_string(root, curr_index, index=False, delimiter='-'): """Recursively walk down the binary tree and build a pretty-print string. In each recursive call, a "box" of characters visually representing the current (sub)tree is constructed line by line. Each line is padded with whitespaces to ensure all lines in the box have the same length. Then the box, its width, and start-end positions of its root node value repr string (required for drawing branches) are sent up to the parent call. The parent call then combines its left and right sub-boxes to build a larger box etc. :param root: Root node of the binary tree. :type root: binarytree.Node | None :param curr_index: Level-order_ index of the current node (root node is 0). :type curr_index: int :param index: If set to True, include the level-order_ node indexes using the following format: ``{index}{delimiter}{value}`` (default: False). :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: :return: Box of characters visually representing the current subtree, width of the box, and start-end positions of the repr string of the new root node value. :rtype: ([str], int, int, int) .. _Level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ if root is None: return [], 0, 0, 0 line1 = [] line2 = [] if index: node_repr = '{}{}{}'.format(curr_index, delimiter, root.value) else: node_repr = str(root.value) new_root_width = gap_size = len(node_repr) # Get the left and right sub-boxes, their widths, and root repr positions l_box, l_box_width, l_root_start, l_root_end = \ _build_tree_string(root.left, 2 * curr_index + 1, index, delimiter) r_box, r_box_width, r_root_start, r_root_end = \ _build_tree_string(root.right, 2 * curr_index + 2, index, delimiter) # Draw the branch connecting the current root node to the left sub-box # Pad the line with whitespaces where necessary if l_box_width > 0: l_root = (l_root_start + l_root_end) // 2 + 1 line1.append(' ' * (l_root + 1)) line1.append('_' * (l_box_width - l_root)) line2.append(' ' * l_root + '/') line2.append(' ' * (l_box_width - l_root)) new_root_start = l_box_width + 1 gap_size += 1 else: new_root_start = 0 # Draw the representation of the current root node line1.append(node_repr) line2.append(' ' * new_root_width) # Draw the branch connecting the current root node to the right sub-box # Pad the line with whitespaces where necessary if r_box_width > 0: r_root = (r_root_start + r_root_end) // 2 line1.append('_' * r_root) line1.append(' ' * (r_box_width - r_root + 1)) line2.append(' ' * r_root + '\\') line2.append(' ' * (r_box_width - r_root)) gap_size += 1 new_root_end = new_root_start + new_root_width - 1 # Combine the left and right sub-boxes with the branches drawn above gap = ' ' * gap_size new_box = [''.join(line1), ''.join(line2)] for i in range(max(len(l_box), len(r_box))): l_line = l_box[i] if i < len(l_box) else ' ' * l_box_width r_line = r_box[i] if i < len(r_box) else ' ' * r_box_width new_box.append(l_line + gap + r_line) # Return the new box, its width and its root repr positions return new_box, len(new_box[0]), new_root_start, new_root_end def _get_tree_properties(root): """Inspect the binary tree and return its properties (e.g. height). :param root: Root node of the binary tree. :rtype: binarytree.Node :return: Binary tree properties. :rtype: dict """ is_descending = True is_ascending = True min_node_value = root.value max_node_value = root.value size = 0 leaf_count = 0 min_leaf_depth = 0 max_leaf_depth = -1 is_strict = True is_complete = True current_nodes = [root] non_full_node_seen = False while len(current_nodes) > 0: max_leaf_depth += 1 next_nodes = [] for node in current_nodes: size += 1 value = node.value min_node_value = min(value, min_node_value) max_node_value = max(value, max_node_value) # Node is a leaf. if node.left is None and node.right is None: if min_leaf_depth == 0: min_leaf_depth = max_leaf_depth leaf_count += 1 if node.left is not None: if node.left.value > value: is_descending = False elif node.left.value < value: is_ascending = False next_nodes.append(node.left) is_complete = not non_full_node_seen else: non_full_node_seen = True if node.right is not None: if node.right.value > value: is_descending = False elif node.right.value < value: is_ascending = False next_nodes.append(node.right) is_complete = not non_full_node_seen else: non_full_node_seen = True # If we see a node with only one child, it is not strict is_strict &= (node.left is None) == (node.right is None) current_nodes = next_nodes return { 'height': max_leaf_depth, 'size': size, 'is_max_heap': is_complete and is_descending, 'is_min_heap': is_complete and is_ascending, 'is_perfect': leaf_count == 2 ** max_leaf_depth, 'is_strict': is_strict, 'is_complete': is_complete, 'leaf_count': leaf_count, 'min_node_value': min_node_value, 'max_node_value': max_node_value, 'min_leaf_depth': min_leaf_depth, 'max_leaf_depth': max_leaf_depth, } class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result def build(values): """Build a tree from `list representation`_ and return its root node. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :param values: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :type values: [int | float | None] :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.NodeNotFoundError: If the list representation is malformed (e.g. a parent node is missing). **Example**: .. doctest:: >>> from binarytree import build >>> >>> root = build([1, 2, 3, None, 4]) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. doctest:: >>> from binarytree import build >>> >>> root = build([None, 2, 3]) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 0 """ nodes = [None if v is None else Node(v) for v in values] for index in range(1, len(nodes)): node = nodes[index] if node is not None: parent_index = (index - 1) // 2 parent = nodes[parent_index] if parent is None: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) return nodes[0] if nodes else None def tree(height=3, is_perfect=False): """Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary tree may still be generated by chance. :type is_perfect: bool :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import tree >>> >>> root = tree() >>> >>> root.height 3 .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=5, is_perfect=True) >>> >>> root.height 5 >>> root.is_perfect True .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if is_perfect: return build(values) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = random.choice(('left', 'right')) if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def bst(height=3, is_perfect=False): """Generate a random BST (binary search tree) and return its root node. :param height: Height of the BST (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect BST with all levels filled is returned. If set to False, a perfect BST may still be generated by chance. :type is_perfect: bool :return: Root node of the BST. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import bst >>> >>> root = bst() >>> >>> root.height 3 >>> root.is_bst True .. doctest:: >>> from binarytree import bst >>> >>> root = bst(10) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) if is_perfect: return _generate_perfect_bst(height) values = _generate_random_node_values(height) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = 'left' if node.value > value else 'right' if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def heap(height=3, is_max=True, is_perfect=False): """Generate a random heap and return its root node. :param height: Height of the heap (default: 3, range: 0 - 9 inclusive). :type height: int :param is_max: If set to True (default: True), generate a max heap. If set to False, generate a min heap. A binary tree with only the root node is considered both a min and max heap. :type is_max: bool :param is_perfect: If set to True (default: False), a perfect heap with all levels filled is returned. If set to False, a perfect heap may still be generated by chance. :type is_perfect: bool :return: Root node of the heap. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import heap >>> >>> root = heap() >>> >>> root.height 3 >>> root.is_max_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(4, is_max=False) >>> >>> root.height 4 >>> root.is_min_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(5, is_max=False, is_perfect=True) >>> >>> root.height 5 >>> root.is_min_heap True >>> root.is_perfect True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(-1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if not is_perfect: # Randomly cut some of the leaf nodes away random_cut = random.randint(2 ** height, len(values)) values = values[:random_cut] if is_max: negated = [-v for v in values] heapq.heapify(negated) return build([-v for v in negated]) else: heapq.heapify(values) return build(values)
joowani/binarytree
binarytree/__init__.py
_generate_perfect_bst
python
def _generate_perfect_bst(height): max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) return _build_bst_from_sorted_values(node_values)
Generate a perfect BST (binary search tree) and return its root. :param height: Height of the BST. :type height: int :return: Root node of the BST. :rtype: binarytree.Node
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L71-L81
[ "def _build_bst_from_sorted_values(sorted_values):\n \"\"\"Recursively build a perfect BST from odd number of sorted values.\n\n :param sorted_values: Odd number of sorted values.\n :type sorted_values: [int | float]\n :return: Root node of the BST.\n :rtype: binarytree.Node\n \"\"\"\n if len(sorted_values) == 0:\n return None\n mid_index = len(sorted_values) // 2\n root = Node(sorted_values[mid_index])\n root.left = _build_bst_from_sorted_values(sorted_values[:mid_index])\n root.right = _build_bst_from_sorted_values(sorted_values[mid_index + 1:])\n return root\n" ]
from __future__ import absolute_import, unicode_literals, division __all__ = ['Node', 'tree', 'bst', 'heap', 'build'] import heapq import random import numbers from binarytree.exceptions import ( TreeHeightError, NodeValueError, NodeIndexError, NodeTypeError, NodeModifyError, NodeNotFoundError, NodeReferenceError, ) def _is_balanced(root): """Return the height if the binary tree is balanced, -1 otherwise. :param root: Root node of the binary tree. :type root: binarytree.Node | None :return: Height if the binary tree is balanced, -1 otherwise. :rtype: int """ if root is None: return 0 left = _is_balanced(root.left) if left < 0: return -1 right = _is_balanced(root.right) if right < 0: return -1 return -1 if abs(left - right) > 1 else max(left, right) + 1 def _is_bst(root, min_value=float('-inf'), max_value=float('inf')): """Check if the binary tree is a BST (binary search tree). :param root: Root node of the binary tree. :type root: binarytree.Node | None :param min_value: Minimum node value seen. :type min_value: int | float :param max_value: Maximum node value seen. :type max_value: int | float :return: True if the binary tree is a BST, False otherwise. :rtype: bool """ if root is None: return True return ( min_value < root.value < max_value and _is_bst(root.left, min_value, root.value) and _is_bst(root.right, root.value, max_value) ) def _validate_tree_height(height): """Check if the height of the binary tree is valid. :param height: Height of the binary tree (must be 0 - 9 inclusive). :type height: int :raise binarytree.exceptions.TreeHeightError: If height is invalid. """ if not (isinstance(height, int) and 0 <= height <= 9): raise TreeHeightError('height must be an int between 0 - 9') def _build_bst_from_sorted_values(sorted_values): """Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node """ if len(sorted_values) == 0: return None mid_index = len(sorted_values) // 2 root = Node(sorted_values[mid_index]) root.left = _build_bst_from_sorted_values(sorted_values[:mid_index]) root.right = _build_bst_from_sorted_values(sorted_values[mid_index + 1:]) return root def _generate_random_leaf_count(height): """Return a random leaf count for building binary trees. :param height: Height of the binary tree. :type height: int :return: Random leaf count. :rtype: int """ max_leaf_count = 2 ** height half_leaf_count = max_leaf_count // 2 # A very naive way of mimicking normal distribution roll_1 = random.randint(0, half_leaf_count) roll_2 = random.randint(0, max_leaf_count - half_leaf_count) return roll_1 + roll_2 or half_leaf_count def _generate_random_node_values(height): """Return random node values for building binary trees. :param height: Height of the binary tree. :type height: int :return: Randomly generated node values. :rtype: [int] """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) random.shuffle(node_values) return node_values def _build_tree_string(root, curr_index, index=False, delimiter='-'): """Recursively walk down the binary tree and build a pretty-print string. In each recursive call, a "box" of characters visually representing the current (sub)tree is constructed line by line. Each line is padded with whitespaces to ensure all lines in the box have the same length. Then the box, its width, and start-end positions of its root node value repr string (required for drawing branches) are sent up to the parent call. The parent call then combines its left and right sub-boxes to build a larger box etc. :param root: Root node of the binary tree. :type root: binarytree.Node | None :param curr_index: Level-order_ index of the current node (root node is 0). :type curr_index: int :param index: If set to True, include the level-order_ node indexes using the following format: ``{index}{delimiter}{value}`` (default: False). :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: :return: Box of characters visually representing the current subtree, width of the box, and start-end positions of the repr string of the new root node value. :rtype: ([str], int, int, int) .. _Level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ if root is None: return [], 0, 0, 0 line1 = [] line2 = [] if index: node_repr = '{}{}{}'.format(curr_index, delimiter, root.value) else: node_repr = str(root.value) new_root_width = gap_size = len(node_repr) # Get the left and right sub-boxes, their widths, and root repr positions l_box, l_box_width, l_root_start, l_root_end = \ _build_tree_string(root.left, 2 * curr_index + 1, index, delimiter) r_box, r_box_width, r_root_start, r_root_end = \ _build_tree_string(root.right, 2 * curr_index + 2, index, delimiter) # Draw the branch connecting the current root node to the left sub-box # Pad the line with whitespaces where necessary if l_box_width > 0: l_root = (l_root_start + l_root_end) // 2 + 1 line1.append(' ' * (l_root + 1)) line1.append('_' * (l_box_width - l_root)) line2.append(' ' * l_root + '/') line2.append(' ' * (l_box_width - l_root)) new_root_start = l_box_width + 1 gap_size += 1 else: new_root_start = 0 # Draw the representation of the current root node line1.append(node_repr) line2.append(' ' * new_root_width) # Draw the branch connecting the current root node to the right sub-box # Pad the line with whitespaces where necessary if r_box_width > 0: r_root = (r_root_start + r_root_end) // 2 line1.append('_' * r_root) line1.append(' ' * (r_box_width - r_root + 1)) line2.append(' ' * r_root + '\\') line2.append(' ' * (r_box_width - r_root)) gap_size += 1 new_root_end = new_root_start + new_root_width - 1 # Combine the left and right sub-boxes with the branches drawn above gap = ' ' * gap_size new_box = [''.join(line1), ''.join(line2)] for i in range(max(len(l_box), len(r_box))): l_line = l_box[i] if i < len(l_box) else ' ' * l_box_width r_line = r_box[i] if i < len(r_box) else ' ' * r_box_width new_box.append(l_line + gap + r_line) # Return the new box, its width and its root repr positions return new_box, len(new_box[0]), new_root_start, new_root_end def _get_tree_properties(root): """Inspect the binary tree and return its properties (e.g. height). :param root: Root node of the binary tree. :rtype: binarytree.Node :return: Binary tree properties. :rtype: dict """ is_descending = True is_ascending = True min_node_value = root.value max_node_value = root.value size = 0 leaf_count = 0 min_leaf_depth = 0 max_leaf_depth = -1 is_strict = True is_complete = True current_nodes = [root] non_full_node_seen = False while len(current_nodes) > 0: max_leaf_depth += 1 next_nodes = [] for node in current_nodes: size += 1 value = node.value min_node_value = min(value, min_node_value) max_node_value = max(value, max_node_value) # Node is a leaf. if node.left is None and node.right is None: if min_leaf_depth == 0: min_leaf_depth = max_leaf_depth leaf_count += 1 if node.left is not None: if node.left.value > value: is_descending = False elif node.left.value < value: is_ascending = False next_nodes.append(node.left) is_complete = not non_full_node_seen else: non_full_node_seen = True if node.right is not None: if node.right.value > value: is_descending = False elif node.right.value < value: is_ascending = False next_nodes.append(node.right) is_complete = not non_full_node_seen else: non_full_node_seen = True # If we see a node with only one child, it is not strict is_strict &= (node.left is None) == (node.right is None) current_nodes = next_nodes return { 'height': max_leaf_depth, 'size': size, 'is_max_heap': is_complete and is_descending, 'is_min_heap': is_complete and is_ascending, 'is_perfect': leaf_count == 2 ** max_leaf_depth, 'is_strict': is_strict, 'is_complete': is_complete, 'leaf_count': leaf_count, 'min_node_value': min_node_value, 'max_node_value': max_node_value, 'min_leaf_depth': min_leaf_depth, 'max_leaf_depth': max_leaf_depth, } class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result def build(values): """Build a tree from `list representation`_ and return its root node. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :param values: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :type values: [int | float | None] :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.NodeNotFoundError: If the list representation is malformed (e.g. a parent node is missing). **Example**: .. doctest:: >>> from binarytree import build >>> >>> root = build([1, 2, 3, None, 4]) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. doctest:: >>> from binarytree import build >>> >>> root = build([None, 2, 3]) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 0 """ nodes = [None if v is None else Node(v) for v in values] for index in range(1, len(nodes)): node = nodes[index] if node is not None: parent_index = (index - 1) // 2 parent = nodes[parent_index] if parent is None: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) return nodes[0] if nodes else None def tree(height=3, is_perfect=False): """Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary tree may still be generated by chance. :type is_perfect: bool :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import tree >>> >>> root = tree() >>> >>> root.height 3 .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=5, is_perfect=True) >>> >>> root.height 5 >>> root.is_perfect True .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if is_perfect: return build(values) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = random.choice(('left', 'right')) if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def bst(height=3, is_perfect=False): """Generate a random BST (binary search tree) and return its root node. :param height: Height of the BST (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect BST with all levels filled is returned. If set to False, a perfect BST may still be generated by chance. :type is_perfect: bool :return: Root node of the BST. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import bst >>> >>> root = bst() >>> >>> root.height 3 >>> root.is_bst True .. doctest:: >>> from binarytree import bst >>> >>> root = bst(10) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) if is_perfect: return _generate_perfect_bst(height) values = _generate_random_node_values(height) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = 'left' if node.value > value else 'right' if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def heap(height=3, is_max=True, is_perfect=False): """Generate a random heap and return its root node. :param height: Height of the heap (default: 3, range: 0 - 9 inclusive). :type height: int :param is_max: If set to True (default: True), generate a max heap. If set to False, generate a min heap. A binary tree with only the root node is considered both a min and max heap. :type is_max: bool :param is_perfect: If set to True (default: False), a perfect heap with all levels filled is returned. If set to False, a perfect heap may still be generated by chance. :type is_perfect: bool :return: Root node of the heap. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import heap >>> >>> root = heap() >>> >>> root.height 3 >>> root.is_max_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(4, is_max=False) >>> >>> root.height 4 >>> root.is_min_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(5, is_max=False, is_perfect=True) >>> >>> root.height 5 >>> root.is_min_heap True >>> root.is_perfect True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(-1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if not is_perfect: # Randomly cut some of the leaf nodes away random_cut = random.randint(2 ** height, len(values)) values = values[:random_cut] if is_max: negated = [-v for v in values] heapq.heapify(negated) return build([-v for v in negated]) else: heapq.heapify(values) return build(values)
joowani/binarytree
binarytree/__init__.py
_build_bst_from_sorted_values
python
def _build_bst_from_sorted_values(sorted_values): if len(sorted_values) == 0: return None mid_index = len(sorted_values) // 2 root = Node(sorted_values[mid_index]) root.left = _build_bst_from_sorted_values(sorted_values[:mid_index]) root.right = _build_bst_from_sorted_values(sorted_values[mid_index + 1:]) return root
Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L84-L98
null
from __future__ import absolute_import, unicode_literals, division __all__ = ['Node', 'tree', 'bst', 'heap', 'build'] import heapq import random import numbers from binarytree.exceptions import ( TreeHeightError, NodeValueError, NodeIndexError, NodeTypeError, NodeModifyError, NodeNotFoundError, NodeReferenceError, ) def _is_balanced(root): """Return the height if the binary tree is balanced, -1 otherwise. :param root: Root node of the binary tree. :type root: binarytree.Node | None :return: Height if the binary tree is balanced, -1 otherwise. :rtype: int """ if root is None: return 0 left = _is_balanced(root.left) if left < 0: return -1 right = _is_balanced(root.right) if right < 0: return -1 return -1 if abs(left - right) > 1 else max(left, right) + 1 def _is_bst(root, min_value=float('-inf'), max_value=float('inf')): """Check if the binary tree is a BST (binary search tree). :param root: Root node of the binary tree. :type root: binarytree.Node | None :param min_value: Minimum node value seen. :type min_value: int | float :param max_value: Maximum node value seen. :type max_value: int | float :return: True if the binary tree is a BST, False otherwise. :rtype: bool """ if root is None: return True return ( min_value < root.value < max_value and _is_bst(root.left, min_value, root.value) and _is_bst(root.right, root.value, max_value) ) def _validate_tree_height(height): """Check if the height of the binary tree is valid. :param height: Height of the binary tree (must be 0 - 9 inclusive). :type height: int :raise binarytree.exceptions.TreeHeightError: If height is invalid. """ if not (isinstance(height, int) and 0 <= height <= 9): raise TreeHeightError('height must be an int between 0 - 9') def _generate_perfect_bst(height): """Generate a perfect BST (binary search tree) and return its root. :param height: Height of the BST. :type height: int :return: Root node of the BST. :rtype: binarytree.Node """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) return _build_bst_from_sorted_values(node_values) def _generate_random_leaf_count(height): """Return a random leaf count for building binary trees. :param height: Height of the binary tree. :type height: int :return: Random leaf count. :rtype: int """ max_leaf_count = 2 ** height half_leaf_count = max_leaf_count // 2 # A very naive way of mimicking normal distribution roll_1 = random.randint(0, half_leaf_count) roll_2 = random.randint(0, max_leaf_count - half_leaf_count) return roll_1 + roll_2 or half_leaf_count def _generate_random_node_values(height): """Return random node values for building binary trees. :param height: Height of the binary tree. :type height: int :return: Randomly generated node values. :rtype: [int] """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) random.shuffle(node_values) return node_values def _build_tree_string(root, curr_index, index=False, delimiter='-'): """Recursively walk down the binary tree and build a pretty-print string. In each recursive call, a "box" of characters visually representing the current (sub)tree is constructed line by line. Each line is padded with whitespaces to ensure all lines in the box have the same length. Then the box, its width, and start-end positions of its root node value repr string (required for drawing branches) are sent up to the parent call. The parent call then combines its left and right sub-boxes to build a larger box etc. :param root: Root node of the binary tree. :type root: binarytree.Node | None :param curr_index: Level-order_ index of the current node (root node is 0). :type curr_index: int :param index: If set to True, include the level-order_ node indexes using the following format: ``{index}{delimiter}{value}`` (default: False). :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: :return: Box of characters visually representing the current subtree, width of the box, and start-end positions of the repr string of the new root node value. :rtype: ([str], int, int, int) .. _Level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ if root is None: return [], 0, 0, 0 line1 = [] line2 = [] if index: node_repr = '{}{}{}'.format(curr_index, delimiter, root.value) else: node_repr = str(root.value) new_root_width = gap_size = len(node_repr) # Get the left and right sub-boxes, their widths, and root repr positions l_box, l_box_width, l_root_start, l_root_end = \ _build_tree_string(root.left, 2 * curr_index + 1, index, delimiter) r_box, r_box_width, r_root_start, r_root_end = \ _build_tree_string(root.right, 2 * curr_index + 2, index, delimiter) # Draw the branch connecting the current root node to the left sub-box # Pad the line with whitespaces where necessary if l_box_width > 0: l_root = (l_root_start + l_root_end) // 2 + 1 line1.append(' ' * (l_root + 1)) line1.append('_' * (l_box_width - l_root)) line2.append(' ' * l_root + '/') line2.append(' ' * (l_box_width - l_root)) new_root_start = l_box_width + 1 gap_size += 1 else: new_root_start = 0 # Draw the representation of the current root node line1.append(node_repr) line2.append(' ' * new_root_width) # Draw the branch connecting the current root node to the right sub-box # Pad the line with whitespaces where necessary if r_box_width > 0: r_root = (r_root_start + r_root_end) // 2 line1.append('_' * r_root) line1.append(' ' * (r_box_width - r_root + 1)) line2.append(' ' * r_root + '\\') line2.append(' ' * (r_box_width - r_root)) gap_size += 1 new_root_end = new_root_start + new_root_width - 1 # Combine the left and right sub-boxes with the branches drawn above gap = ' ' * gap_size new_box = [''.join(line1), ''.join(line2)] for i in range(max(len(l_box), len(r_box))): l_line = l_box[i] if i < len(l_box) else ' ' * l_box_width r_line = r_box[i] if i < len(r_box) else ' ' * r_box_width new_box.append(l_line + gap + r_line) # Return the new box, its width and its root repr positions return new_box, len(new_box[0]), new_root_start, new_root_end def _get_tree_properties(root): """Inspect the binary tree and return its properties (e.g. height). :param root: Root node of the binary tree. :rtype: binarytree.Node :return: Binary tree properties. :rtype: dict """ is_descending = True is_ascending = True min_node_value = root.value max_node_value = root.value size = 0 leaf_count = 0 min_leaf_depth = 0 max_leaf_depth = -1 is_strict = True is_complete = True current_nodes = [root] non_full_node_seen = False while len(current_nodes) > 0: max_leaf_depth += 1 next_nodes = [] for node in current_nodes: size += 1 value = node.value min_node_value = min(value, min_node_value) max_node_value = max(value, max_node_value) # Node is a leaf. if node.left is None and node.right is None: if min_leaf_depth == 0: min_leaf_depth = max_leaf_depth leaf_count += 1 if node.left is not None: if node.left.value > value: is_descending = False elif node.left.value < value: is_ascending = False next_nodes.append(node.left) is_complete = not non_full_node_seen else: non_full_node_seen = True if node.right is not None: if node.right.value > value: is_descending = False elif node.right.value < value: is_ascending = False next_nodes.append(node.right) is_complete = not non_full_node_seen else: non_full_node_seen = True # If we see a node with only one child, it is not strict is_strict &= (node.left is None) == (node.right is None) current_nodes = next_nodes return { 'height': max_leaf_depth, 'size': size, 'is_max_heap': is_complete and is_descending, 'is_min_heap': is_complete and is_ascending, 'is_perfect': leaf_count == 2 ** max_leaf_depth, 'is_strict': is_strict, 'is_complete': is_complete, 'leaf_count': leaf_count, 'min_node_value': min_node_value, 'max_node_value': max_node_value, 'min_leaf_depth': min_leaf_depth, 'max_leaf_depth': max_leaf_depth, } class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result def build(values): """Build a tree from `list representation`_ and return its root node. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :param values: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :type values: [int | float | None] :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.NodeNotFoundError: If the list representation is malformed (e.g. a parent node is missing). **Example**: .. doctest:: >>> from binarytree import build >>> >>> root = build([1, 2, 3, None, 4]) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. doctest:: >>> from binarytree import build >>> >>> root = build([None, 2, 3]) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 0 """ nodes = [None if v is None else Node(v) for v in values] for index in range(1, len(nodes)): node = nodes[index] if node is not None: parent_index = (index - 1) // 2 parent = nodes[parent_index] if parent is None: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) return nodes[0] if nodes else None def tree(height=3, is_perfect=False): """Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary tree may still be generated by chance. :type is_perfect: bool :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import tree >>> >>> root = tree() >>> >>> root.height 3 .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=5, is_perfect=True) >>> >>> root.height 5 >>> root.is_perfect True .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if is_perfect: return build(values) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = random.choice(('left', 'right')) if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def bst(height=3, is_perfect=False): """Generate a random BST (binary search tree) and return its root node. :param height: Height of the BST (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect BST with all levels filled is returned. If set to False, a perfect BST may still be generated by chance. :type is_perfect: bool :return: Root node of the BST. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import bst >>> >>> root = bst() >>> >>> root.height 3 >>> root.is_bst True .. doctest:: >>> from binarytree import bst >>> >>> root = bst(10) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) if is_perfect: return _generate_perfect_bst(height) values = _generate_random_node_values(height) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = 'left' if node.value > value else 'right' if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def heap(height=3, is_max=True, is_perfect=False): """Generate a random heap and return its root node. :param height: Height of the heap (default: 3, range: 0 - 9 inclusive). :type height: int :param is_max: If set to True (default: True), generate a max heap. If set to False, generate a min heap. A binary tree with only the root node is considered both a min and max heap. :type is_max: bool :param is_perfect: If set to True (default: False), a perfect heap with all levels filled is returned. If set to False, a perfect heap may still be generated by chance. :type is_perfect: bool :return: Root node of the heap. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import heap >>> >>> root = heap() >>> >>> root.height 3 >>> root.is_max_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(4, is_max=False) >>> >>> root.height 4 >>> root.is_min_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(5, is_max=False, is_perfect=True) >>> >>> root.height 5 >>> root.is_min_heap True >>> root.is_perfect True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(-1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if not is_perfect: # Randomly cut some of the leaf nodes away random_cut = random.randint(2 ** height, len(values)) values = values[:random_cut] if is_max: negated = [-v for v in values] heapq.heapify(negated) return build([-v for v in negated]) else: heapq.heapify(values) return build(values)
joowani/binarytree
binarytree/__init__.py
_generate_random_leaf_count
python
def _generate_random_leaf_count(height): max_leaf_count = 2 ** height half_leaf_count = max_leaf_count // 2 # A very naive way of mimicking normal distribution roll_1 = random.randint(0, half_leaf_count) roll_2 = random.randint(0, max_leaf_count - half_leaf_count) return roll_1 + roll_2 or half_leaf_count
Return a random leaf count for building binary trees. :param height: Height of the binary tree. :type height: int :return: Random leaf count. :rtype: int
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L101-L115
null
from __future__ import absolute_import, unicode_literals, division __all__ = ['Node', 'tree', 'bst', 'heap', 'build'] import heapq import random import numbers from binarytree.exceptions import ( TreeHeightError, NodeValueError, NodeIndexError, NodeTypeError, NodeModifyError, NodeNotFoundError, NodeReferenceError, ) def _is_balanced(root): """Return the height if the binary tree is balanced, -1 otherwise. :param root: Root node of the binary tree. :type root: binarytree.Node | None :return: Height if the binary tree is balanced, -1 otherwise. :rtype: int """ if root is None: return 0 left = _is_balanced(root.left) if left < 0: return -1 right = _is_balanced(root.right) if right < 0: return -1 return -1 if abs(left - right) > 1 else max(left, right) + 1 def _is_bst(root, min_value=float('-inf'), max_value=float('inf')): """Check if the binary tree is a BST (binary search tree). :param root: Root node of the binary tree. :type root: binarytree.Node | None :param min_value: Minimum node value seen. :type min_value: int | float :param max_value: Maximum node value seen. :type max_value: int | float :return: True if the binary tree is a BST, False otherwise. :rtype: bool """ if root is None: return True return ( min_value < root.value < max_value and _is_bst(root.left, min_value, root.value) and _is_bst(root.right, root.value, max_value) ) def _validate_tree_height(height): """Check if the height of the binary tree is valid. :param height: Height of the binary tree (must be 0 - 9 inclusive). :type height: int :raise binarytree.exceptions.TreeHeightError: If height is invalid. """ if not (isinstance(height, int) and 0 <= height <= 9): raise TreeHeightError('height must be an int between 0 - 9') def _generate_perfect_bst(height): """Generate a perfect BST (binary search tree) and return its root. :param height: Height of the BST. :type height: int :return: Root node of the BST. :rtype: binarytree.Node """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) return _build_bst_from_sorted_values(node_values) def _build_bst_from_sorted_values(sorted_values): """Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node """ if len(sorted_values) == 0: return None mid_index = len(sorted_values) // 2 root = Node(sorted_values[mid_index]) root.left = _build_bst_from_sorted_values(sorted_values[:mid_index]) root.right = _build_bst_from_sorted_values(sorted_values[mid_index + 1:]) return root def _generate_random_node_values(height): """Return random node values for building binary trees. :param height: Height of the binary tree. :type height: int :return: Randomly generated node values. :rtype: [int] """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) random.shuffle(node_values) return node_values def _build_tree_string(root, curr_index, index=False, delimiter='-'): """Recursively walk down the binary tree and build a pretty-print string. In each recursive call, a "box" of characters visually representing the current (sub)tree is constructed line by line. Each line is padded with whitespaces to ensure all lines in the box have the same length. Then the box, its width, and start-end positions of its root node value repr string (required for drawing branches) are sent up to the parent call. The parent call then combines its left and right sub-boxes to build a larger box etc. :param root: Root node of the binary tree. :type root: binarytree.Node | None :param curr_index: Level-order_ index of the current node (root node is 0). :type curr_index: int :param index: If set to True, include the level-order_ node indexes using the following format: ``{index}{delimiter}{value}`` (default: False). :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: :return: Box of characters visually representing the current subtree, width of the box, and start-end positions of the repr string of the new root node value. :rtype: ([str], int, int, int) .. _Level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ if root is None: return [], 0, 0, 0 line1 = [] line2 = [] if index: node_repr = '{}{}{}'.format(curr_index, delimiter, root.value) else: node_repr = str(root.value) new_root_width = gap_size = len(node_repr) # Get the left and right sub-boxes, their widths, and root repr positions l_box, l_box_width, l_root_start, l_root_end = \ _build_tree_string(root.left, 2 * curr_index + 1, index, delimiter) r_box, r_box_width, r_root_start, r_root_end = \ _build_tree_string(root.right, 2 * curr_index + 2, index, delimiter) # Draw the branch connecting the current root node to the left sub-box # Pad the line with whitespaces where necessary if l_box_width > 0: l_root = (l_root_start + l_root_end) // 2 + 1 line1.append(' ' * (l_root + 1)) line1.append('_' * (l_box_width - l_root)) line2.append(' ' * l_root + '/') line2.append(' ' * (l_box_width - l_root)) new_root_start = l_box_width + 1 gap_size += 1 else: new_root_start = 0 # Draw the representation of the current root node line1.append(node_repr) line2.append(' ' * new_root_width) # Draw the branch connecting the current root node to the right sub-box # Pad the line with whitespaces where necessary if r_box_width > 0: r_root = (r_root_start + r_root_end) // 2 line1.append('_' * r_root) line1.append(' ' * (r_box_width - r_root + 1)) line2.append(' ' * r_root + '\\') line2.append(' ' * (r_box_width - r_root)) gap_size += 1 new_root_end = new_root_start + new_root_width - 1 # Combine the left and right sub-boxes with the branches drawn above gap = ' ' * gap_size new_box = [''.join(line1), ''.join(line2)] for i in range(max(len(l_box), len(r_box))): l_line = l_box[i] if i < len(l_box) else ' ' * l_box_width r_line = r_box[i] if i < len(r_box) else ' ' * r_box_width new_box.append(l_line + gap + r_line) # Return the new box, its width and its root repr positions return new_box, len(new_box[0]), new_root_start, new_root_end def _get_tree_properties(root): """Inspect the binary tree and return its properties (e.g. height). :param root: Root node of the binary tree. :rtype: binarytree.Node :return: Binary tree properties. :rtype: dict """ is_descending = True is_ascending = True min_node_value = root.value max_node_value = root.value size = 0 leaf_count = 0 min_leaf_depth = 0 max_leaf_depth = -1 is_strict = True is_complete = True current_nodes = [root] non_full_node_seen = False while len(current_nodes) > 0: max_leaf_depth += 1 next_nodes = [] for node in current_nodes: size += 1 value = node.value min_node_value = min(value, min_node_value) max_node_value = max(value, max_node_value) # Node is a leaf. if node.left is None and node.right is None: if min_leaf_depth == 0: min_leaf_depth = max_leaf_depth leaf_count += 1 if node.left is not None: if node.left.value > value: is_descending = False elif node.left.value < value: is_ascending = False next_nodes.append(node.left) is_complete = not non_full_node_seen else: non_full_node_seen = True if node.right is not None: if node.right.value > value: is_descending = False elif node.right.value < value: is_ascending = False next_nodes.append(node.right) is_complete = not non_full_node_seen else: non_full_node_seen = True # If we see a node with only one child, it is not strict is_strict &= (node.left is None) == (node.right is None) current_nodes = next_nodes return { 'height': max_leaf_depth, 'size': size, 'is_max_heap': is_complete and is_descending, 'is_min_heap': is_complete and is_ascending, 'is_perfect': leaf_count == 2 ** max_leaf_depth, 'is_strict': is_strict, 'is_complete': is_complete, 'leaf_count': leaf_count, 'min_node_value': min_node_value, 'max_node_value': max_node_value, 'min_leaf_depth': min_leaf_depth, 'max_leaf_depth': max_leaf_depth, } class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result def build(values): """Build a tree from `list representation`_ and return its root node. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :param values: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :type values: [int | float | None] :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.NodeNotFoundError: If the list representation is malformed (e.g. a parent node is missing). **Example**: .. doctest:: >>> from binarytree import build >>> >>> root = build([1, 2, 3, None, 4]) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. doctest:: >>> from binarytree import build >>> >>> root = build([None, 2, 3]) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 0 """ nodes = [None if v is None else Node(v) for v in values] for index in range(1, len(nodes)): node = nodes[index] if node is not None: parent_index = (index - 1) // 2 parent = nodes[parent_index] if parent is None: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) return nodes[0] if nodes else None def tree(height=3, is_perfect=False): """Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary tree may still be generated by chance. :type is_perfect: bool :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import tree >>> >>> root = tree() >>> >>> root.height 3 .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=5, is_perfect=True) >>> >>> root.height 5 >>> root.is_perfect True .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if is_perfect: return build(values) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = random.choice(('left', 'right')) if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def bst(height=3, is_perfect=False): """Generate a random BST (binary search tree) and return its root node. :param height: Height of the BST (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect BST with all levels filled is returned. If set to False, a perfect BST may still be generated by chance. :type is_perfect: bool :return: Root node of the BST. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import bst >>> >>> root = bst() >>> >>> root.height 3 >>> root.is_bst True .. doctest:: >>> from binarytree import bst >>> >>> root = bst(10) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) if is_perfect: return _generate_perfect_bst(height) values = _generate_random_node_values(height) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = 'left' if node.value > value else 'right' if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def heap(height=3, is_max=True, is_perfect=False): """Generate a random heap and return its root node. :param height: Height of the heap (default: 3, range: 0 - 9 inclusive). :type height: int :param is_max: If set to True (default: True), generate a max heap. If set to False, generate a min heap. A binary tree with only the root node is considered both a min and max heap. :type is_max: bool :param is_perfect: If set to True (default: False), a perfect heap with all levels filled is returned. If set to False, a perfect heap may still be generated by chance. :type is_perfect: bool :return: Root node of the heap. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import heap >>> >>> root = heap() >>> >>> root.height 3 >>> root.is_max_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(4, is_max=False) >>> >>> root.height 4 >>> root.is_min_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(5, is_max=False, is_perfect=True) >>> >>> root.height 5 >>> root.is_min_heap True >>> root.is_perfect True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(-1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if not is_perfect: # Randomly cut some of the leaf nodes away random_cut = random.randint(2 ** height, len(values)) values = values[:random_cut] if is_max: negated = [-v for v in values] heapq.heapify(negated) return build([-v for v in negated]) else: heapq.heapify(values) return build(values)
joowani/binarytree
binarytree/__init__.py
_generate_random_node_values
python
def _generate_random_node_values(height): max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) random.shuffle(node_values) return node_values
Return random node values for building binary trees. :param height: Height of the binary tree. :type height: int :return: Randomly generated node values. :rtype: [int]
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L118-L129
null
from __future__ import absolute_import, unicode_literals, division __all__ = ['Node', 'tree', 'bst', 'heap', 'build'] import heapq import random import numbers from binarytree.exceptions import ( TreeHeightError, NodeValueError, NodeIndexError, NodeTypeError, NodeModifyError, NodeNotFoundError, NodeReferenceError, ) def _is_balanced(root): """Return the height if the binary tree is balanced, -1 otherwise. :param root: Root node of the binary tree. :type root: binarytree.Node | None :return: Height if the binary tree is balanced, -1 otherwise. :rtype: int """ if root is None: return 0 left = _is_balanced(root.left) if left < 0: return -1 right = _is_balanced(root.right) if right < 0: return -1 return -1 if abs(left - right) > 1 else max(left, right) + 1 def _is_bst(root, min_value=float('-inf'), max_value=float('inf')): """Check if the binary tree is a BST (binary search tree). :param root: Root node of the binary tree. :type root: binarytree.Node | None :param min_value: Minimum node value seen. :type min_value: int | float :param max_value: Maximum node value seen. :type max_value: int | float :return: True if the binary tree is a BST, False otherwise. :rtype: bool """ if root is None: return True return ( min_value < root.value < max_value and _is_bst(root.left, min_value, root.value) and _is_bst(root.right, root.value, max_value) ) def _validate_tree_height(height): """Check if the height of the binary tree is valid. :param height: Height of the binary tree (must be 0 - 9 inclusive). :type height: int :raise binarytree.exceptions.TreeHeightError: If height is invalid. """ if not (isinstance(height, int) and 0 <= height <= 9): raise TreeHeightError('height must be an int between 0 - 9') def _generate_perfect_bst(height): """Generate a perfect BST (binary search tree) and return its root. :param height: Height of the BST. :type height: int :return: Root node of the BST. :rtype: binarytree.Node """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) return _build_bst_from_sorted_values(node_values) def _build_bst_from_sorted_values(sorted_values): """Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node """ if len(sorted_values) == 0: return None mid_index = len(sorted_values) // 2 root = Node(sorted_values[mid_index]) root.left = _build_bst_from_sorted_values(sorted_values[:mid_index]) root.right = _build_bst_from_sorted_values(sorted_values[mid_index + 1:]) return root def _generate_random_leaf_count(height): """Return a random leaf count for building binary trees. :param height: Height of the binary tree. :type height: int :return: Random leaf count. :rtype: int """ max_leaf_count = 2 ** height half_leaf_count = max_leaf_count // 2 # A very naive way of mimicking normal distribution roll_1 = random.randint(0, half_leaf_count) roll_2 = random.randint(0, max_leaf_count - half_leaf_count) return roll_1 + roll_2 or half_leaf_count def _build_tree_string(root, curr_index, index=False, delimiter='-'): """Recursively walk down the binary tree and build a pretty-print string. In each recursive call, a "box" of characters visually representing the current (sub)tree is constructed line by line. Each line is padded with whitespaces to ensure all lines in the box have the same length. Then the box, its width, and start-end positions of its root node value repr string (required for drawing branches) are sent up to the parent call. The parent call then combines its left and right sub-boxes to build a larger box etc. :param root: Root node of the binary tree. :type root: binarytree.Node | None :param curr_index: Level-order_ index of the current node (root node is 0). :type curr_index: int :param index: If set to True, include the level-order_ node indexes using the following format: ``{index}{delimiter}{value}`` (default: False). :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: :return: Box of characters visually representing the current subtree, width of the box, and start-end positions of the repr string of the new root node value. :rtype: ([str], int, int, int) .. _Level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ if root is None: return [], 0, 0, 0 line1 = [] line2 = [] if index: node_repr = '{}{}{}'.format(curr_index, delimiter, root.value) else: node_repr = str(root.value) new_root_width = gap_size = len(node_repr) # Get the left and right sub-boxes, their widths, and root repr positions l_box, l_box_width, l_root_start, l_root_end = \ _build_tree_string(root.left, 2 * curr_index + 1, index, delimiter) r_box, r_box_width, r_root_start, r_root_end = \ _build_tree_string(root.right, 2 * curr_index + 2, index, delimiter) # Draw the branch connecting the current root node to the left sub-box # Pad the line with whitespaces where necessary if l_box_width > 0: l_root = (l_root_start + l_root_end) // 2 + 1 line1.append(' ' * (l_root + 1)) line1.append('_' * (l_box_width - l_root)) line2.append(' ' * l_root + '/') line2.append(' ' * (l_box_width - l_root)) new_root_start = l_box_width + 1 gap_size += 1 else: new_root_start = 0 # Draw the representation of the current root node line1.append(node_repr) line2.append(' ' * new_root_width) # Draw the branch connecting the current root node to the right sub-box # Pad the line with whitespaces where necessary if r_box_width > 0: r_root = (r_root_start + r_root_end) // 2 line1.append('_' * r_root) line1.append(' ' * (r_box_width - r_root + 1)) line2.append(' ' * r_root + '\\') line2.append(' ' * (r_box_width - r_root)) gap_size += 1 new_root_end = new_root_start + new_root_width - 1 # Combine the left and right sub-boxes with the branches drawn above gap = ' ' * gap_size new_box = [''.join(line1), ''.join(line2)] for i in range(max(len(l_box), len(r_box))): l_line = l_box[i] if i < len(l_box) else ' ' * l_box_width r_line = r_box[i] if i < len(r_box) else ' ' * r_box_width new_box.append(l_line + gap + r_line) # Return the new box, its width and its root repr positions return new_box, len(new_box[0]), new_root_start, new_root_end def _get_tree_properties(root): """Inspect the binary tree and return its properties (e.g. height). :param root: Root node of the binary tree. :rtype: binarytree.Node :return: Binary tree properties. :rtype: dict """ is_descending = True is_ascending = True min_node_value = root.value max_node_value = root.value size = 0 leaf_count = 0 min_leaf_depth = 0 max_leaf_depth = -1 is_strict = True is_complete = True current_nodes = [root] non_full_node_seen = False while len(current_nodes) > 0: max_leaf_depth += 1 next_nodes = [] for node in current_nodes: size += 1 value = node.value min_node_value = min(value, min_node_value) max_node_value = max(value, max_node_value) # Node is a leaf. if node.left is None and node.right is None: if min_leaf_depth == 0: min_leaf_depth = max_leaf_depth leaf_count += 1 if node.left is not None: if node.left.value > value: is_descending = False elif node.left.value < value: is_ascending = False next_nodes.append(node.left) is_complete = not non_full_node_seen else: non_full_node_seen = True if node.right is not None: if node.right.value > value: is_descending = False elif node.right.value < value: is_ascending = False next_nodes.append(node.right) is_complete = not non_full_node_seen else: non_full_node_seen = True # If we see a node with only one child, it is not strict is_strict &= (node.left is None) == (node.right is None) current_nodes = next_nodes return { 'height': max_leaf_depth, 'size': size, 'is_max_heap': is_complete and is_descending, 'is_min_heap': is_complete and is_ascending, 'is_perfect': leaf_count == 2 ** max_leaf_depth, 'is_strict': is_strict, 'is_complete': is_complete, 'leaf_count': leaf_count, 'min_node_value': min_node_value, 'max_node_value': max_node_value, 'min_leaf_depth': min_leaf_depth, 'max_leaf_depth': max_leaf_depth, } class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result def build(values): """Build a tree from `list representation`_ and return its root node. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :param values: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :type values: [int | float | None] :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.NodeNotFoundError: If the list representation is malformed (e.g. a parent node is missing). **Example**: .. doctest:: >>> from binarytree import build >>> >>> root = build([1, 2, 3, None, 4]) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. doctest:: >>> from binarytree import build >>> >>> root = build([None, 2, 3]) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 0 """ nodes = [None if v is None else Node(v) for v in values] for index in range(1, len(nodes)): node = nodes[index] if node is not None: parent_index = (index - 1) // 2 parent = nodes[parent_index] if parent is None: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) return nodes[0] if nodes else None def tree(height=3, is_perfect=False): """Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary tree may still be generated by chance. :type is_perfect: bool :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import tree >>> >>> root = tree() >>> >>> root.height 3 .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=5, is_perfect=True) >>> >>> root.height 5 >>> root.is_perfect True .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if is_perfect: return build(values) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = random.choice(('left', 'right')) if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def bst(height=3, is_perfect=False): """Generate a random BST (binary search tree) and return its root node. :param height: Height of the BST (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect BST with all levels filled is returned. If set to False, a perfect BST may still be generated by chance. :type is_perfect: bool :return: Root node of the BST. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import bst >>> >>> root = bst() >>> >>> root.height 3 >>> root.is_bst True .. doctest:: >>> from binarytree import bst >>> >>> root = bst(10) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) if is_perfect: return _generate_perfect_bst(height) values = _generate_random_node_values(height) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = 'left' if node.value > value else 'right' if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def heap(height=3, is_max=True, is_perfect=False): """Generate a random heap and return its root node. :param height: Height of the heap (default: 3, range: 0 - 9 inclusive). :type height: int :param is_max: If set to True (default: True), generate a max heap. If set to False, generate a min heap. A binary tree with only the root node is considered both a min and max heap. :type is_max: bool :param is_perfect: If set to True (default: False), a perfect heap with all levels filled is returned. If set to False, a perfect heap may still be generated by chance. :type is_perfect: bool :return: Root node of the heap. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import heap >>> >>> root = heap() >>> >>> root.height 3 >>> root.is_max_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(4, is_max=False) >>> >>> root.height 4 >>> root.is_min_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(5, is_max=False, is_perfect=True) >>> >>> root.height 5 >>> root.is_min_heap True >>> root.is_perfect True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(-1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if not is_perfect: # Randomly cut some of the leaf nodes away random_cut = random.randint(2 ** height, len(values)) values = values[:random_cut] if is_max: negated = [-v for v in values] heapq.heapify(negated) return build([-v for v in negated]) else: heapq.heapify(values) return build(values)
joowani/binarytree
binarytree/__init__.py
_build_tree_string
python
def _build_tree_string(root, curr_index, index=False, delimiter='-'): if root is None: return [], 0, 0, 0 line1 = [] line2 = [] if index: node_repr = '{}{}{}'.format(curr_index, delimiter, root.value) else: node_repr = str(root.value) new_root_width = gap_size = len(node_repr) # Get the left and right sub-boxes, their widths, and root repr positions l_box, l_box_width, l_root_start, l_root_end = \ _build_tree_string(root.left, 2 * curr_index + 1, index, delimiter) r_box, r_box_width, r_root_start, r_root_end = \ _build_tree_string(root.right, 2 * curr_index + 2, index, delimiter) # Draw the branch connecting the current root node to the left sub-box # Pad the line with whitespaces where necessary if l_box_width > 0: l_root = (l_root_start + l_root_end) // 2 + 1 line1.append(' ' * (l_root + 1)) line1.append('_' * (l_box_width - l_root)) line2.append(' ' * l_root + '/') line2.append(' ' * (l_box_width - l_root)) new_root_start = l_box_width + 1 gap_size += 1 else: new_root_start = 0 # Draw the representation of the current root node line1.append(node_repr) line2.append(' ' * new_root_width) # Draw the branch connecting the current root node to the right sub-box # Pad the line with whitespaces where necessary if r_box_width > 0: r_root = (r_root_start + r_root_end) // 2 line1.append('_' * r_root) line1.append(' ' * (r_box_width - r_root + 1)) line2.append(' ' * r_root + '\\') line2.append(' ' * (r_box_width - r_root)) gap_size += 1 new_root_end = new_root_start + new_root_width - 1 # Combine the left and right sub-boxes with the branches drawn above gap = ' ' * gap_size new_box = [''.join(line1), ''.join(line2)] for i in range(max(len(l_box), len(r_box))): l_line = l_box[i] if i < len(l_box) else ' ' * l_box_width r_line = r_box[i] if i < len(r_box) else ' ' * r_box_width new_box.append(l_line + gap + r_line) # Return the new box, its width and its root repr positions return new_box, len(new_box[0]), new_root_start, new_root_end
Recursively walk down the binary tree and build a pretty-print string. In each recursive call, a "box" of characters visually representing the current (sub)tree is constructed line by line. Each line is padded with whitespaces to ensure all lines in the box have the same length. Then the box, its width, and start-end positions of its root node value repr string (required for drawing branches) are sent up to the parent call. The parent call then combines its left and right sub-boxes to build a larger box etc. :param root: Root node of the binary tree. :type root: binarytree.Node | None :param curr_index: Level-order_ index of the current node (root node is 0). :type curr_index: int :param index: If set to True, include the level-order_ node indexes using the following format: ``{index}{delimiter}{value}`` (default: False). :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: :return: Box of characters visually representing the current subtree, width of the box, and start-end positions of the repr string of the new root node value. :rtype: ([str], int, int, int) .. _Level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L132-L215
[ "def _build_tree_string(root, curr_index, index=False, delimiter='-'):\n \"\"\"Recursively walk down the binary tree and build a pretty-print string.\n\n In each recursive call, a \"box\" of characters visually representing the\n current (sub)tree is constructed line by line. Each line is padded with\n whitespaces to ensure all lines in the box have the same length. Then the\n box, its width, and start-end positions of its root node value repr string\n (required for drawing branches) are sent up to the parent call. The parent\n call then combines its left and right sub-boxes to build a larger box etc.\n\n :param root: Root node of the binary tree.\n :type root: binarytree.Node | None\n :param curr_index: Level-order_ index of the current node (root node is 0).\n :type curr_index: int\n :param index: If set to True, include the level-order_ node indexes using\n the following format: ``{index}{delimiter}{value}`` (default: False).\n :type index: bool\n :param delimiter: Delimiter character between the node index and the node\n value (default: '-').\n :type delimiter:\n :return: Box of characters visually representing the current subtree, width\n of the box, and start-end positions of the repr string of the new root\n node value.\n :rtype: ([str], int, int, int)\n\n .. _Level-order:\n https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search\n \"\"\"\n if root is None:\n return [], 0, 0, 0\n\n line1 = []\n line2 = []\n if index:\n node_repr = '{}{}{}'.format(curr_index, delimiter, root.value)\n else:\n node_repr = str(root.value)\n\n new_root_width = gap_size = len(node_repr)\n\n # Get the left and right sub-boxes, their widths, and root repr positions\n l_box, l_box_width, l_root_start, l_root_end = \\\n _build_tree_string(root.left, 2 * curr_index + 1, index, delimiter)\n r_box, r_box_width, r_root_start, r_root_end = \\\n _build_tree_string(root.right, 2 * curr_index + 2, index, delimiter)\n\n # Draw the branch connecting the current root node to the left sub-box\n # Pad the line with whitespaces where necessary\n if l_box_width > 0:\n l_root = (l_root_start + l_root_end) // 2 + 1\n line1.append(' ' * (l_root + 1))\n line1.append('_' * (l_box_width - l_root))\n line2.append(' ' * l_root + '/')\n line2.append(' ' * (l_box_width - l_root))\n new_root_start = l_box_width + 1\n gap_size += 1\n else:\n new_root_start = 0\n\n # Draw the representation of the current root node\n line1.append(node_repr)\n line2.append(' ' * new_root_width)\n\n # Draw the branch connecting the current root node to the right sub-box\n # Pad the line with whitespaces where necessary\n if r_box_width > 0:\n r_root = (r_root_start + r_root_end) // 2\n line1.append('_' * r_root)\n line1.append(' ' * (r_box_width - r_root + 1))\n line2.append(' ' * r_root + '\\\\')\n line2.append(' ' * (r_box_width - r_root))\n gap_size += 1\n new_root_end = new_root_start + new_root_width - 1\n\n # Combine the left and right sub-boxes with the branches drawn above\n gap = ' ' * gap_size\n new_box = [''.join(line1), ''.join(line2)]\n for i in range(max(len(l_box), len(r_box))):\n l_line = l_box[i] if i < len(l_box) else ' ' * l_box_width\n r_line = r_box[i] if i < len(r_box) else ' ' * r_box_width\n new_box.append(l_line + gap + r_line)\n\n # Return the new box, its width and its root repr positions\n return new_box, len(new_box[0]), new_root_start, new_root_end\n" ]
from __future__ import absolute_import, unicode_literals, division __all__ = ['Node', 'tree', 'bst', 'heap', 'build'] import heapq import random import numbers from binarytree.exceptions import ( TreeHeightError, NodeValueError, NodeIndexError, NodeTypeError, NodeModifyError, NodeNotFoundError, NodeReferenceError, ) def _is_balanced(root): """Return the height if the binary tree is balanced, -1 otherwise. :param root: Root node of the binary tree. :type root: binarytree.Node | None :return: Height if the binary tree is balanced, -1 otherwise. :rtype: int """ if root is None: return 0 left = _is_balanced(root.left) if left < 0: return -1 right = _is_balanced(root.right) if right < 0: return -1 return -1 if abs(left - right) > 1 else max(left, right) + 1 def _is_bst(root, min_value=float('-inf'), max_value=float('inf')): """Check if the binary tree is a BST (binary search tree). :param root: Root node of the binary tree. :type root: binarytree.Node | None :param min_value: Minimum node value seen. :type min_value: int | float :param max_value: Maximum node value seen. :type max_value: int | float :return: True if the binary tree is a BST, False otherwise. :rtype: bool """ if root is None: return True return ( min_value < root.value < max_value and _is_bst(root.left, min_value, root.value) and _is_bst(root.right, root.value, max_value) ) def _validate_tree_height(height): """Check if the height of the binary tree is valid. :param height: Height of the binary tree (must be 0 - 9 inclusive). :type height: int :raise binarytree.exceptions.TreeHeightError: If height is invalid. """ if not (isinstance(height, int) and 0 <= height <= 9): raise TreeHeightError('height must be an int between 0 - 9') def _generate_perfect_bst(height): """Generate a perfect BST (binary search tree) and return its root. :param height: Height of the BST. :type height: int :return: Root node of the BST. :rtype: binarytree.Node """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) return _build_bst_from_sorted_values(node_values) def _build_bst_from_sorted_values(sorted_values): """Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node """ if len(sorted_values) == 0: return None mid_index = len(sorted_values) // 2 root = Node(sorted_values[mid_index]) root.left = _build_bst_from_sorted_values(sorted_values[:mid_index]) root.right = _build_bst_from_sorted_values(sorted_values[mid_index + 1:]) return root def _generate_random_leaf_count(height): """Return a random leaf count for building binary trees. :param height: Height of the binary tree. :type height: int :return: Random leaf count. :rtype: int """ max_leaf_count = 2 ** height half_leaf_count = max_leaf_count // 2 # A very naive way of mimicking normal distribution roll_1 = random.randint(0, half_leaf_count) roll_2 = random.randint(0, max_leaf_count - half_leaf_count) return roll_1 + roll_2 or half_leaf_count def _generate_random_node_values(height): """Return random node values for building binary trees. :param height: Height of the binary tree. :type height: int :return: Randomly generated node values. :rtype: [int] """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) random.shuffle(node_values) return node_values def _get_tree_properties(root): """Inspect the binary tree and return its properties (e.g. height). :param root: Root node of the binary tree. :rtype: binarytree.Node :return: Binary tree properties. :rtype: dict """ is_descending = True is_ascending = True min_node_value = root.value max_node_value = root.value size = 0 leaf_count = 0 min_leaf_depth = 0 max_leaf_depth = -1 is_strict = True is_complete = True current_nodes = [root] non_full_node_seen = False while len(current_nodes) > 0: max_leaf_depth += 1 next_nodes = [] for node in current_nodes: size += 1 value = node.value min_node_value = min(value, min_node_value) max_node_value = max(value, max_node_value) # Node is a leaf. if node.left is None and node.right is None: if min_leaf_depth == 0: min_leaf_depth = max_leaf_depth leaf_count += 1 if node.left is not None: if node.left.value > value: is_descending = False elif node.left.value < value: is_ascending = False next_nodes.append(node.left) is_complete = not non_full_node_seen else: non_full_node_seen = True if node.right is not None: if node.right.value > value: is_descending = False elif node.right.value < value: is_ascending = False next_nodes.append(node.right) is_complete = not non_full_node_seen else: non_full_node_seen = True # If we see a node with only one child, it is not strict is_strict &= (node.left is None) == (node.right is None) current_nodes = next_nodes return { 'height': max_leaf_depth, 'size': size, 'is_max_heap': is_complete and is_descending, 'is_min_heap': is_complete and is_ascending, 'is_perfect': leaf_count == 2 ** max_leaf_depth, 'is_strict': is_strict, 'is_complete': is_complete, 'leaf_count': leaf_count, 'min_node_value': min_node_value, 'max_node_value': max_node_value, 'min_leaf_depth': min_leaf_depth, 'max_leaf_depth': max_leaf_depth, } class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result def build(values): """Build a tree from `list representation`_ and return its root node. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :param values: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :type values: [int | float | None] :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.NodeNotFoundError: If the list representation is malformed (e.g. a parent node is missing). **Example**: .. doctest:: >>> from binarytree import build >>> >>> root = build([1, 2, 3, None, 4]) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. doctest:: >>> from binarytree import build >>> >>> root = build([None, 2, 3]) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 0 """ nodes = [None if v is None else Node(v) for v in values] for index in range(1, len(nodes)): node = nodes[index] if node is not None: parent_index = (index - 1) // 2 parent = nodes[parent_index] if parent is None: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) return nodes[0] if nodes else None def tree(height=3, is_perfect=False): """Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary tree may still be generated by chance. :type is_perfect: bool :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import tree >>> >>> root = tree() >>> >>> root.height 3 .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=5, is_perfect=True) >>> >>> root.height 5 >>> root.is_perfect True .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if is_perfect: return build(values) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = random.choice(('left', 'right')) if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def bst(height=3, is_perfect=False): """Generate a random BST (binary search tree) and return its root node. :param height: Height of the BST (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect BST with all levels filled is returned. If set to False, a perfect BST may still be generated by chance. :type is_perfect: bool :return: Root node of the BST. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import bst >>> >>> root = bst() >>> >>> root.height 3 >>> root.is_bst True .. doctest:: >>> from binarytree import bst >>> >>> root = bst(10) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) if is_perfect: return _generate_perfect_bst(height) values = _generate_random_node_values(height) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = 'left' if node.value > value else 'right' if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def heap(height=3, is_max=True, is_perfect=False): """Generate a random heap and return its root node. :param height: Height of the heap (default: 3, range: 0 - 9 inclusive). :type height: int :param is_max: If set to True (default: True), generate a max heap. If set to False, generate a min heap. A binary tree with only the root node is considered both a min and max heap. :type is_max: bool :param is_perfect: If set to True (default: False), a perfect heap with all levels filled is returned. If set to False, a perfect heap may still be generated by chance. :type is_perfect: bool :return: Root node of the heap. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import heap >>> >>> root = heap() >>> >>> root.height 3 >>> root.is_max_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(4, is_max=False) >>> >>> root.height 4 >>> root.is_min_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(5, is_max=False, is_perfect=True) >>> >>> root.height 5 >>> root.is_min_heap True >>> root.is_perfect True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(-1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if not is_perfect: # Randomly cut some of the leaf nodes away random_cut = random.randint(2 ** height, len(values)) values = values[:random_cut] if is_max: negated = [-v for v in values] heapq.heapify(negated) return build([-v for v in negated]) else: heapq.heapify(values) return build(values)
joowani/binarytree
binarytree/__init__.py
_get_tree_properties
python
def _get_tree_properties(root): is_descending = True is_ascending = True min_node_value = root.value max_node_value = root.value size = 0 leaf_count = 0 min_leaf_depth = 0 max_leaf_depth = -1 is_strict = True is_complete = True current_nodes = [root] non_full_node_seen = False while len(current_nodes) > 0: max_leaf_depth += 1 next_nodes = [] for node in current_nodes: size += 1 value = node.value min_node_value = min(value, min_node_value) max_node_value = max(value, max_node_value) # Node is a leaf. if node.left is None and node.right is None: if min_leaf_depth == 0: min_leaf_depth = max_leaf_depth leaf_count += 1 if node.left is not None: if node.left.value > value: is_descending = False elif node.left.value < value: is_ascending = False next_nodes.append(node.left) is_complete = not non_full_node_seen else: non_full_node_seen = True if node.right is not None: if node.right.value > value: is_descending = False elif node.right.value < value: is_ascending = False next_nodes.append(node.right) is_complete = not non_full_node_seen else: non_full_node_seen = True # If we see a node with only one child, it is not strict is_strict &= (node.left is None) == (node.right is None) current_nodes = next_nodes return { 'height': max_leaf_depth, 'size': size, 'is_max_heap': is_complete and is_descending, 'is_min_heap': is_complete and is_ascending, 'is_perfect': leaf_count == 2 ** max_leaf_depth, 'is_strict': is_strict, 'is_complete': is_complete, 'leaf_count': leaf_count, 'min_node_value': min_node_value, 'max_node_value': max_node_value, 'min_leaf_depth': min_leaf_depth, 'max_leaf_depth': max_leaf_depth, }
Inspect the binary tree and return its properties (e.g. height). :param root: Root node of the binary tree. :rtype: binarytree.Node :return: Binary tree properties. :rtype: dict
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L218-L293
null
from __future__ import absolute_import, unicode_literals, division __all__ = ['Node', 'tree', 'bst', 'heap', 'build'] import heapq import random import numbers from binarytree.exceptions import ( TreeHeightError, NodeValueError, NodeIndexError, NodeTypeError, NodeModifyError, NodeNotFoundError, NodeReferenceError, ) def _is_balanced(root): """Return the height if the binary tree is balanced, -1 otherwise. :param root: Root node of the binary tree. :type root: binarytree.Node | None :return: Height if the binary tree is balanced, -1 otherwise. :rtype: int """ if root is None: return 0 left = _is_balanced(root.left) if left < 0: return -1 right = _is_balanced(root.right) if right < 0: return -1 return -1 if abs(left - right) > 1 else max(left, right) + 1 def _is_bst(root, min_value=float('-inf'), max_value=float('inf')): """Check if the binary tree is a BST (binary search tree). :param root: Root node of the binary tree. :type root: binarytree.Node | None :param min_value: Minimum node value seen. :type min_value: int | float :param max_value: Maximum node value seen. :type max_value: int | float :return: True if the binary tree is a BST, False otherwise. :rtype: bool """ if root is None: return True return ( min_value < root.value < max_value and _is_bst(root.left, min_value, root.value) and _is_bst(root.right, root.value, max_value) ) def _validate_tree_height(height): """Check if the height of the binary tree is valid. :param height: Height of the binary tree (must be 0 - 9 inclusive). :type height: int :raise binarytree.exceptions.TreeHeightError: If height is invalid. """ if not (isinstance(height, int) and 0 <= height <= 9): raise TreeHeightError('height must be an int between 0 - 9') def _generate_perfect_bst(height): """Generate a perfect BST (binary search tree) and return its root. :param height: Height of the BST. :type height: int :return: Root node of the BST. :rtype: binarytree.Node """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) return _build_bst_from_sorted_values(node_values) def _build_bst_from_sorted_values(sorted_values): """Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node """ if len(sorted_values) == 0: return None mid_index = len(sorted_values) // 2 root = Node(sorted_values[mid_index]) root.left = _build_bst_from_sorted_values(sorted_values[:mid_index]) root.right = _build_bst_from_sorted_values(sorted_values[mid_index + 1:]) return root def _generate_random_leaf_count(height): """Return a random leaf count for building binary trees. :param height: Height of the binary tree. :type height: int :return: Random leaf count. :rtype: int """ max_leaf_count = 2 ** height half_leaf_count = max_leaf_count // 2 # A very naive way of mimicking normal distribution roll_1 = random.randint(0, half_leaf_count) roll_2 = random.randint(0, max_leaf_count - half_leaf_count) return roll_1 + roll_2 or half_leaf_count def _generate_random_node_values(height): """Return random node values for building binary trees. :param height: Height of the binary tree. :type height: int :return: Randomly generated node values. :rtype: [int] """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) random.shuffle(node_values) return node_values def _build_tree_string(root, curr_index, index=False, delimiter='-'): """Recursively walk down the binary tree and build a pretty-print string. In each recursive call, a "box" of characters visually representing the current (sub)tree is constructed line by line. Each line is padded with whitespaces to ensure all lines in the box have the same length. Then the box, its width, and start-end positions of its root node value repr string (required for drawing branches) are sent up to the parent call. The parent call then combines its left and right sub-boxes to build a larger box etc. :param root: Root node of the binary tree. :type root: binarytree.Node | None :param curr_index: Level-order_ index of the current node (root node is 0). :type curr_index: int :param index: If set to True, include the level-order_ node indexes using the following format: ``{index}{delimiter}{value}`` (default: False). :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: :return: Box of characters visually representing the current subtree, width of the box, and start-end positions of the repr string of the new root node value. :rtype: ([str], int, int, int) .. _Level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ if root is None: return [], 0, 0, 0 line1 = [] line2 = [] if index: node_repr = '{}{}{}'.format(curr_index, delimiter, root.value) else: node_repr = str(root.value) new_root_width = gap_size = len(node_repr) # Get the left and right sub-boxes, their widths, and root repr positions l_box, l_box_width, l_root_start, l_root_end = \ _build_tree_string(root.left, 2 * curr_index + 1, index, delimiter) r_box, r_box_width, r_root_start, r_root_end = \ _build_tree_string(root.right, 2 * curr_index + 2, index, delimiter) # Draw the branch connecting the current root node to the left sub-box # Pad the line with whitespaces where necessary if l_box_width > 0: l_root = (l_root_start + l_root_end) // 2 + 1 line1.append(' ' * (l_root + 1)) line1.append('_' * (l_box_width - l_root)) line2.append(' ' * l_root + '/') line2.append(' ' * (l_box_width - l_root)) new_root_start = l_box_width + 1 gap_size += 1 else: new_root_start = 0 # Draw the representation of the current root node line1.append(node_repr) line2.append(' ' * new_root_width) # Draw the branch connecting the current root node to the right sub-box # Pad the line with whitespaces where necessary if r_box_width > 0: r_root = (r_root_start + r_root_end) // 2 line1.append('_' * r_root) line1.append(' ' * (r_box_width - r_root + 1)) line2.append(' ' * r_root + '\\') line2.append(' ' * (r_box_width - r_root)) gap_size += 1 new_root_end = new_root_start + new_root_width - 1 # Combine the left and right sub-boxes with the branches drawn above gap = ' ' * gap_size new_box = [''.join(line1), ''.join(line2)] for i in range(max(len(l_box), len(r_box))): l_line = l_box[i] if i < len(l_box) else ' ' * l_box_width r_line = r_box[i] if i < len(r_box) else ' ' * r_box_width new_box.append(l_line + gap + r_line) # Return the new box, its width and its root repr positions return new_box, len(new_box[0]), new_root_start, new_root_end class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result def build(values): """Build a tree from `list representation`_ and return its root node. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :param values: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :type values: [int | float | None] :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.NodeNotFoundError: If the list representation is malformed (e.g. a parent node is missing). **Example**: .. doctest:: >>> from binarytree import build >>> >>> root = build([1, 2, 3, None, 4]) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. doctest:: >>> from binarytree import build >>> >>> root = build([None, 2, 3]) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 0 """ nodes = [None if v is None else Node(v) for v in values] for index in range(1, len(nodes)): node = nodes[index] if node is not None: parent_index = (index - 1) // 2 parent = nodes[parent_index] if parent is None: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) return nodes[0] if nodes else None def tree(height=3, is_perfect=False): """Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary tree may still be generated by chance. :type is_perfect: bool :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import tree >>> >>> root = tree() >>> >>> root.height 3 .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=5, is_perfect=True) >>> >>> root.height 5 >>> root.is_perfect True .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if is_perfect: return build(values) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = random.choice(('left', 'right')) if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def bst(height=3, is_perfect=False): """Generate a random BST (binary search tree) and return its root node. :param height: Height of the BST (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect BST with all levels filled is returned. If set to False, a perfect BST may still be generated by chance. :type is_perfect: bool :return: Root node of the BST. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import bst >>> >>> root = bst() >>> >>> root.height 3 >>> root.is_bst True .. doctest:: >>> from binarytree import bst >>> >>> root = bst(10) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) if is_perfect: return _generate_perfect_bst(height) values = _generate_random_node_values(height) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = 'left' if node.value > value else 'right' if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def heap(height=3, is_max=True, is_perfect=False): """Generate a random heap and return its root node. :param height: Height of the heap (default: 3, range: 0 - 9 inclusive). :type height: int :param is_max: If set to True (default: True), generate a max heap. If set to False, generate a min heap. A binary tree with only the root node is considered both a min and max heap. :type is_max: bool :param is_perfect: If set to True (default: False), a perfect heap with all levels filled is returned. If set to False, a perfect heap may still be generated by chance. :type is_perfect: bool :return: Root node of the heap. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import heap >>> >>> root = heap() >>> >>> root.height 3 >>> root.is_max_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(4, is_max=False) >>> >>> root.height 4 >>> root.is_min_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(5, is_max=False, is_perfect=True) >>> >>> root.height 5 >>> root.is_min_heap True >>> root.is_perfect True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(-1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if not is_perfect: # Randomly cut some of the leaf nodes away random_cut = random.randint(2 ** height, len(values)) values = values[:random_cut] if is_max: negated = [-v for v in values] heapq.heapify(negated) return build([-v for v in negated]) else: heapq.heapify(values) return build(values)
joowani/binarytree
binarytree/__init__.py
build
python
def build(values): nodes = [None if v is None else Node(v) for v in values] for index in range(1, len(nodes)): node = nodes[index] if node is not None: parent_index = (index - 1) // 2 parent = nodes[parent_index] if parent is None: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) return nodes[0] if nodes else None
Build a tree from `list representation`_ and return its root node. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :param values: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :type values: [int | float | None] :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.NodeNotFoundError: If the list representation is malformed (e.g. a parent node is missing). **Example**: .. doctest:: >>> from binarytree import build >>> >>> root = build([1, 2, 3, None, 4]) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. doctest:: >>> from binarytree import build >>> >>> root = build([None, 2, 3]) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 0
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L1654-L1709
null
from __future__ import absolute_import, unicode_literals, division __all__ = ['Node', 'tree', 'bst', 'heap', 'build'] import heapq import random import numbers from binarytree.exceptions import ( TreeHeightError, NodeValueError, NodeIndexError, NodeTypeError, NodeModifyError, NodeNotFoundError, NodeReferenceError, ) def _is_balanced(root): """Return the height if the binary tree is balanced, -1 otherwise. :param root: Root node of the binary tree. :type root: binarytree.Node | None :return: Height if the binary tree is balanced, -1 otherwise. :rtype: int """ if root is None: return 0 left = _is_balanced(root.left) if left < 0: return -1 right = _is_balanced(root.right) if right < 0: return -1 return -1 if abs(left - right) > 1 else max(left, right) + 1 def _is_bst(root, min_value=float('-inf'), max_value=float('inf')): """Check if the binary tree is a BST (binary search tree). :param root: Root node of the binary tree. :type root: binarytree.Node | None :param min_value: Minimum node value seen. :type min_value: int | float :param max_value: Maximum node value seen. :type max_value: int | float :return: True if the binary tree is a BST, False otherwise. :rtype: bool """ if root is None: return True return ( min_value < root.value < max_value and _is_bst(root.left, min_value, root.value) and _is_bst(root.right, root.value, max_value) ) def _validate_tree_height(height): """Check if the height of the binary tree is valid. :param height: Height of the binary tree (must be 0 - 9 inclusive). :type height: int :raise binarytree.exceptions.TreeHeightError: If height is invalid. """ if not (isinstance(height, int) and 0 <= height <= 9): raise TreeHeightError('height must be an int between 0 - 9') def _generate_perfect_bst(height): """Generate a perfect BST (binary search tree) and return its root. :param height: Height of the BST. :type height: int :return: Root node of the BST. :rtype: binarytree.Node """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) return _build_bst_from_sorted_values(node_values) def _build_bst_from_sorted_values(sorted_values): """Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node """ if len(sorted_values) == 0: return None mid_index = len(sorted_values) // 2 root = Node(sorted_values[mid_index]) root.left = _build_bst_from_sorted_values(sorted_values[:mid_index]) root.right = _build_bst_from_sorted_values(sorted_values[mid_index + 1:]) return root def _generate_random_leaf_count(height): """Return a random leaf count for building binary trees. :param height: Height of the binary tree. :type height: int :return: Random leaf count. :rtype: int """ max_leaf_count = 2 ** height half_leaf_count = max_leaf_count // 2 # A very naive way of mimicking normal distribution roll_1 = random.randint(0, half_leaf_count) roll_2 = random.randint(0, max_leaf_count - half_leaf_count) return roll_1 + roll_2 or half_leaf_count def _generate_random_node_values(height): """Return random node values for building binary trees. :param height: Height of the binary tree. :type height: int :return: Randomly generated node values. :rtype: [int] """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) random.shuffle(node_values) return node_values def _build_tree_string(root, curr_index, index=False, delimiter='-'): """Recursively walk down the binary tree and build a pretty-print string. In each recursive call, a "box" of characters visually representing the current (sub)tree is constructed line by line. Each line is padded with whitespaces to ensure all lines in the box have the same length. Then the box, its width, and start-end positions of its root node value repr string (required for drawing branches) are sent up to the parent call. The parent call then combines its left and right sub-boxes to build a larger box etc. :param root: Root node of the binary tree. :type root: binarytree.Node | None :param curr_index: Level-order_ index of the current node (root node is 0). :type curr_index: int :param index: If set to True, include the level-order_ node indexes using the following format: ``{index}{delimiter}{value}`` (default: False). :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: :return: Box of characters visually representing the current subtree, width of the box, and start-end positions of the repr string of the new root node value. :rtype: ([str], int, int, int) .. _Level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ if root is None: return [], 0, 0, 0 line1 = [] line2 = [] if index: node_repr = '{}{}{}'.format(curr_index, delimiter, root.value) else: node_repr = str(root.value) new_root_width = gap_size = len(node_repr) # Get the left and right sub-boxes, their widths, and root repr positions l_box, l_box_width, l_root_start, l_root_end = \ _build_tree_string(root.left, 2 * curr_index + 1, index, delimiter) r_box, r_box_width, r_root_start, r_root_end = \ _build_tree_string(root.right, 2 * curr_index + 2, index, delimiter) # Draw the branch connecting the current root node to the left sub-box # Pad the line with whitespaces where necessary if l_box_width > 0: l_root = (l_root_start + l_root_end) // 2 + 1 line1.append(' ' * (l_root + 1)) line1.append('_' * (l_box_width - l_root)) line2.append(' ' * l_root + '/') line2.append(' ' * (l_box_width - l_root)) new_root_start = l_box_width + 1 gap_size += 1 else: new_root_start = 0 # Draw the representation of the current root node line1.append(node_repr) line2.append(' ' * new_root_width) # Draw the branch connecting the current root node to the right sub-box # Pad the line with whitespaces where necessary if r_box_width > 0: r_root = (r_root_start + r_root_end) // 2 line1.append('_' * r_root) line1.append(' ' * (r_box_width - r_root + 1)) line2.append(' ' * r_root + '\\') line2.append(' ' * (r_box_width - r_root)) gap_size += 1 new_root_end = new_root_start + new_root_width - 1 # Combine the left and right sub-boxes with the branches drawn above gap = ' ' * gap_size new_box = [''.join(line1), ''.join(line2)] for i in range(max(len(l_box), len(r_box))): l_line = l_box[i] if i < len(l_box) else ' ' * l_box_width r_line = r_box[i] if i < len(r_box) else ' ' * r_box_width new_box.append(l_line + gap + r_line) # Return the new box, its width and its root repr positions return new_box, len(new_box[0]), new_root_start, new_root_end def _get_tree_properties(root): """Inspect the binary tree and return its properties (e.g. height). :param root: Root node of the binary tree. :rtype: binarytree.Node :return: Binary tree properties. :rtype: dict """ is_descending = True is_ascending = True min_node_value = root.value max_node_value = root.value size = 0 leaf_count = 0 min_leaf_depth = 0 max_leaf_depth = -1 is_strict = True is_complete = True current_nodes = [root] non_full_node_seen = False while len(current_nodes) > 0: max_leaf_depth += 1 next_nodes = [] for node in current_nodes: size += 1 value = node.value min_node_value = min(value, min_node_value) max_node_value = max(value, max_node_value) # Node is a leaf. if node.left is None and node.right is None: if min_leaf_depth == 0: min_leaf_depth = max_leaf_depth leaf_count += 1 if node.left is not None: if node.left.value > value: is_descending = False elif node.left.value < value: is_ascending = False next_nodes.append(node.left) is_complete = not non_full_node_seen else: non_full_node_seen = True if node.right is not None: if node.right.value > value: is_descending = False elif node.right.value < value: is_ascending = False next_nodes.append(node.right) is_complete = not non_full_node_seen else: non_full_node_seen = True # If we see a node with only one child, it is not strict is_strict &= (node.left is None) == (node.right is None) current_nodes = next_nodes return { 'height': max_leaf_depth, 'size': size, 'is_max_heap': is_complete and is_descending, 'is_min_heap': is_complete and is_ascending, 'is_perfect': leaf_count == 2 ** max_leaf_depth, 'is_strict': is_strict, 'is_complete': is_complete, 'leaf_count': leaf_count, 'min_node_value': min_node_value, 'max_node_value': max_node_value, 'min_leaf_depth': min_leaf_depth, 'max_leaf_depth': max_leaf_depth, } class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result def tree(height=3, is_perfect=False): """Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary tree may still be generated by chance. :type is_perfect: bool :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import tree >>> >>> root = tree() >>> >>> root.height 3 .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=5, is_perfect=True) >>> >>> root.height 5 >>> root.is_perfect True .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if is_perfect: return build(values) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = random.choice(('left', 'right')) if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def bst(height=3, is_perfect=False): """Generate a random BST (binary search tree) and return its root node. :param height: Height of the BST (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect BST with all levels filled is returned. If set to False, a perfect BST may still be generated by chance. :type is_perfect: bool :return: Root node of the BST. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import bst >>> >>> root = bst() >>> >>> root.height 3 >>> root.is_bst True .. doctest:: >>> from binarytree import bst >>> >>> root = bst(10) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) if is_perfect: return _generate_perfect_bst(height) values = _generate_random_node_values(height) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = 'left' if node.value > value else 'right' if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def heap(height=3, is_max=True, is_perfect=False): """Generate a random heap and return its root node. :param height: Height of the heap (default: 3, range: 0 - 9 inclusive). :type height: int :param is_max: If set to True (default: True), generate a max heap. If set to False, generate a min heap. A binary tree with only the root node is considered both a min and max heap. :type is_max: bool :param is_perfect: If set to True (default: False), a perfect heap with all levels filled is returned. If set to False, a perfect heap may still be generated by chance. :type is_perfect: bool :return: Root node of the heap. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import heap >>> >>> root = heap() >>> >>> root.height 3 >>> root.is_max_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(4, is_max=False) >>> >>> root.height 4 >>> root.is_min_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(5, is_max=False, is_perfect=True) >>> >>> root.height 5 >>> root.is_min_heap True >>> root.is_perfect True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(-1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if not is_perfect: # Randomly cut some of the leaf nodes away random_cut = random.randint(2 ** height, len(values)) values = values[:random_cut] if is_max: negated = [-v for v in values] heapq.heapify(negated) return build([-v for v in negated]) else: heapq.heapify(values) return build(values)
joowani/binarytree
binarytree/__init__.py
tree
python
def tree(height=3, is_perfect=False): _validate_tree_height(height) values = _generate_random_node_values(height) if is_perfect: return build(values) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = random.choice(('left', 'right')) if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root
Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary tree may still be generated by chance. :type is_perfect: bool :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import tree >>> >>> root = tree() >>> >>> root.height 3 .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=5, is_perfect=True) >>> >>> root.height 5 >>> root.is_perfect True .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L1712-L1783
[ "def build(values):\n \"\"\"Build a tree from `list representation`_ and return its root node.\n\n .. _list representation:\n https://en.wikipedia.org/wiki/Binary_tree#Arrays\n\n :param values: List representation of the binary tree, which is a list of\n node values in breadth-first order starting from the root (current\n node). If a node is at index i, its left child is always at 2i + 1,\n right child at 2i + 2, and parent at floor((i - 1) / 2). None indicates\n absence of a node at that index. See example below for an illustration.\n :type values: [int | float | None]\n :return: Root node of the binary tree.\n :rtype: binarytree.Node\n :raise binarytree.exceptions.NodeNotFoundError: If the list representation\n is malformed (e.g. a parent node is missing).\n\n **Example**:\n\n .. doctest::\n\n >>> from binarytree import build\n >>>\n >>> root = build([1, 2, 3, None, 4])\n >>>\n >>> print(root)\n <BLANKLINE>\n __1\n / \\\\\n 2 3\n \\\\\n 4\n <BLANKLINE>\n\n .. doctest::\n\n >>> from binarytree import build\n >>>\n >>> root = build([None, 2, 3]) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n NodeNotFoundError: parent node missing at index 0\n \"\"\"\n nodes = [None if v is None else Node(v) for v in values]\n\n for index in range(1, len(nodes)):\n node = nodes[index]\n if node is not None:\n parent_index = (index - 1) // 2\n parent = nodes[parent_index]\n if parent is None:\n raise NodeNotFoundError(\n 'parent node missing at index {}'.format(parent_index))\n setattr(parent, 'left' if index % 2 else 'right', node)\n\n return nodes[0] if nodes else None\n", "def _validate_tree_height(height):\n \"\"\"Check if the height of the binary tree is valid.\n\n :param height: Height of the binary tree (must be 0 - 9 inclusive).\n :type height: int\n :raise binarytree.exceptions.TreeHeightError: If height is invalid.\n \"\"\"\n if not (isinstance(height, int) and 0 <= height <= 9):\n raise TreeHeightError('height must be an int between 0 - 9')\n", "def _generate_random_leaf_count(height):\n \"\"\"Return a random leaf count for building binary trees.\n\n :param height: Height of the binary tree.\n :type height: int\n :return: Random leaf count.\n :rtype: int\n \"\"\"\n max_leaf_count = 2 ** height\n half_leaf_count = max_leaf_count // 2\n\n # A very naive way of mimicking normal distribution\n roll_1 = random.randint(0, half_leaf_count)\n roll_2 = random.randint(0, max_leaf_count - half_leaf_count)\n return roll_1 + roll_2 or half_leaf_count\n", "def _generate_random_node_values(height):\n \"\"\"Return random node values for building binary trees.\n\n :param height: Height of the binary tree.\n :type height: int\n :return: Randomly generated node values.\n :rtype: [int]\n \"\"\"\n max_node_count = 2 ** (height + 1) - 1\n node_values = list(range(max_node_count))\n random.shuffle(node_values)\n return node_values\n" ]
from __future__ import absolute_import, unicode_literals, division __all__ = ['Node', 'tree', 'bst', 'heap', 'build'] import heapq import random import numbers from binarytree.exceptions import ( TreeHeightError, NodeValueError, NodeIndexError, NodeTypeError, NodeModifyError, NodeNotFoundError, NodeReferenceError, ) def _is_balanced(root): """Return the height if the binary tree is balanced, -1 otherwise. :param root: Root node of the binary tree. :type root: binarytree.Node | None :return: Height if the binary tree is balanced, -1 otherwise. :rtype: int """ if root is None: return 0 left = _is_balanced(root.left) if left < 0: return -1 right = _is_balanced(root.right) if right < 0: return -1 return -1 if abs(left - right) > 1 else max(left, right) + 1 def _is_bst(root, min_value=float('-inf'), max_value=float('inf')): """Check if the binary tree is a BST (binary search tree). :param root: Root node of the binary tree. :type root: binarytree.Node | None :param min_value: Minimum node value seen. :type min_value: int | float :param max_value: Maximum node value seen. :type max_value: int | float :return: True if the binary tree is a BST, False otherwise. :rtype: bool """ if root is None: return True return ( min_value < root.value < max_value and _is_bst(root.left, min_value, root.value) and _is_bst(root.right, root.value, max_value) ) def _validate_tree_height(height): """Check if the height of the binary tree is valid. :param height: Height of the binary tree (must be 0 - 9 inclusive). :type height: int :raise binarytree.exceptions.TreeHeightError: If height is invalid. """ if not (isinstance(height, int) and 0 <= height <= 9): raise TreeHeightError('height must be an int between 0 - 9') def _generate_perfect_bst(height): """Generate a perfect BST (binary search tree) and return its root. :param height: Height of the BST. :type height: int :return: Root node of the BST. :rtype: binarytree.Node """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) return _build_bst_from_sorted_values(node_values) def _build_bst_from_sorted_values(sorted_values): """Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node """ if len(sorted_values) == 0: return None mid_index = len(sorted_values) // 2 root = Node(sorted_values[mid_index]) root.left = _build_bst_from_sorted_values(sorted_values[:mid_index]) root.right = _build_bst_from_sorted_values(sorted_values[mid_index + 1:]) return root def _generate_random_leaf_count(height): """Return a random leaf count for building binary trees. :param height: Height of the binary tree. :type height: int :return: Random leaf count. :rtype: int """ max_leaf_count = 2 ** height half_leaf_count = max_leaf_count // 2 # A very naive way of mimicking normal distribution roll_1 = random.randint(0, half_leaf_count) roll_2 = random.randint(0, max_leaf_count - half_leaf_count) return roll_1 + roll_2 or half_leaf_count def _generate_random_node_values(height): """Return random node values for building binary trees. :param height: Height of the binary tree. :type height: int :return: Randomly generated node values. :rtype: [int] """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) random.shuffle(node_values) return node_values def _build_tree_string(root, curr_index, index=False, delimiter='-'): """Recursively walk down the binary tree and build a pretty-print string. In each recursive call, a "box" of characters visually representing the current (sub)tree is constructed line by line. Each line is padded with whitespaces to ensure all lines in the box have the same length. Then the box, its width, and start-end positions of its root node value repr string (required for drawing branches) are sent up to the parent call. The parent call then combines its left and right sub-boxes to build a larger box etc. :param root: Root node of the binary tree. :type root: binarytree.Node | None :param curr_index: Level-order_ index of the current node (root node is 0). :type curr_index: int :param index: If set to True, include the level-order_ node indexes using the following format: ``{index}{delimiter}{value}`` (default: False). :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: :return: Box of characters visually representing the current subtree, width of the box, and start-end positions of the repr string of the new root node value. :rtype: ([str], int, int, int) .. _Level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ if root is None: return [], 0, 0, 0 line1 = [] line2 = [] if index: node_repr = '{}{}{}'.format(curr_index, delimiter, root.value) else: node_repr = str(root.value) new_root_width = gap_size = len(node_repr) # Get the left and right sub-boxes, their widths, and root repr positions l_box, l_box_width, l_root_start, l_root_end = \ _build_tree_string(root.left, 2 * curr_index + 1, index, delimiter) r_box, r_box_width, r_root_start, r_root_end = \ _build_tree_string(root.right, 2 * curr_index + 2, index, delimiter) # Draw the branch connecting the current root node to the left sub-box # Pad the line with whitespaces where necessary if l_box_width > 0: l_root = (l_root_start + l_root_end) // 2 + 1 line1.append(' ' * (l_root + 1)) line1.append('_' * (l_box_width - l_root)) line2.append(' ' * l_root + '/') line2.append(' ' * (l_box_width - l_root)) new_root_start = l_box_width + 1 gap_size += 1 else: new_root_start = 0 # Draw the representation of the current root node line1.append(node_repr) line2.append(' ' * new_root_width) # Draw the branch connecting the current root node to the right sub-box # Pad the line with whitespaces where necessary if r_box_width > 0: r_root = (r_root_start + r_root_end) // 2 line1.append('_' * r_root) line1.append(' ' * (r_box_width - r_root + 1)) line2.append(' ' * r_root + '\\') line2.append(' ' * (r_box_width - r_root)) gap_size += 1 new_root_end = new_root_start + new_root_width - 1 # Combine the left and right sub-boxes with the branches drawn above gap = ' ' * gap_size new_box = [''.join(line1), ''.join(line2)] for i in range(max(len(l_box), len(r_box))): l_line = l_box[i] if i < len(l_box) else ' ' * l_box_width r_line = r_box[i] if i < len(r_box) else ' ' * r_box_width new_box.append(l_line + gap + r_line) # Return the new box, its width and its root repr positions return new_box, len(new_box[0]), new_root_start, new_root_end def _get_tree_properties(root): """Inspect the binary tree and return its properties (e.g. height). :param root: Root node of the binary tree. :rtype: binarytree.Node :return: Binary tree properties. :rtype: dict """ is_descending = True is_ascending = True min_node_value = root.value max_node_value = root.value size = 0 leaf_count = 0 min_leaf_depth = 0 max_leaf_depth = -1 is_strict = True is_complete = True current_nodes = [root] non_full_node_seen = False while len(current_nodes) > 0: max_leaf_depth += 1 next_nodes = [] for node in current_nodes: size += 1 value = node.value min_node_value = min(value, min_node_value) max_node_value = max(value, max_node_value) # Node is a leaf. if node.left is None and node.right is None: if min_leaf_depth == 0: min_leaf_depth = max_leaf_depth leaf_count += 1 if node.left is not None: if node.left.value > value: is_descending = False elif node.left.value < value: is_ascending = False next_nodes.append(node.left) is_complete = not non_full_node_seen else: non_full_node_seen = True if node.right is not None: if node.right.value > value: is_descending = False elif node.right.value < value: is_ascending = False next_nodes.append(node.right) is_complete = not non_full_node_seen else: non_full_node_seen = True # If we see a node with only one child, it is not strict is_strict &= (node.left is None) == (node.right is None) current_nodes = next_nodes return { 'height': max_leaf_depth, 'size': size, 'is_max_heap': is_complete and is_descending, 'is_min_heap': is_complete and is_ascending, 'is_perfect': leaf_count == 2 ** max_leaf_depth, 'is_strict': is_strict, 'is_complete': is_complete, 'leaf_count': leaf_count, 'min_node_value': min_node_value, 'max_node_value': max_node_value, 'min_leaf_depth': min_leaf_depth, 'max_leaf_depth': max_leaf_depth, } class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result def build(values): """Build a tree from `list representation`_ and return its root node. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :param values: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :type values: [int | float | None] :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.NodeNotFoundError: If the list representation is malformed (e.g. a parent node is missing). **Example**: .. doctest:: >>> from binarytree import build >>> >>> root = build([1, 2, 3, None, 4]) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. doctest:: >>> from binarytree import build >>> >>> root = build([None, 2, 3]) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 0 """ nodes = [None if v is None else Node(v) for v in values] for index in range(1, len(nodes)): node = nodes[index] if node is not None: parent_index = (index - 1) // 2 parent = nodes[parent_index] if parent is None: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) return nodes[0] if nodes else None def bst(height=3, is_perfect=False): """Generate a random BST (binary search tree) and return its root node. :param height: Height of the BST (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect BST with all levels filled is returned. If set to False, a perfect BST may still be generated by chance. :type is_perfect: bool :return: Root node of the BST. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import bst >>> >>> root = bst() >>> >>> root.height 3 >>> root.is_bst True .. doctest:: >>> from binarytree import bst >>> >>> root = bst(10) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) if is_perfect: return _generate_perfect_bst(height) values = _generate_random_node_values(height) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = 'left' if node.value > value else 'right' if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def heap(height=3, is_max=True, is_perfect=False): """Generate a random heap and return its root node. :param height: Height of the heap (default: 3, range: 0 - 9 inclusive). :type height: int :param is_max: If set to True (default: True), generate a max heap. If set to False, generate a min heap. A binary tree with only the root node is considered both a min and max heap. :type is_max: bool :param is_perfect: If set to True (default: False), a perfect heap with all levels filled is returned. If set to False, a perfect heap may still be generated by chance. :type is_perfect: bool :return: Root node of the heap. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import heap >>> >>> root = heap() >>> >>> root.height 3 >>> root.is_max_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(4, is_max=False) >>> >>> root.height 4 >>> root.is_min_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(5, is_max=False, is_perfect=True) >>> >>> root.height 5 >>> root.is_min_heap True >>> root.is_perfect True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(-1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if not is_perfect: # Randomly cut some of the leaf nodes away random_cut = random.randint(2 ** height, len(values)) values = values[:random_cut] if is_max: negated = [-v for v in values] heapq.heapify(negated) return build([-v for v in negated]) else: heapq.heapify(values) return build(values)
joowani/binarytree
binarytree/__init__.py
bst
python
def bst(height=3, is_perfect=False): _validate_tree_height(height) if is_perfect: return _generate_perfect_bst(height) values = _generate_random_node_values(height) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = 'left' if node.value > value else 'right' if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root
Generate a random BST (binary search tree) and return its root node. :param height: Height of the BST (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect BST with all levels filled is returned. If set to False, a perfect BST may still be generated by chance. :type is_perfect: bool :return: Root node of the BST. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import bst >>> >>> root = bst() >>> >>> root.height 3 >>> root.is_bst True .. doctest:: >>> from binarytree import bst >>> >>> root = bst(10) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L1786-L1849
[ "def _validate_tree_height(height):\n \"\"\"Check if the height of the binary tree is valid.\n\n :param height: Height of the binary tree (must be 0 - 9 inclusive).\n :type height: int\n :raise binarytree.exceptions.TreeHeightError: If height is invalid.\n \"\"\"\n if not (isinstance(height, int) and 0 <= height <= 9):\n raise TreeHeightError('height must be an int between 0 - 9')\n", "def _generate_perfect_bst(height):\n \"\"\"Generate a perfect BST (binary search tree) and return its root.\n\n :param height: Height of the BST.\n :type height: int\n :return: Root node of the BST.\n :rtype: binarytree.Node\n \"\"\"\n max_node_count = 2 ** (height + 1) - 1\n node_values = list(range(max_node_count))\n return _build_bst_from_sorted_values(node_values)\n", "def _generate_random_leaf_count(height):\n \"\"\"Return a random leaf count for building binary trees.\n\n :param height: Height of the binary tree.\n :type height: int\n :return: Random leaf count.\n :rtype: int\n \"\"\"\n max_leaf_count = 2 ** height\n half_leaf_count = max_leaf_count // 2\n\n # A very naive way of mimicking normal distribution\n roll_1 = random.randint(0, half_leaf_count)\n roll_2 = random.randint(0, max_leaf_count - half_leaf_count)\n return roll_1 + roll_2 or half_leaf_count\n", "def _generate_random_node_values(height):\n \"\"\"Return random node values for building binary trees.\n\n :param height: Height of the binary tree.\n :type height: int\n :return: Randomly generated node values.\n :rtype: [int]\n \"\"\"\n max_node_count = 2 ** (height + 1) - 1\n node_values = list(range(max_node_count))\n random.shuffle(node_values)\n return node_values\n" ]
from __future__ import absolute_import, unicode_literals, division __all__ = ['Node', 'tree', 'bst', 'heap', 'build'] import heapq import random import numbers from binarytree.exceptions import ( TreeHeightError, NodeValueError, NodeIndexError, NodeTypeError, NodeModifyError, NodeNotFoundError, NodeReferenceError, ) def _is_balanced(root): """Return the height if the binary tree is balanced, -1 otherwise. :param root: Root node of the binary tree. :type root: binarytree.Node | None :return: Height if the binary tree is balanced, -1 otherwise. :rtype: int """ if root is None: return 0 left = _is_balanced(root.left) if left < 0: return -1 right = _is_balanced(root.right) if right < 0: return -1 return -1 if abs(left - right) > 1 else max(left, right) + 1 def _is_bst(root, min_value=float('-inf'), max_value=float('inf')): """Check if the binary tree is a BST (binary search tree). :param root: Root node of the binary tree. :type root: binarytree.Node | None :param min_value: Minimum node value seen. :type min_value: int | float :param max_value: Maximum node value seen. :type max_value: int | float :return: True if the binary tree is a BST, False otherwise. :rtype: bool """ if root is None: return True return ( min_value < root.value < max_value and _is_bst(root.left, min_value, root.value) and _is_bst(root.right, root.value, max_value) ) def _validate_tree_height(height): """Check if the height of the binary tree is valid. :param height: Height of the binary tree (must be 0 - 9 inclusive). :type height: int :raise binarytree.exceptions.TreeHeightError: If height is invalid. """ if not (isinstance(height, int) and 0 <= height <= 9): raise TreeHeightError('height must be an int between 0 - 9') def _generate_perfect_bst(height): """Generate a perfect BST (binary search tree) and return its root. :param height: Height of the BST. :type height: int :return: Root node of the BST. :rtype: binarytree.Node """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) return _build_bst_from_sorted_values(node_values) def _build_bst_from_sorted_values(sorted_values): """Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node """ if len(sorted_values) == 0: return None mid_index = len(sorted_values) // 2 root = Node(sorted_values[mid_index]) root.left = _build_bst_from_sorted_values(sorted_values[:mid_index]) root.right = _build_bst_from_sorted_values(sorted_values[mid_index + 1:]) return root def _generate_random_leaf_count(height): """Return a random leaf count for building binary trees. :param height: Height of the binary tree. :type height: int :return: Random leaf count. :rtype: int """ max_leaf_count = 2 ** height half_leaf_count = max_leaf_count // 2 # A very naive way of mimicking normal distribution roll_1 = random.randint(0, half_leaf_count) roll_2 = random.randint(0, max_leaf_count - half_leaf_count) return roll_1 + roll_2 or half_leaf_count def _generate_random_node_values(height): """Return random node values for building binary trees. :param height: Height of the binary tree. :type height: int :return: Randomly generated node values. :rtype: [int] """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) random.shuffle(node_values) return node_values def _build_tree_string(root, curr_index, index=False, delimiter='-'): """Recursively walk down the binary tree and build a pretty-print string. In each recursive call, a "box" of characters visually representing the current (sub)tree is constructed line by line. Each line is padded with whitespaces to ensure all lines in the box have the same length. Then the box, its width, and start-end positions of its root node value repr string (required for drawing branches) are sent up to the parent call. The parent call then combines its left and right sub-boxes to build a larger box etc. :param root: Root node of the binary tree. :type root: binarytree.Node | None :param curr_index: Level-order_ index of the current node (root node is 0). :type curr_index: int :param index: If set to True, include the level-order_ node indexes using the following format: ``{index}{delimiter}{value}`` (default: False). :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: :return: Box of characters visually representing the current subtree, width of the box, and start-end positions of the repr string of the new root node value. :rtype: ([str], int, int, int) .. _Level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ if root is None: return [], 0, 0, 0 line1 = [] line2 = [] if index: node_repr = '{}{}{}'.format(curr_index, delimiter, root.value) else: node_repr = str(root.value) new_root_width = gap_size = len(node_repr) # Get the left and right sub-boxes, their widths, and root repr positions l_box, l_box_width, l_root_start, l_root_end = \ _build_tree_string(root.left, 2 * curr_index + 1, index, delimiter) r_box, r_box_width, r_root_start, r_root_end = \ _build_tree_string(root.right, 2 * curr_index + 2, index, delimiter) # Draw the branch connecting the current root node to the left sub-box # Pad the line with whitespaces where necessary if l_box_width > 0: l_root = (l_root_start + l_root_end) // 2 + 1 line1.append(' ' * (l_root + 1)) line1.append('_' * (l_box_width - l_root)) line2.append(' ' * l_root + '/') line2.append(' ' * (l_box_width - l_root)) new_root_start = l_box_width + 1 gap_size += 1 else: new_root_start = 0 # Draw the representation of the current root node line1.append(node_repr) line2.append(' ' * new_root_width) # Draw the branch connecting the current root node to the right sub-box # Pad the line with whitespaces where necessary if r_box_width > 0: r_root = (r_root_start + r_root_end) // 2 line1.append('_' * r_root) line1.append(' ' * (r_box_width - r_root + 1)) line2.append(' ' * r_root + '\\') line2.append(' ' * (r_box_width - r_root)) gap_size += 1 new_root_end = new_root_start + new_root_width - 1 # Combine the left and right sub-boxes with the branches drawn above gap = ' ' * gap_size new_box = [''.join(line1), ''.join(line2)] for i in range(max(len(l_box), len(r_box))): l_line = l_box[i] if i < len(l_box) else ' ' * l_box_width r_line = r_box[i] if i < len(r_box) else ' ' * r_box_width new_box.append(l_line + gap + r_line) # Return the new box, its width and its root repr positions return new_box, len(new_box[0]), new_root_start, new_root_end def _get_tree_properties(root): """Inspect the binary tree and return its properties (e.g. height). :param root: Root node of the binary tree. :rtype: binarytree.Node :return: Binary tree properties. :rtype: dict """ is_descending = True is_ascending = True min_node_value = root.value max_node_value = root.value size = 0 leaf_count = 0 min_leaf_depth = 0 max_leaf_depth = -1 is_strict = True is_complete = True current_nodes = [root] non_full_node_seen = False while len(current_nodes) > 0: max_leaf_depth += 1 next_nodes = [] for node in current_nodes: size += 1 value = node.value min_node_value = min(value, min_node_value) max_node_value = max(value, max_node_value) # Node is a leaf. if node.left is None and node.right is None: if min_leaf_depth == 0: min_leaf_depth = max_leaf_depth leaf_count += 1 if node.left is not None: if node.left.value > value: is_descending = False elif node.left.value < value: is_ascending = False next_nodes.append(node.left) is_complete = not non_full_node_seen else: non_full_node_seen = True if node.right is not None: if node.right.value > value: is_descending = False elif node.right.value < value: is_ascending = False next_nodes.append(node.right) is_complete = not non_full_node_seen else: non_full_node_seen = True # If we see a node with only one child, it is not strict is_strict &= (node.left is None) == (node.right is None) current_nodes = next_nodes return { 'height': max_leaf_depth, 'size': size, 'is_max_heap': is_complete and is_descending, 'is_min_heap': is_complete and is_ascending, 'is_perfect': leaf_count == 2 ** max_leaf_depth, 'is_strict': is_strict, 'is_complete': is_complete, 'leaf_count': leaf_count, 'min_node_value': min_node_value, 'max_node_value': max_node_value, 'min_leaf_depth': min_leaf_depth, 'max_leaf_depth': max_leaf_depth, } class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result def build(values): """Build a tree from `list representation`_ and return its root node. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :param values: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :type values: [int | float | None] :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.NodeNotFoundError: If the list representation is malformed (e.g. a parent node is missing). **Example**: .. doctest:: >>> from binarytree import build >>> >>> root = build([1, 2, 3, None, 4]) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. doctest:: >>> from binarytree import build >>> >>> root = build([None, 2, 3]) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 0 """ nodes = [None if v is None else Node(v) for v in values] for index in range(1, len(nodes)): node = nodes[index] if node is not None: parent_index = (index - 1) // 2 parent = nodes[parent_index] if parent is None: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) return nodes[0] if nodes else None def tree(height=3, is_perfect=False): """Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary tree may still be generated by chance. :type is_perfect: bool :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import tree >>> >>> root = tree() >>> >>> root.height 3 .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=5, is_perfect=True) >>> >>> root.height 5 >>> root.is_perfect True .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if is_perfect: return build(values) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = random.choice(('left', 'right')) if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def heap(height=3, is_max=True, is_perfect=False): """Generate a random heap and return its root node. :param height: Height of the heap (default: 3, range: 0 - 9 inclusive). :type height: int :param is_max: If set to True (default: True), generate a max heap. If set to False, generate a min heap. A binary tree with only the root node is considered both a min and max heap. :type is_max: bool :param is_perfect: If set to True (default: False), a perfect heap with all levels filled is returned. If set to False, a perfect heap may still be generated by chance. :type is_perfect: bool :return: Root node of the heap. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import heap >>> >>> root = heap() >>> >>> root.height 3 >>> root.is_max_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(4, is_max=False) >>> >>> root.height 4 >>> root.is_min_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(5, is_max=False, is_perfect=True) >>> >>> root.height 5 >>> root.is_min_heap True >>> root.is_perfect True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(-1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if not is_perfect: # Randomly cut some of the leaf nodes away random_cut = random.randint(2 ** height, len(values)) values = values[:random_cut] if is_max: negated = [-v for v in values] heapq.heapify(negated) return build([-v for v in negated]) else: heapq.heapify(values) return build(values)
joowani/binarytree
binarytree/__init__.py
heap
python
def heap(height=3, is_max=True, is_perfect=False): _validate_tree_height(height) values = _generate_random_node_values(height) if not is_perfect: # Randomly cut some of the leaf nodes away random_cut = random.randint(2 ** height, len(values)) values = values[:random_cut] if is_max: negated = [-v for v in values] heapq.heapify(negated) return build([-v for v in negated]) else: heapq.heapify(values) return build(values)
Generate a random heap and return its root node. :param height: Height of the heap (default: 3, range: 0 - 9 inclusive). :type height: int :param is_max: If set to True (default: True), generate a max heap. If set to False, generate a min heap. A binary tree with only the root node is considered both a min and max heap. :type is_max: bool :param is_perfect: If set to True (default: False), a perfect heap with all levels filled is returned. If set to False, a perfect heap may still be generated by chance. :type is_perfect: bool :return: Root node of the heap. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import heap >>> >>> root = heap() >>> >>> root.height 3 >>> root.is_max_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(4, is_max=False) >>> >>> root.height 4 >>> root.is_min_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(5, is_max=False, is_perfect=True) >>> >>> root.height 5 >>> root.is_min_heap True >>> root.is_perfect True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(-1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L1852-L1929
[ "def build(values):\n \"\"\"Build a tree from `list representation`_ and return its root node.\n\n .. _list representation:\n https://en.wikipedia.org/wiki/Binary_tree#Arrays\n\n :param values: List representation of the binary tree, which is a list of\n node values in breadth-first order starting from the root (current\n node). If a node is at index i, its left child is always at 2i + 1,\n right child at 2i + 2, and parent at floor((i - 1) / 2). None indicates\n absence of a node at that index. See example below for an illustration.\n :type values: [int | float | None]\n :return: Root node of the binary tree.\n :rtype: binarytree.Node\n :raise binarytree.exceptions.NodeNotFoundError: If the list representation\n is malformed (e.g. a parent node is missing).\n\n **Example**:\n\n .. doctest::\n\n >>> from binarytree import build\n >>>\n >>> root = build([1, 2, 3, None, 4])\n >>>\n >>> print(root)\n <BLANKLINE>\n __1\n / \\\\\n 2 3\n \\\\\n 4\n <BLANKLINE>\n\n .. doctest::\n\n >>> from binarytree import build\n >>>\n >>> root = build([None, 2, 3]) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n NodeNotFoundError: parent node missing at index 0\n \"\"\"\n nodes = [None if v is None else Node(v) for v in values]\n\n for index in range(1, len(nodes)):\n node = nodes[index]\n if node is not None:\n parent_index = (index - 1) // 2\n parent = nodes[parent_index]\n if parent is None:\n raise NodeNotFoundError(\n 'parent node missing at index {}'.format(parent_index))\n setattr(parent, 'left' if index % 2 else 'right', node)\n\n return nodes[0] if nodes else None\n", "def _validate_tree_height(height):\n \"\"\"Check if the height of the binary tree is valid.\n\n :param height: Height of the binary tree (must be 0 - 9 inclusive).\n :type height: int\n :raise binarytree.exceptions.TreeHeightError: If height is invalid.\n \"\"\"\n if not (isinstance(height, int) and 0 <= height <= 9):\n raise TreeHeightError('height must be an int between 0 - 9')\n", "def _generate_random_node_values(height):\n \"\"\"Return random node values for building binary trees.\n\n :param height: Height of the binary tree.\n :type height: int\n :return: Randomly generated node values.\n :rtype: [int]\n \"\"\"\n max_node_count = 2 ** (height + 1) - 1\n node_values = list(range(max_node_count))\n random.shuffle(node_values)\n return node_values\n" ]
from __future__ import absolute_import, unicode_literals, division __all__ = ['Node', 'tree', 'bst', 'heap', 'build'] import heapq import random import numbers from binarytree.exceptions import ( TreeHeightError, NodeValueError, NodeIndexError, NodeTypeError, NodeModifyError, NodeNotFoundError, NodeReferenceError, ) def _is_balanced(root): """Return the height if the binary tree is balanced, -1 otherwise. :param root: Root node of the binary tree. :type root: binarytree.Node | None :return: Height if the binary tree is balanced, -1 otherwise. :rtype: int """ if root is None: return 0 left = _is_balanced(root.left) if left < 0: return -1 right = _is_balanced(root.right) if right < 0: return -1 return -1 if abs(left - right) > 1 else max(left, right) + 1 def _is_bst(root, min_value=float('-inf'), max_value=float('inf')): """Check if the binary tree is a BST (binary search tree). :param root: Root node of the binary tree. :type root: binarytree.Node | None :param min_value: Minimum node value seen. :type min_value: int | float :param max_value: Maximum node value seen. :type max_value: int | float :return: True if the binary tree is a BST, False otherwise. :rtype: bool """ if root is None: return True return ( min_value < root.value < max_value and _is_bst(root.left, min_value, root.value) and _is_bst(root.right, root.value, max_value) ) def _validate_tree_height(height): """Check if the height of the binary tree is valid. :param height: Height of the binary tree (must be 0 - 9 inclusive). :type height: int :raise binarytree.exceptions.TreeHeightError: If height is invalid. """ if not (isinstance(height, int) and 0 <= height <= 9): raise TreeHeightError('height must be an int between 0 - 9') def _generate_perfect_bst(height): """Generate a perfect BST (binary search tree) and return its root. :param height: Height of the BST. :type height: int :return: Root node of the BST. :rtype: binarytree.Node """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) return _build_bst_from_sorted_values(node_values) def _build_bst_from_sorted_values(sorted_values): """Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node """ if len(sorted_values) == 0: return None mid_index = len(sorted_values) // 2 root = Node(sorted_values[mid_index]) root.left = _build_bst_from_sorted_values(sorted_values[:mid_index]) root.right = _build_bst_from_sorted_values(sorted_values[mid_index + 1:]) return root def _generate_random_leaf_count(height): """Return a random leaf count for building binary trees. :param height: Height of the binary tree. :type height: int :return: Random leaf count. :rtype: int """ max_leaf_count = 2 ** height half_leaf_count = max_leaf_count // 2 # A very naive way of mimicking normal distribution roll_1 = random.randint(0, half_leaf_count) roll_2 = random.randint(0, max_leaf_count - half_leaf_count) return roll_1 + roll_2 or half_leaf_count def _generate_random_node_values(height): """Return random node values for building binary trees. :param height: Height of the binary tree. :type height: int :return: Randomly generated node values. :rtype: [int] """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) random.shuffle(node_values) return node_values def _build_tree_string(root, curr_index, index=False, delimiter='-'): """Recursively walk down the binary tree and build a pretty-print string. In each recursive call, a "box" of characters visually representing the current (sub)tree is constructed line by line. Each line is padded with whitespaces to ensure all lines in the box have the same length. Then the box, its width, and start-end positions of its root node value repr string (required for drawing branches) are sent up to the parent call. The parent call then combines its left and right sub-boxes to build a larger box etc. :param root: Root node of the binary tree. :type root: binarytree.Node | None :param curr_index: Level-order_ index of the current node (root node is 0). :type curr_index: int :param index: If set to True, include the level-order_ node indexes using the following format: ``{index}{delimiter}{value}`` (default: False). :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: :return: Box of characters visually representing the current subtree, width of the box, and start-end positions of the repr string of the new root node value. :rtype: ([str], int, int, int) .. _Level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ if root is None: return [], 0, 0, 0 line1 = [] line2 = [] if index: node_repr = '{}{}{}'.format(curr_index, delimiter, root.value) else: node_repr = str(root.value) new_root_width = gap_size = len(node_repr) # Get the left and right sub-boxes, their widths, and root repr positions l_box, l_box_width, l_root_start, l_root_end = \ _build_tree_string(root.left, 2 * curr_index + 1, index, delimiter) r_box, r_box_width, r_root_start, r_root_end = \ _build_tree_string(root.right, 2 * curr_index + 2, index, delimiter) # Draw the branch connecting the current root node to the left sub-box # Pad the line with whitespaces where necessary if l_box_width > 0: l_root = (l_root_start + l_root_end) // 2 + 1 line1.append(' ' * (l_root + 1)) line1.append('_' * (l_box_width - l_root)) line2.append(' ' * l_root + '/') line2.append(' ' * (l_box_width - l_root)) new_root_start = l_box_width + 1 gap_size += 1 else: new_root_start = 0 # Draw the representation of the current root node line1.append(node_repr) line2.append(' ' * new_root_width) # Draw the branch connecting the current root node to the right sub-box # Pad the line with whitespaces where necessary if r_box_width > 0: r_root = (r_root_start + r_root_end) // 2 line1.append('_' * r_root) line1.append(' ' * (r_box_width - r_root + 1)) line2.append(' ' * r_root + '\\') line2.append(' ' * (r_box_width - r_root)) gap_size += 1 new_root_end = new_root_start + new_root_width - 1 # Combine the left and right sub-boxes with the branches drawn above gap = ' ' * gap_size new_box = [''.join(line1), ''.join(line2)] for i in range(max(len(l_box), len(r_box))): l_line = l_box[i] if i < len(l_box) else ' ' * l_box_width r_line = r_box[i] if i < len(r_box) else ' ' * r_box_width new_box.append(l_line + gap + r_line) # Return the new box, its width and its root repr positions return new_box, len(new_box[0]), new_root_start, new_root_end def _get_tree_properties(root): """Inspect the binary tree and return its properties (e.g. height). :param root: Root node of the binary tree. :rtype: binarytree.Node :return: Binary tree properties. :rtype: dict """ is_descending = True is_ascending = True min_node_value = root.value max_node_value = root.value size = 0 leaf_count = 0 min_leaf_depth = 0 max_leaf_depth = -1 is_strict = True is_complete = True current_nodes = [root] non_full_node_seen = False while len(current_nodes) > 0: max_leaf_depth += 1 next_nodes = [] for node in current_nodes: size += 1 value = node.value min_node_value = min(value, min_node_value) max_node_value = max(value, max_node_value) # Node is a leaf. if node.left is None and node.right is None: if min_leaf_depth == 0: min_leaf_depth = max_leaf_depth leaf_count += 1 if node.left is not None: if node.left.value > value: is_descending = False elif node.left.value < value: is_ascending = False next_nodes.append(node.left) is_complete = not non_full_node_seen else: non_full_node_seen = True if node.right is not None: if node.right.value > value: is_descending = False elif node.right.value < value: is_ascending = False next_nodes.append(node.right) is_complete = not non_full_node_seen else: non_full_node_seen = True # If we see a node with only one child, it is not strict is_strict &= (node.left is None) == (node.right is None) current_nodes = next_nodes return { 'height': max_leaf_depth, 'size': size, 'is_max_heap': is_complete and is_descending, 'is_min_heap': is_complete and is_ascending, 'is_perfect': leaf_count == 2 ** max_leaf_depth, 'is_strict': is_strict, 'is_complete': is_complete, 'leaf_count': leaf_count, 'min_node_value': min_node_value, 'max_node_value': max_node_value, 'min_leaf_depth': min_leaf_depth, 'max_leaf_depth': max_leaf_depth, } class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result def build(values): """Build a tree from `list representation`_ and return its root node. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :param values: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :type values: [int | float | None] :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.NodeNotFoundError: If the list representation is malformed (e.g. a parent node is missing). **Example**: .. doctest:: >>> from binarytree import build >>> >>> root = build([1, 2, 3, None, 4]) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. doctest:: >>> from binarytree import build >>> >>> root = build([None, 2, 3]) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 0 """ nodes = [None if v is None else Node(v) for v in values] for index in range(1, len(nodes)): node = nodes[index] if node is not None: parent_index = (index - 1) // 2 parent = nodes[parent_index] if parent is None: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) return nodes[0] if nodes else None def tree(height=3, is_perfect=False): """Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary tree may still be generated by chance. :type is_perfect: bool :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import tree >>> >>> root = tree() >>> >>> root.height 3 .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=5, is_perfect=True) >>> >>> root.height 5 >>> root.is_perfect True .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if is_perfect: return build(values) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = random.choice(('left', 'right')) if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root def bst(height=3, is_perfect=False): """Generate a random BST (binary search tree) and return its root node. :param height: Height of the BST (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect BST with all levels filled is returned. If set to False, a perfect BST may still be generated by chance. :type is_perfect: bool :return: Root node of the BST. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import bst >>> >>> root = bst() >>> >>> root.height 3 >>> root.is_bst True .. doctest:: >>> from binarytree import bst >>> >>> root = bst(10) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) if is_perfect: return _generate_perfect_bst(height) values = _generate_random_node_values(height) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = 'left' if node.value > value else 'right' if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root
joowani/binarytree
binarytree/__init__.py
Node.pprint
python
def pprint(self, index=False, delimiter='-'): lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines)))
Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L700-L746
[ "def _build_tree_string(root, curr_index, index=False, delimiter='-'):\n \"\"\"Recursively walk down the binary tree and build a pretty-print string.\n\n In each recursive call, a \"box\" of characters visually representing the\n current (sub)tree is constructed line by line. Each line is padded with\n whitespaces to ensure all lines in the box have the same length. Then the\n box, its width, and start-end positions of its root node value repr string\n (required for drawing branches) are sent up to the parent call. The parent\n call then combines its left and right sub-boxes to build a larger box etc.\n\n :param root: Root node of the binary tree.\n :type root: binarytree.Node | None\n :param curr_index: Level-order_ index of the current node (root node is 0).\n :type curr_index: int\n :param index: If set to True, include the level-order_ node indexes using\n the following format: ``{index}{delimiter}{value}`` (default: False).\n :type index: bool\n :param delimiter: Delimiter character between the node index and the node\n value (default: '-').\n :type delimiter:\n :return: Box of characters visually representing the current subtree, width\n of the box, and start-end positions of the repr string of the new root\n node value.\n :rtype: ([str], int, int, int)\n\n .. _Level-order:\n https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search\n \"\"\"\n if root is None:\n return [], 0, 0, 0\n\n line1 = []\n line2 = []\n if index:\n node_repr = '{}{}{}'.format(curr_index, delimiter, root.value)\n else:\n node_repr = str(root.value)\n\n new_root_width = gap_size = len(node_repr)\n\n # Get the left and right sub-boxes, their widths, and root repr positions\n l_box, l_box_width, l_root_start, l_root_end = \\\n _build_tree_string(root.left, 2 * curr_index + 1, index, delimiter)\n r_box, r_box_width, r_root_start, r_root_end = \\\n _build_tree_string(root.right, 2 * curr_index + 2, index, delimiter)\n\n # Draw the branch connecting the current root node to the left sub-box\n # Pad the line with whitespaces where necessary\n if l_box_width > 0:\n l_root = (l_root_start + l_root_end) // 2 + 1\n line1.append(' ' * (l_root + 1))\n line1.append('_' * (l_box_width - l_root))\n line2.append(' ' * l_root + '/')\n line2.append(' ' * (l_box_width - l_root))\n new_root_start = l_box_width + 1\n gap_size += 1\n else:\n new_root_start = 0\n\n # Draw the representation of the current root node\n line1.append(node_repr)\n line2.append(' ' * new_root_width)\n\n # Draw the branch connecting the current root node to the right sub-box\n # Pad the line with whitespaces where necessary\n if r_box_width > 0:\n r_root = (r_root_start + r_root_end) // 2\n line1.append('_' * r_root)\n line1.append(' ' * (r_box_width - r_root + 1))\n line2.append(' ' * r_root + '\\\\')\n line2.append(' ' * (r_box_width - r_root))\n gap_size += 1\n new_root_end = new_root_start + new_root_width - 1\n\n # Combine the left and right sub-boxes with the branches drawn above\n gap = ' ' * gap_size\n new_box = [''.join(line1), ''.join(line2)]\n for i in range(max(len(l_box), len(r_box))):\n l_line = l_box[i] if i < len(l_box) else ' ' * l_box_width\n r_line = r_box[i] if i < len(r_box) else ' ' * r_box_width\n new_box.append(l_line + gap + r_line)\n\n # Return the new box, its width and its root repr positions\n return new_box, len(new_box[0]), new_root_start, new_root_end\n" ]
class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result
joowani/binarytree
binarytree/__init__.py
Node.validate
python
def validate(self): has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes
Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L748-L801
null
class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result
joowani/binarytree
binarytree/__init__.py
Node.values
python
def values(self): current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values
Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4]
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L804-L857
null
class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result
joowani/binarytree
binarytree/__init__.py
Node.leaves
python
def leaves(self): current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves
Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)]
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L860-L904
null
class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result
joowani/binarytree
binarytree/__init__.py
Node.properties
python
def properties(self): properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties
Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L1388-L1441
[ "def _is_balanced(root):\n \"\"\"Return the height if the binary tree is balanced, -1 otherwise.\n\n :param root: Root node of the binary tree.\n :type root: binarytree.Node | None\n :return: Height if the binary tree is balanced, -1 otherwise.\n :rtype: int\n \"\"\"\n if root is None:\n return 0\n left = _is_balanced(root.left)\n if left < 0:\n return -1\n right = _is_balanced(root.right)\n if right < 0:\n return -1\n return -1 if abs(left - right) > 1 else max(left, right) + 1\n", "def _is_bst(root, min_value=float('-inf'), max_value=float('inf')):\n \"\"\"Check if the binary tree is a BST (binary search tree).\n\n :param root: Root node of the binary tree.\n :type root: binarytree.Node | None\n :param min_value: Minimum node value seen.\n :type min_value: int | float\n :param max_value: Maximum node value seen.\n :type max_value: int | float\n :return: True if the binary tree is a BST, False otherwise.\n :rtype: bool\n \"\"\"\n if root is None:\n return True\n return (\n min_value < root.value < max_value and\n _is_bst(root.left, min_value, root.value) and\n _is_bst(root.right, root.value, max_value)\n )\n", "def _get_tree_properties(root):\n \"\"\"Inspect the binary tree and return its properties (e.g. height).\n\n :param root: Root node of the binary tree.\n :rtype: binarytree.Node\n :return: Binary tree properties.\n :rtype: dict\n \"\"\"\n is_descending = True\n is_ascending = True\n min_node_value = root.value\n max_node_value = root.value\n size = 0\n leaf_count = 0\n min_leaf_depth = 0\n max_leaf_depth = -1\n is_strict = True\n is_complete = True\n current_nodes = [root]\n non_full_node_seen = False\n\n while len(current_nodes) > 0:\n max_leaf_depth += 1\n next_nodes = []\n\n for node in current_nodes:\n size += 1\n value = node.value\n min_node_value = min(value, min_node_value)\n max_node_value = max(value, max_node_value)\n\n # Node is a leaf.\n if node.left is None and node.right is None:\n if min_leaf_depth == 0:\n min_leaf_depth = max_leaf_depth\n leaf_count += 1\n\n if node.left is not None:\n if node.left.value > value:\n is_descending = False\n elif node.left.value < value:\n is_ascending = False\n next_nodes.append(node.left)\n is_complete = not non_full_node_seen\n else:\n non_full_node_seen = True\n\n if node.right is not None:\n if node.right.value > value:\n is_descending = False\n elif node.right.value < value:\n is_ascending = False\n next_nodes.append(node.right)\n is_complete = not non_full_node_seen\n else:\n non_full_node_seen = True\n\n # If we see a node with only one child, it is not strict\n is_strict &= (node.left is None) == (node.right is None)\n\n current_nodes = next_nodes\n\n return {\n 'height': max_leaf_depth,\n 'size': size,\n 'is_max_heap': is_complete and is_descending,\n 'is_min_heap': is_complete and is_ascending,\n 'is_perfect': leaf_count == 2 ** max_leaf_depth,\n 'is_strict': is_strict,\n 'is_complete': is_complete,\n 'leaf_count': leaf_count,\n 'min_node_value': min_node_value,\n 'max_node_value': max_node_value,\n 'min_leaf_depth': min_leaf_depth,\n 'max_leaf_depth': max_leaf_depth,\n }\n" ]
class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result
joowani/binarytree
binarytree/__init__.py
Node.inorder
python
def inorder(self): node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result
Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)]
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L1444-L1492
null
class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result
joowani/binarytree
binarytree/__init__.py
Node.preorder
python
def preorder(self): node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result
Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)]
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L1495-L1540
null
class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result
joowani/binarytree
binarytree/__init__.py
Node.postorder
python
def postorder(self): node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result
Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)]
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L1543-L1601
null
class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property @property def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result
joowani/binarytree
binarytree/__init__.py
Node.levelorder
python
def levelorder(self): current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result
Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)]
train
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L1604-L1651
null
class Node(object): """Represents a binary tree node. This class provides methods and properties for managing the current node instance, and the binary tree in which the node is the root of. When a docstring in this class mentions "binary tree", it is referring to the current node and its descendants. :param value: Node value (must be a number). :type value: int | float :param left: Left child node (default: None). :type left: binarytree.Node | None :param right: Right child node (default: None). :type right: binarytree.Node | None :raise binarytree.exceptions.NodeTypeError: If left or right child node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). """ def __init__(self, value, left=None, right=None): if not isinstance(value, numbers.Number): raise NodeValueError('node value must be a number') if left is not None and not isinstance(left, Node): raise NodeTypeError('left child must be a Node instance') if right is not None and not isinstance(right, Node): raise NodeTypeError('right child must be a Node instance') self.value = value self.left = left self.right = right def __repr__(self): """Return the string representation of the current node. :return: String representation. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> Node(1) Node(1) """ return 'Node({})'.format(self.value) def __str__(self): """Return the pretty-print string for the binary tree. :return: Pretty-print string. :rtype: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. note:: To include level-order_ indexes in the output string, use :func:`binarytree.Node.pprint` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, False, '-')[0] return '\n' + '\n'.join((line.rstrip() for line in lines)) def __setattr__(self, attr, obj): """Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str | unicode :param obj: Object to set. :type obj: object :raise binarytree.exceptions.NodeTypeError: If left or right child is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeTypeError: Left child must be a Node instance .. doctest:: >>> from binarytree import Node >>> >>> node = Node(1) >>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeValueError: node value must be a number """ if attr == 'left': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'left child must be a Node instance') elif attr == 'right': if obj is not None and not isinstance(obj, Node): raise NodeTypeError( 'right child must be a Node instance') elif attr == 'value' and not isinstance(obj, numbers.Number): raise NodeValueError('node value must be a number') object.__setattr__(self, attr, obj) def __iter__(self): """Iterate through the nodes in the binary tree in level-order_. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: Node iterator. :rtype: (binarytree.Node) **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> [node for node in root] [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: yield node if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes def __len__(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> len(root) 3 .. note:: This method is equivalent to :attr:`binarytree.Node.size`. """ return self.properties['size'] def __getitem__(self, index): """Return the node (or subtree) at the given level-order_ index. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :return: Node (or subtree) at the given index. :rtype: binarytree.Node :raise binarytree.exceptions.NodeIndexError: If node index is invalid. :raise binarytree.exceptions.NodeNotFoundError: If the node is missing. **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] Node(1) >>> root[1] Node(2) >>> root[2] Node(3) >>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 3 """ if not isinstance(index, int) or index < 0: raise NodeIndexError( 'node index must be a non-negative int') current_nodes = [self] current_index = 0 has_more_nodes = True while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if current_index == index: if node is None: break else: return node current_index += 1 if node is None: next_nodes.extend((None, None)) continue next_nodes.extend((node.left, node.right)) if node.left is not None or node.right is not None: has_more_nodes = True current_nodes = next_nodes raise NodeNotFoundError('node missing at index {}'.format(index)) def __setitem__(self, index, node): """Insert a node (or subtree) at the given level-order_ index. * An exception is raised if the parent node is missing. * Any existing node or subtree is overwritten. * Root node (current node) cannot be replaced. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :param node: Node to insert. :type node: binarytree.Node :raise binarytree.exceptions.NodeTypeError: If new node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeNotFoundError: If parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to overwrite the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot modify the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 5 .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> root[1] = Node(4) >>> >>> root.left Node(4) """ if index == 0: raise NodeModifyError('cannot modify the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) def __delitem__(self, index): """Remove the node (or subtree) at the given level-order_ index. * An exception is raised if the target node is missing. * The descendants of the target node (if any) are also removed. * Root node (current node) cannot be deleted. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :param index: Level-order index of the node. :type index: int :raise binarytree.exceptions.NodeNotFoundError: If the target node or its parent is missing. :raise binarytree.exceptions.NodeModifyError: If user attempts to delete the root node (current node). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeModifyError: cannot delete the root node .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> >>> del root[2] >>> >>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: node missing at index 2 """ if index == 0: raise NodeModifyError('cannot delete the root node') parent_index = (index - 1) // 2 try: parent = self.__getitem__(parent_index) except NodeNotFoundError: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) child_attr = 'left' if index % 2 == 1 else 'right' if getattr(parent, child_attr) is None: raise NodeNotFoundError( 'no node to delete at index {}'.format(index)) setattr(parent, child_attr, None) def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines))) def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes @property def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values @property def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves @property def levels(self): """Return the nodes in the binary tree level by level. :return: Lists of nodes level by level. :rtype: [[binarytree.Node]] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> >>> root.levels [[Node(1)], [Node(2), Node(3)], [Node(4)]] """ current_nodes = [self] levels = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) levels.append(current_nodes) current_nodes = next_nodes return levels @property def height(self): """Return the height of the binary tree. Height of a binary tree is the number of edges on the longest path between the root node and a leaf node. Binary tree with just a single node has a height of 0. :return: Height of the binary tree. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.height 2 .. note:: A binary tree with only a root node has a height of 0. """ return _get_tree_properties(self)['height'] @property def size(self): """Return the total number of nodes in the binary tree. :return: Total number of nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.size 4 .. note:: This method is equivalent to :func:`binarytree.Node.__len__`. """ return _get_tree_properties(self)['size'] @property def leaf_count(self): """Return the total number of leaf nodes in the binary tree. A leaf node is a node with no child nodes. :return: Total number of leaf nodes. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.leaf_count 2 """ return _get_tree_properties(self)['leaf_count'] @property def is_balanced(self): """Check if the binary tree is height-balanced. A binary tree is height-balanced if it meets the following criteria: * Left subtree is height-balanced. * Right subtree is height-balanced. * The difference between heights of left and right subtrees is no more than 1. * An empty binary tree is always height-balanced. :return: True if the binary tree is balanced, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.left.left = Node(3) >>> >>> print(root) <BLANKLINE> 1 / 2 / 3 <BLANKLINE> >>> root.is_balanced False """ return _is_balanced(self) >= 0 @property def is_bst(self): """Check if the binary tree is a BST_ (binary search tree). :return: True if the binary tree is a BST_, False otherwise. :rtype: bool .. _BST: https://en.wikipedia.org/wiki/Binary_search_tree **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(2) >>> root.left = Node(1) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 2 / \\ 1 3 <BLANKLINE> >>> root.is_bst True """ return _is_bst(self, float('-inf'), float('inf')) @property def is_max_heap(self): """Check if the binary tree is a `max heap`_. :return: True if the binary tree is a `max heap`_, False otherwise. :rtype: bool .. _max heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(3) >>> root.left = Node(1) >>> root.right = Node(2) >>> >>> print(root) <BLANKLINE> 3 / \\ 1 2 <BLANKLINE> >>> root.is_max_heap True """ return _get_tree_properties(self)['is_max_heap'] @property def is_min_heap(self): """Check if the binary tree is a `min heap`_. :return: True if the binary tree is a `min heap`_, False otherwise. :rtype: bool .. _min heap: https://en.wikipedia.org/wiki/Min-max_heap **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> print(root) <BLANKLINE> 1 / \\ 2 3 <BLANKLINE> >>> root.is_min_heap True """ return _get_tree_properties(self)['is_min_heap'] @property def is_perfect(self): """Check if the binary tree is perfect. A binary tree is perfect if all its levels are completely filled. See example below for an illustration. :return: True if the binary tree is perfect, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> root.right.left = Node(6) >>> root.right.right = Node(7) >>> >>> print(root) <BLANKLINE> __1__ / \\ 2 3 / \\ / \\ 4 5 6 7 <BLANKLINE> >>> root.is_perfect True """ return _get_tree_properties(self)['is_perfect'] @property def is_strict(self): """Check if the binary tree is strict. A binary tree is strict if all its non-leaf nodes have both the left and right child nodes. :return: True if the binary tree is strict, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_strict True """ return _get_tree_properties(self)['is_strict'] @property def is_complete(self): """Check if the binary tree is complete. A binary tree is complete if it meets the following criteria: * All levels except possibly the last are completely filled. * Last level is left-justified. :return: True if the binary tree is complete, False otherwise. :rtype: bool **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.is_complete True """ return _get_tree_properties(self)['is_complete'] @property def min_node_value(self): """Return the minimum node value of the binary tree. :return: Minimum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.min_node_value 1 """ return _get_tree_properties(self)['min_node_value'] @property def max_node_value(self): """Return the maximum node value of the binary tree. :return: Maximum node value. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> >>> root.max_node_value 3 """ return _get_tree_properties(self)['max_node_value'] @property def max_leaf_depth(self): """Return the maximum leaf node depth of the binary tree. :return: Maximum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.max_leaf_depth 3 """ return _get_tree_properties(self)['max_leaf_depth'] @property def min_leaf_depth(self): """Return the minimum leaf node depth of the binary tree. :return: Minimum leaf node depth. :rtype: int **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.right.left = Node(4) >>> root.right.left.left = Node(5) >>> >>> print(root) <BLANKLINE> 1____ / \\ 2 3 / 4 / 5 <BLANKLINE> >>> root.min_leaf_depth 1 """ return _get_tree_properties(self)['min_leaf_depth'] @property def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties @property def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result @property def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result @property def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result @property
PX4/pyulog
pyulog/ulog2kml.py
main
python
def main(): parser = argparse.ArgumentParser(description='Convert ULog to KML') parser.add_argument('filename', metavar='file.ulg', help='ULog input file') parser.add_argument('-o', '--output', dest='output_filename', help="output filename", default='track.kml') parser.add_argument('--topic', dest='topic_name', help="topic name with position data (default=vehicle_gps_position)", default='vehicle_gps_position') parser.add_argument('--camera-trigger', dest='camera_trigger', help="Camera trigger topic name (e.g. camera_capture)", default=None) args = parser.parse_args() convert_ulog2kml(args.filename, args.output_filename, position_topic_name=args.topic_name, camera_trigger_topic_name=args.camera_trigger)
Command line interface
train
https://github.com/PX4/pyulog/blob/3bc4f9338d30e2e0a0dfbed58f54d200967e5056/pyulog/ulog2kml.py#L18-L37
[ "def convert_ulog2kml(ulog_file_name, output_file_name, position_topic_name=\n 'vehicle_gps_position', colors=_kml_default_colors, altitude_offset=0,\n minimum_interval_s=0.1, style=None, camera_trigger_topic_name=None):\n \"\"\"\n Coverts and ULog file to a CSV file.\n\n :param ulog_file_name: The ULog filename to open and read\n :param output_file_name: KML Output file name\n :param position_topic_name: either name of a topic (must have 'lon', 'lat' &\n 'alt' fields), or a list of topic names\n :param colors: lambda function with flight mode (int) (or -1) as input and\n returns a color (eg 'fffff8f0') (or list of lambda functions if\n multiple position_topic_name's)\n :param altitude_offset: add this offset to the altitude [m]\n :param minimum_interval_s: minimum time difference between two datapoints\n (drop if more points)\n :param style: dictionary with rendering options:\n 'extrude': Bool\n 'line_width': int\n :param camera_trigger_topic_name: name of the camera trigger topic (must\n have 'lon', 'lat' & 'seq')\n\n :return: None\n \"\"\"\n\n default_style = {\n 'extrude': False,\n 'line_width': 3\n }\n\n used_style = default_style\n if style is not None:\n for key in style:\n used_style[key] = style[key]\n\n\n if not isinstance(position_topic_name, list):\n position_topic_name = [position_topic_name]\n colors = [colors]\n\n kml = simplekml.Kml()\n load_topic_names = position_topic_name + ['vehicle_status']\n if camera_trigger_topic_name is not None:\n load_topic_names.append(camera_trigger_topic_name)\n ulog = ULog(ulog_file_name, load_topic_names)\n\n # get flight modes\n try:\n cur_dataset = ulog.get_dataset('vehicle_status')\n flight_mode_changes = cur_dataset.list_value_changes('nav_state')\n flight_mode_changes.append((ulog.last_timestamp, -1))\n except (KeyError, IndexError) as error:\n flight_mode_changes = []\n\n # add the graphs\n for topic, cur_colors in zip(position_topic_name, colors):\n _kml_add_position_data(kml, ulog, topic, cur_colors, used_style,\n altitude_offset, minimum_interval_s, flight_mode_changes)\n\n # camera triggers\n _kml_add_camera_triggers(kml, ulog, camera_trigger_topic_name, altitude_offset)\n\n kml.save(output_file_name)\n" ]
#! /usr/bin/env python """ Convert a ULog file into a KML file (positioning information) """ from __future__ import print_function import argparse import simplekml # pylint: disable=import-error from .core import ULog #pylint: disable=too-many-locals, invalid-name, consider-using-enumerate, too-many-arguments #pylint: disable=unused-variable # alternative example call: # convert_ulog2kml(args.filename, 'test.kml', ['vehicle_global_position', # 'vehicle_gps_position'], [_kml_default_colors, lambda x: simplekml.Color.green]) def _kml_default_colors(x): """ flight mode to color conversion """ x = max([x, 0]) colors_arr = [simplekml.Color.red, simplekml.Color.green, simplekml.Color.blue, simplekml.Color.violet, simplekml.Color.yellow, simplekml.Color.orange, simplekml.Color.burlywood, simplekml.Color.azure, simplekml.Color.lightblue, simplekml.Color.lawngreen, simplekml.Color.indianred, simplekml.Color.hotpink] return colors_arr[x] def convert_ulog2kml(ulog_file_name, output_file_name, position_topic_name= 'vehicle_gps_position', colors=_kml_default_colors, altitude_offset=0, minimum_interval_s=0.1, style=None, camera_trigger_topic_name=None): """ Coverts and ULog file to a CSV file. :param ulog_file_name: The ULog filename to open and read :param output_file_name: KML Output file name :param position_topic_name: either name of a topic (must have 'lon', 'lat' & 'alt' fields), or a list of topic names :param colors: lambda function with flight mode (int) (or -1) as input and returns a color (eg 'fffff8f0') (or list of lambda functions if multiple position_topic_name's) :param altitude_offset: add this offset to the altitude [m] :param minimum_interval_s: minimum time difference between two datapoints (drop if more points) :param style: dictionary with rendering options: 'extrude': Bool 'line_width': int :param camera_trigger_topic_name: name of the camera trigger topic (must have 'lon', 'lat' & 'seq') :return: None """ default_style = { 'extrude': False, 'line_width': 3 } used_style = default_style if style is not None: for key in style: used_style[key] = style[key] if not isinstance(position_topic_name, list): position_topic_name = [position_topic_name] colors = [colors] kml = simplekml.Kml() load_topic_names = position_topic_name + ['vehicle_status'] if camera_trigger_topic_name is not None: load_topic_names.append(camera_trigger_topic_name) ulog = ULog(ulog_file_name, load_topic_names) # get flight modes try: cur_dataset = ulog.get_dataset('vehicle_status') flight_mode_changes = cur_dataset.list_value_changes('nav_state') flight_mode_changes.append((ulog.last_timestamp, -1)) except (KeyError, IndexError) as error: flight_mode_changes = [] # add the graphs for topic, cur_colors in zip(position_topic_name, colors): _kml_add_position_data(kml, ulog, topic, cur_colors, used_style, altitude_offset, minimum_interval_s, flight_mode_changes) # camera triggers _kml_add_camera_triggers(kml, ulog, camera_trigger_topic_name, altitude_offset) kml.save(output_file_name) def _kml_add_camera_triggers(kml, ulog, camera_trigger_topic_name, altitude_offset): """ Add camera trigger points to the map """ data = ulog.data_list topic_instance = 0 cur_dataset = [elem for elem in data if elem.name == camera_trigger_topic_name and elem.multi_id == topic_instance] if len(cur_dataset) > 0: cur_dataset = cur_dataset[0] pos_lon = cur_dataset.data['lon'] pos_lat = cur_dataset.data['lat'] pos_alt = cur_dataset.data['alt'] sequence = cur_dataset.data['seq'] for i in range(len(pos_lon)): pnt = kml.newpoint(name='Camera Trigger '+str(sequence[i])) pnt.coords = [(pos_lon[i], pos_lat[i], pos_alt[i] + altitude_offset)] # Balloons instead of text does not work #pnt.style.balloonstyle.text = 'Camera Trigger '+str(sequence[i]) def _kml_add_position_data(kml, ulog, position_topic_name, colors, style, altitude_offset=0, minimum_interval_s=0.1, flight_mode_changes=None): data = ulog.data_list topic_instance = 0 if flight_mode_changes is None: flight_mode_changes = [] cur_dataset = [elem for elem in data if elem.name == position_topic_name and elem.multi_id == topic_instance] if len(cur_dataset) == 0: raise Exception(position_topic_name+' not found in data') cur_dataset = cur_dataset[0] pos_lon = cur_dataset.data['lon'] pos_lat = cur_dataset.data['lat'] pos_alt = cur_dataset.data['alt'] pos_t = cur_dataset.data['timestamp'] if 'fix_type' in cur_dataset.data: indices = cur_dataset.data['fix_type'] > 2 # use only data with a fix pos_lon = pos_lon[indices] pos_lat = pos_lat[indices] pos_alt = pos_alt[indices] pos_t = pos_t[indices] # scale if it's an integer type lon_type = [f.type_str for f in cur_dataset.field_data if f.field_name == 'lon'] if len(lon_type) > 0 and lon_type[0] == 'int32_t': pos_lon = pos_lon / 1e7 # to degrees pos_lat = pos_lat / 1e7 pos_alt = pos_alt / 1e3 # to meters current_flight_mode = 0 current_flight_mode_idx = 0 if len(flight_mode_changes) > 0: current_flight_mode = flight_mode_changes[0][1] def create_linestring(): """ create a new kml linestring and set rendering options """ name = position_topic_name + ":" + str(current_flight_mode) new_linestring = kml.newlinestring(name=name, altitudemode='absolute') # set rendering options if style['extrude']: new_linestring.extrude = 1 new_linestring.style.linestyle.color = colors(current_flight_mode) new_linestring.style.linestyle.width = style['line_width'] return new_linestring current_kml_linestring = create_linestring() last_t = 0 for i in range(len(pos_lon)): cur_t = pos_t[i] if (cur_t - last_t)/1e6 > minimum_interval_s: # assume timestamp is in [us] pos_data = [pos_lon[i], pos_lat[i], pos_alt[i] + altitude_offset] current_kml_linestring.coords.addcoordinates([pos_data]) last_t = cur_t # flight mode change? while current_flight_mode_idx < len(flight_mode_changes)-1 and \ flight_mode_changes[current_flight_mode_idx+1][0] <= cur_t: current_flight_mode_idx += 1 current_flight_mode = flight_mode_changes[current_flight_mode_idx][1] current_kml_linestring = create_linestring() current_kml_linestring.coords.addcoordinates([pos_data])
PX4/pyulog
pyulog/ulog2kml.py
_kml_default_colors
python
def _kml_default_colors(x): x = max([x, 0]) colors_arr = [simplekml.Color.red, simplekml.Color.green, simplekml.Color.blue, simplekml.Color.violet, simplekml.Color.yellow, simplekml.Color.orange, simplekml.Color.burlywood, simplekml.Color.azure, simplekml.Color.lightblue, simplekml.Color.lawngreen, simplekml.Color.indianred, simplekml.Color.hotpink] return colors_arr[x]
flight mode to color conversion
train
https://github.com/PX4/pyulog/blob/3bc4f9338d30e2e0a0dfbed58f54d200967e5056/pyulog/ulog2kml.py#L44-L51
null
#! /usr/bin/env python """ Convert a ULog file into a KML file (positioning information) """ from __future__ import print_function import argparse import simplekml # pylint: disable=import-error from .core import ULog #pylint: disable=too-many-locals, invalid-name, consider-using-enumerate, too-many-arguments #pylint: disable=unused-variable def main(): """Command line interface""" parser = argparse.ArgumentParser(description='Convert ULog to KML') parser.add_argument('filename', metavar='file.ulg', help='ULog input file') parser.add_argument('-o', '--output', dest='output_filename', help="output filename", default='track.kml') parser.add_argument('--topic', dest='topic_name', help="topic name with position data (default=vehicle_gps_position)", default='vehicle_gps_position') parser.add_argument('--camera-trigger', dest='camera_trigger', help="Camera trigger topic name (e.g. camera_capture)", default=None) args = parser.parse_args() convert_ulog2kml(args.filename, args.output_filename, position_topic_name=args.topic_name, camera_trigger_topic_name=args.camera_trigger) # alternative example call: # convert_ulog2kml(args.filename, 'test.kml', ['vehicle_global_position', # 'vehicle_gps_position'], [_kml_default_colors, lambda x: simplekml.Color.green]) def convert_ulog2kml(ulog_file_name, output_file_name, position_topic_name= 'vehicle_gps_position', colors=_kml_default_colors, altitude_offset=0, minimum_interval_s=0.1, style=None, camera_trigger_topic_name=None): """ Coverts and ULog file to a CSV file. :param ulog_file_name: The ULog filename to open and read :param output_file_name: KML Output file name :param position_topic_name: either name of a topic (must have 'lon', 'lat' & 'alt' fields), or a list of topic names :param colors: lambda function with flight mode (int) (or -1) as input and returns a color (eg 'fffff8f0') (or list of lambda functions if multiple position_topic_name's) :param altitude_offset: add this offset to the altitude [m] :param minimum_interval_s: minimum time difference between two datapoints (drop if more points) :param style: dictionary with rendering options: 'extrude': Bool 'line_width': int :param camera_trigger_topic_name: name of the camera trigger topic (must have 'lon', 'lat' & 'seq') :return: None """ default_style = { 'extrude': False, 'line_width': 3 } used_style = default_style if style is not None: for key in style: used_style[key] = style[key] if not isinstance(position_topic_name, list): position_topic_name = [position_topic_name] colors = [colors] kml = simplekml.Kml() load_topic_names = position_topic_name + ['vehicle_status'] if camera_trigger_topic_name is not None: load_topic_names.append(camera_trigger_topic_name) ulog = ULog(ulog_file_name, load_topic_names) # get flight modes try: cur_dataset = ulog.get_dataset('vehicle_status') flight_mode_changes = cur_dataset.list_value_changes('nav_state') flight_mode_changes.append((ulog.last_timestamp, -1)) except (KeyError, IndexError) as error: flight_mode_changes = [] # add the graphs for topic, cur_colors in zip(position_topic_name, colors): _kml_add_position_data(kml, ulog, topic, cur_colors, used_style, altitude_offset, minimum_interval_s, flight_mode_changes) # camera triggers _kml_add_camera_triggers(kml, ulog, camera_trigger_topic_name, altitude_offset) kml.save(output_file_name) def _kml_add_camera_triggers(kml, ulog, camera_trigger_topic_name, altitude_offset): """ Add camera trigger points to the map """ data = ulog.data_list topic_instance = 0 cur_dataset = [elem for elem in data if elem.name == camera_trigger_topic_name and elem.multi_id == topic_instance] if len(cur_dataset) > 0: cur_dataset = cur_dataset[0] pos_lon = cur_dataset.data['lon'] pos_lat = cur_dataset.data['lat'] pos_alt = cur_dataset.data['alt'] sequence = cur_dataset.data['seq'] for i in range(len(pos_lon)): pnt = kml.newpoint(name='Camera Trigger '+str(sequence[i])) pnt.coords = [(pos_lon[i], pos_lat[i], pos_alt[i] + altitude_offset)] # Balloons instead of text does not work #pnt.style.balloonstyle.text = 'Camera Trigger '+str(sequence[i]) def _kml_add_position_data(kml, ulog, position_topic_name, colors, style, altitude_offset=0, minimum_interval_s=0.1, flight_mode_changes=None): data = ulog.data_list topic_instance = 0 if flight_mode_changes is None: flight_mode_changes = [] cur_dataset = [elem for elem in data if elem.name == position_topic_name and elem.multi_id == topic_instance] if len(cur_dataset) == 0: raise Exception(position_topic_name+' not found in data') cur_dataset = cur_dataset[0] pos_lon = cur_dataset.data['lon'] pos_lat = cur_dataset.data['lat'] pos_alt = cur_dataset.data['alt'] pos_t = cur_dataset.data['timestamp'] if 'fix_type' in cur_dataset.data: indices = cur_dataset.data['fix_type'] > 2 # use only data with a fix pos_lon = pos_lon[indices] pos_lat = pos_lat[indices] pos_alt = pos_alt[indices] pos_t = pos_t[indices] # scale if it's an integer type lon_type = [f.type_str for f in cur_dataset.field_data if f.field_name == 'lon'] if len(lon_type) > 0 and lon_type[0] == 'int32_t': pos_lon = pos_lon / 1e7 # to degrees pos_lat = pos_lat / 1e7 pos_alt = pos_alt / 1e3 # to meters current_flight_mode = 0 current_flight_mode_idx = 0 if len(flight_mode_changes) > 0: current_flight_mode = flight_mode_changes[0][1] def create_linestring(): """ create a new kml linestring and set rendering options """ name = position_topic_name + ":" + str(current_flight_mode) new_linestring = kml.newlinestring(name=name, altitudemode='absolute') # set rendering options if style['extrude']: new_linestring.extrude = 1 new_linestring.style.linestyle.color = colors(current_flight_mode) new_linestring.style.linestyle.width = style['line_width'] return new_linestring current_kml_linestring = create_linestring() last_t = 0 for i in range(len(pos_lon)): cur_t = pos_t[i] if (cur_t - last_t)/1e6 > minimum_interval_s: # assume timestamp is in [us] pos_data = [pos_lon[i], pos_lat[i], pos_alt[i] + altitude_offset] current_kml_linestring.coords.addcoordinates([pos_data]) last_t = cur_t # flight mode change? while current_flight_mode_idx < len(flight_mode_changes)-1 and \ flight_mode_changes[current_flight_mode_idx+1][0] <= cur_t: current_flight_mode_idx += 1 current_flight_mode = flight_mode_changes[current_flight_mode_idx][1] current_kml_linestring = create_linestring() current_kml_linestring.coords.addcoordinates([pos_data])
PX4/pyulog
pyulog/ulog2kml.py
convert_ulog2kml
python
def convert_ulog2kml(ulog_file_name, output_file_name, position_topic_name= 'vehicle_gps_position', colors=_kml_default_colors, altitude_offset=0, minimum_interval_s=0.1, style=None, camera_trigger_topic_name=None): default_style = { 'extrude': False, 'line_width': 3 } used_style = default_style if style is not None: for key in style: used_style[key] = style[key] if not isinstance(position_topic_name, list): position_topic_name = [position_topic_name] colors = [colors] kml = simplekml.Kml() load_topic_names = position_topic_name + ['vehicle_status'] if camera_trigger_topic_name is not None: load_topic_names.append(camera_trigger_topic_name) ulog = ULog(ulog_file_name, load_topic_names) # get flight modes try: cur_dataset = ulog.get_dataset('vehicle_status') flight_mode_changes = cur_dataset.list_value_changes('nav_state') flight_mode_changes.append((ulog.last_timestamp, -1)) except (KeyError, IndexError) as error: flight_mode_changes = [] # add the graphs for topic, cur_colors in zip(position_topic_name, colors): _kml_add_position_data(kml, ulog, topic, cur_colors, used_style, altitude_offset, minimum_interval_s, flight_mode_changes) # camera triggers _kml_add_camera_triggers(kml, ulog, camera_trigger_topic_name, altitude_offset) kml.save(output_file_name)
Coverts and ULog file to a CSV file. :param ulog_file_name: The ULog filename to open and read :param output_file_name: KML Output file name :param position_topic_name: either name of a topic (must have 'lon', 'lat' & 'alt' fields), or a list of topic names :param colors: lambda function with flight mode (int) (or -1) as input and returns a color (eg 'fffff8f0') (or list of lambda functions if multiple position_topic_name's) :param altitude_offset: add this offset to the altitude [m] :param minimum_interval_s: minimum time difference between two datapoints (drop if more points) :param style: dictionary with rendering options: 'extrude': Bool 'line_width': int :param camera_trigger_topic_name: name of the camera trigger topic (must have 'lon', 'lat' & 'seq') :return: None
train
https://github.com/PX4/pyulog/blob/3bc4f9338d30e2e0a0dfbed58f54d200967e5056/pyulog/ulog2kml.py#L55-L117
[ "def _kml_add_position_data(kml, ulog, position_topic_name, colors, style,\n altitude_offset=0, minimum_interval_s=0.1,\n flight_mode_changes=None):\n\n data = ulog.data_list\n topic_instance = 0\n if flight_mode_changes is None:\n flight_mode_changes = []\n\n cur_dataset = [elem for elem in data\n if elem.name == position_topic_name and elem.multi_id == topic_instance]\n if len(cur_dataset) == 0:\n raise Exception(position_topic_name+' not found in data')\n\n cur_dataset = cur_dataset[0]\n\n\n pos_lon = cur_dataset.data['lon']\n pos_lat = cur_dataset.data['lat']\n pos_alt = cur_dataset.data['alt']\n pos_t = cur_dataset.data['timestamp']\n\n if 'fix_type' in cur_dataset.data:\n indices = cur_dataset.data['fix_type'] > 2 # use only data with a fix\n pos_lon = pos_lon[indices]\n pos_lat = pos_lat[indices]\n pos_alt = pos_alt[indices]\n pos_t = pos_t[indices]\n\n # scale if it's an integer type\n lon_type = [f.type_str for f in cur_dataset.field_data if f.field_name == 'lon']\n if len(lon_type) > 0 and lon_type[0] == 'int32_t':\n pos_lon = pos_lon / 1e7 # to degrees\n pos_lat = pos_lat / 1e7\n pos_alt = pos_alt / 1e3 # to meters\n\n\n current_flight_mode = 0\n current_flight_mode_idx = 0\n if len(flight_mode_changes) > 0:\n current_flight_mode = flight_mode_changes[0][1]\n\n\n def create_linestring():\n \"\"\" create a new kml linestring and set rendering options \"\"\"\n name = position_topic_name + \":\" + str(current_flight_mode)\n new_linestring = kml.newlinestring(name=name, altitudemode='absolute')\n\n # set rendering options\n if style['extrude']:\n new_linestring.extrude = 1\n new_linestring.style.linestyle.color = colors(current_flight_mode)\n\n new_linestring.style.linestyle.width = style['line_width']\n return new_linestring\n\n current_kml_linestring = create_linestring()\n\n last_t = 0\n for i in range(len(pos_lon)):\n cur_t = pos_t[i]\n\n if (cur_t - last_t)/1e6 > minimum_interval_s: # assume timestamp is in [us]\n pos_data = [pos_lon[i], pos_lat[i], pos_alt[i] + altitude_offset]\n current_kml_linestring.coords.addcoordinates([pos_data])\n last_t = cur_t\n\n # flight mode change?\n while current_flight_mode_idx < len(flight_mode_changes)-1 and \\\n flight_mode_changes[current_flight_mode_idx+1][0] <= cur_t:\n current_flight_mode_idx += 1\n current_flight_mode = flight_mode_changes[current_flight_mode_idx][1]\n current_kml_linestring = create_linestring()\n\n current_kml_linestring.coords.addcoordinates([pos_data])\n", "def _kml_add_camera_triggers(kml, ulog, camera_trigger_topic_name, altitude_offset):\n \"\"\"\n Add camera trigger points to the map\n \"\"\"\n\n data = ulog.data_list\n topic_instance = 0\n\n cur_dataset = [elem for elem in data\n if elem.name == camera_trigger_topic_name and elem.multi_id == topic_instance]\n if len(cur_dataset) > 0:\n cur_dataset = cur_dataset[0]\n\n pos_lon = cur_dataset.data['lon']\n pos_lat = cur_dataset.data['lat']\n pos_alt = cur_dataset.data['alt']\n sequence = cur_dataset.data['seq']\n\n for i in range(len(pos_lon)):\n pnt = kml.newpoint(name='Camera Trigger '+str(sequence[i]))\n pnt.coords = [(pos_lon[i], pos_lat[i], pos_alt[i] + altitude_offset)]\n", "def get_dataset(self, name, multi_instance=0):\n \"\"\" get a specific dataset.\n\n example:\n try:\n gyro_data = ulog.get_dataset('sensor_gyro')\n except (KeyError, IndexError, ValueError) as error:\n print(type(error), \"(sensor_gyro):\", error)\n\n :param name: name of the dataset\n :param multi_instance: the multi_id, defaults to the first\n :raises KeyError, IndexError, ValueError: if name or instance not found\n \"\"\"\n return [elem for elem in self._data_list\n if elem.name == name and elem.multi_id == multi_instance][0]\n" ]
#! /usr/bin/env python """ Convert a ULog file into a KML file (positioning information) """ from __future__ import print_function import argparse import simplekml # pylint: disable=import-error from .core import ULog #pylint: disable=too-many-locals, invalid-name, consider-using-enumerate, too-many-arguments #pylint: disable=unused-variable def main(): """Command line interface""" parser = argparse.ArgumentParser(description='Convert ULog to KML') parser.add_argument('filename', metavar='file.ulg', help='ULog input file') parser.add_argument('-o', '--output', dest='output_filename', help="output filename", default='track.kml') parser.add_argument('--topic', dest='topic_name', help="topic name with position data (default=vehicle_gps_position)", default='vehicle_gps_position') parser.add_argument('--camera-trigger', dest='camera_trigger', help="Camera trigger topic name (e.g. camera_capture)", default=None) args = parser.parse_args() convert_ulog2kml(args.filename, args.output_filename, position_topic_name=args.topic_name, camera_trigger_topic_name=args.camera_trigger) # alternative example call: # convert_ulog2kml(args.filename, 'test.kml', ['vehicle_global_position', # 'vehicle_gps_position'], [_kml_default_colors, lambda x: simplekml.Color.green]) def _kml_default_colors(x): """ flight mode to color conversion """ x = max([x, 0]) colors_arr = [simplekml.Color.red, simplekml.Color.green, simplekml.Color.blue, simplekml.Color.violet, simplekml.Color.yellow, simplekml.Color.orange, simplekml.Color.burlywood, simplekml.Color.azure, simplekml.Color.lightblue, simplekml.Color.lawngreen, simplekml.Color.indianred, simplekml.Color.hotpink] return colors_arr[x] def _kml_add_camera_triggers(kml, ulog, camera_trigger_topic_name, altitude_offset): """ Add camera trigger points to the map """ data = ulog.data_list topic_instance = 0 cur_dataset = [elem for elem in data if elem.name == camera_trigger_topic_name and elem.multi_id == topic_instance] if len(cur_dataset) > 0: cur_dataset = cur_dataset[0] pos_lon = cur_dataset.data['lon'] pos_lat = cur_dataset.data['lat'] pos_alt = cur_dataset.data['alt'] sequence = cur_dataset.data['seq'] for i in range(len(pos_lon)): pnt = kml.newpoint(name='Camera Trigger '+str(sequence[i])) pnt.coords = [(pos_lon[i], pos_lat[i], pos_alt[i] + altitude_offset)] # Balloons instead of text does not work #pnt.style.balloonstyle.text = 'Camera Trigger '+str(sequence[i]) def _kml_add_position_data(kml, ulog, position_topic_name, colors, style, altitude_offset=0, minimum_interval_s=0.1, flight_mode_changes=None): data = ulog.data_list topic_instance = 0 if flight_mode_changes is None: flight_mode_changes = [] cur_dataset = [elem for elem in data if elem.name == position_topic_name and elem.multi_id == topic_instance] if len(cur_dataset) == 0: raise Exception(position_topic_name+' not found in data') cur_dataset = cur_dataset[0] pos_lon = cur_dataset.data['lon'] pos_lat = cur_dataset.data['lat'] pos_alt = cur_dataset.data['alt'] pos_t = cur_dataset.data['timestamp'] if 'fix_type' in cur_dataset.data: indices = cur_dataset.data['fix_type'] > 2 # use only data with a fix pos_lon = pos_lon[indices] pos_lat = pos_lat[indices] pos_alt = pos_alt[indices] pos_t = pos_t[indices] # scale if it's an integer type lon_type = [f.type_str for f in cur_dataset.field_data if f.field_name == 'lon'] if len(lon_type) > 0 and lon_type[0] == 'int32_t': pos_lon = pos_lon / 1e7 # to degrees pos_lat = pos_lat / 1e7 pos_alt = pos_alt / 1e3 # to meters current_flight_mode = 0 current_flight_mode_idx = 0 if len(flight_mode_changes) > 0: current_flight_mode = flight_mode_changes[0][1] def create_linestring(): """ create a new kml linestring and set rendering options """ name = position_topic_name + ":" + str(current_flight_mode) new_linestring = kml.newlinestring(name=name, altitudemode='absolute') # set rendering options if style['extrude']: new_linestring.extrude = 1 new_linestring.style.linestyle.color = colors(current_flight_mode) new_linestring.style.linestyle.width = style['line_width'] return new_linestring current_kml_linestring = create_linestring() last_t = 0 for i in range(len(pos_lon)): cur_t = pos_t[i] if (cur_t - last_t)/1e6 > minimum_interval_s: # assume timestamp is in [us] pos_data = [pos_lon[i], pos_lat[i], pos_alt[i] + altitude_offset] current_kml_linestring.coords.addcoordinates([pos_data]) last_t = cur_t # flight mode change? while current_flight_mode_idx < len(flight_mode_changes)-1 and \ flight_mode_changes[current_flight_mode_idx+1][0] <= cur_t: current_flight_mode_idx += 1 current_flight_mode = flight_mode_changes[current_flight_mode_idx][1] current_kml_linestring = create_linestring() current_kml_linestring.coords.addcoordinates([pos_data])
PX4/pyulog
pyulog/ulog2kml.py
_kml_add_camera_triggers
python
def _kml_add_camera_triggers(kml, ulog, camera_trigger_topic_name, altitude_offset): data = ulog.data_list topic_instance = 0 cur_dataset = [elem for elem in data if elem.name == camera_trigger_topic_name and elem.multi_id == topic_instance] if len(cur_dataset) > 0: cur_dataset = cur_dataset[0] pos_lon = cur_dataset.data['lon'] pos_lat = cur_dataset.data['lat'] pos_alt = cur_dataset.data['alt'] sequence = cur_dataset.data['seq'] for i in range(len(pos_lon)): pnt = kml.newpoint(name='Camera Trigger '+str(sequence[i])) pnt.coords = [(pos_lon[i], pos_lat[i], pos_alt[i] + altitude_offset)]
Add camera trigger points to the map
train
https://github.com/PX4/pyulog/blob/3bc4f9338d30e2e0a0dfbed58f54d200967e5056/pyulog/ulog2kml.py#L120-L140
null
#! /usr/bin/env python """ Convert a ULog file into a KML file (positioning information) """ from __future__ import print_function import argparse import simplekml # pylint: disable=import-error from .core import ULog #pylint: disable=too-many-locals, invalid-name, consider-using-enumerate, too-many-arguments #pylint: disable=unused-variable def main(): """Command line interface""" parser = argparse.ArgumentParser(description='Convert ULog to KML') parser.add_argument('filename', metavar='file.ulg', help='ULog input file') parser.add_argument('-o', '--output', dest='output_filename', help="output filename", default='track.kml') parser.add_argument('--topic', dest='topic_name', help="topic name with position data (default=vehicle_gps_position)", default='vehicle_gps_position') parser.add_argument('--camera-trigger', dest='camera_trigger', help="Camera trigger topic name (e.g. camera_capture)", default=None) args = parser.parse_args() convert_ulog2kml(args.filename, args.output_filename, position_topic_name=args.topic_name, camera_trigger_topic_name=args.camera_trigger) # alternative example call: # convert_ulog2kml(args.filename, 'test.kml', ['vehicle_global_position', # 'vehicle_gps_position'], [_kml_default_colors, lambda x: simplekml.Color.green]) def _kml_default_colors(x): """ flight mode to color conversion """ x = max([x, 0]) colors_arr = [simplekml.Color.red, simplekml.Color.green, simplekml.Color.blue, simplekml.Color.violet, simplekml.Color.yellow, simplekml.Color.orange, simplekml.Color.burlywood, simplekml.Color.azure, simplekml.Color.lightblue, simplekml.Color.lawngreen, simplekml.Color.indianred, simplekml.Color.hotpink] return colors_arr[x] def convert_ulog2kml(ulog_file_name, output_file_name, position_topic_name= 'vehicle_gps_position', colors=_kml_default_colors, altitude_offset=0, minimum_interval_s=0.1, style=None, camera_trigger_topic_name=None): """ Coverts and ULog file to a CSV file. :param ulog_file_name: The ULog filename to open and read :param output_file_name: KML Output file name :param position_topic_name: either name of a topic (must have 'lon', 'lat' & 'alt' fields), or a list of topic names :param colors: lambda function with flight mode (int) (or -1) as input and returns a color (eg 'fffff8f0') (or list of lambda functions if multiple position_topic_name's) :param altitude_offset: add this offset to the altitude [m] :param minimum_interval_s: minimum time difference between two datapoints (drop if more points) :param style: dictionary with rendering options: 'extrude': Bool 'line_width': int :param camera_trigger_topic_name: name of the camera trigger topic (must have 'lon', 'lat' & 'seq') :return: None """ default_style = { 'extrude': False, 'line_width': 3 } used_style = default_style if style is not None: for key in style: used_style[key] = style[key] if not isinstance(position_topic_name, list): position_topic_name = [position_topic_name] colors = [colors] kml = simplekml.Kml() load_topic_names = position_topic_name + ['vehicle_status'] if camera_trigger_topic_name is not None: load_topic_names.append(camera_trigger_topic_name) ulog = ULog(ulog_file_name, load_topic_names) # get flight modes try: cur_dataset = ulog.get_dataset('vehicle_status') flight_mode_changes = cur_dataset.list_value_changes('nav_state') flight_mode_changes.append((ulog.last_timestamp, -1)) except (KeyError, IndexError) as error: flight_mode_changes = [] # add the graphs for topic, cur_colors in zip(position_topic_name, colors): _kml_add_position_data(kml, ulog, topic, cur_colors, used_style, altitude_offset, minimum_interval_s, flight_mode_changes) # camera triggers _kml_add_camera_triggers(kml, ulog, camera_trigger_topic_name, altitude_offset) kml.save(output_file_name) # Balloons instead of text does not work #pnt.style.balloonstyle.text = 'Camera Trigger '+str(sequence[i]) def _kml_add_position_data(kml, ulog, position_topic_name, colors, style, altitude_offset=0, minimum_interval_s=0.1, flight_mode_changes=None): data = ulog.data_list topic_instance = 0 if flight_mode_changes is None: flight_mode_changes = [] cur_dataset = [elem for elem in data if elem.name == position_topic_name and elem.multi_id == topic_instance] if len(cur_dataset) == 0: raise Exception(position_topic_name+' not found in data') cur_dataset = cur_dataset[0] pos_lon = cur_dataset.data['lon'] pos_lat = cur_dataset.data['lat'] pos_alt = cur_dataset.data['alt'] pos_t = cur_dataset.data['timestamp'] if 'fix_type' in cur_dataset.data: indices = cur_dataset.data['fix_type'] > 2 # use only data with a fix pos_lon = pos_lon[indices] pos_lat = pos_lat[indices] pos_alt = pos_alt[indices] pos_t = pos_t[indices] # scale if it's an integer type lon_type = [f.type_str for f in cur_dataset.field_data if f.field_name == 'lon'] if len(lon_type) > 0 and lon_type[0] == 'int32_t': pos_lon = pos_lon / 1e7 # to degrees pos_lat = pos_lat / 1e7 pos_alt = pos_alt / 1e3 # to meters current_flight_mode = 0 current_flight_mode_idx = 0 if len(flight_mode_changes) > 0: current_flight_mode = flight_mode_changes[0][1] def create_linestring(): """ create a new kml linestring and set rendering options """ name = position_topic_name + ":" + str(current_flight_mode) new_linestring = kml.newlinestring(name=name, altitudemode='absolute') # set rendering options if style['extrude']: new_linestring.extrude = 1 new_linestring.style.linestyle.color = colors(current_flight_mode) new_linestring.style.linestyle.width = style['line_width'] return new_linestring current_kml_linestring = create_linestring() last_t = 0 for i in range(len(pos_lon)): cur_t = pos_t[i] if (cur_t - last_t)/1e6 > minimum_interval_s: # assume timestamp is in [us] pos_data = [pos_lon[i], pos_lat[i], pos_alt[i] + altitude_offset] current_kml_linestring.coords.addcoordinates([pos_data]) last_t = cur_t # flight mode change? while current_flight_mode_idx < len(flight_mode_changes)-1 and \ flight_mode_changes[current_flight_mode_idx+1][0] <= cur_t: current_flight_mode_idx += 1 current_flight_mode = flight_mode_changes[current_flight_mode_idx][1] current_kml_linestring = create_linestring() current_kml_linestring.coords.addcoordinates([pos_data])
PX4/pyulog
pyulog/extract_gps_dump.py
main
python
def main(): parser = argparse.ArgumentParser( description='Extract the raw gps communication from an ULog file') parser.add_argument('filename', metavar='file.ulg', help='ULog input file') def is_valid_directory(parser, arg): """Check if valid directory""" if not os.path.isdir(arg): parser.error('The directory {} does not exist'.format(arg)) # File exists so return the directory return arg parser.add_argument('-o', '--output', dest='output', action='store', help='Output directory (default is CWD)', metavar='DIR', type=lambda x: is_valid_directory(parser, x)) args = parser.parse_args() ulog_file_name = args.filename msg_filter = ['gps_dump'] ulog = ULog(ulog_file_name, msg_filter) data = ulog.data_list output_file_prefix = os.path.basename(ulog_file_name) # strip '.ulg' if output_file_prefix.lower().endswith('.ulg'): output_file_prefix = output_file_prefix[:-4] # write to different output path? if args.output is not None: output_file_prefix = os.path.join(args.output, output_file_prefix) to_dev_filename = output_file_prefix+'_to_device.dat' from_dev_filename = output_file_prefix+'_from_device.dat' if len(data) == 0: print("File {0} does not contain gps_dump messages!".format(ulog_file_name)) exit(0) gps_dump_data = data[0] # message format check field_names = [f.field_name for f in gps_dump_data.field_data] if not 'len' in field_names or not 'data[0]' in field_names: print('Error: gps_dump message has wrong format') exit(-1) if len(ulog.dropouts) > 0: print("Warning: file contains {0} dropouts".format(len(ulog.dropouts))) print("Creating files {0} and {1}".format(to_dev_filename, from_dev_filename)) with open(to_dev_filename, 'wb') as to_dev_file: with open(from_dev_filename, 'wb') as from_dev_file: msg_lens = gps_dump_data.data['len'] for i in range(len(gps_dump_data.data['timestamp'])): msg_len = msg_lens[i] if msg_len & (1<<7): msg_len = msg_len & ~(1<<7) file_handle = to_dev_file else: file_handle = from_dev_file for k in range(msg_len): file_handle.write(gps_dump_data.data['data['+str(k)+']'][i])
Command line interface
train
https://github.com/PX4/pyulog/blob/3bc4f9338d30e2e0a0dfbed58f54d200967e5056/pyulog/extract_gps_dump.py#L15-L81
null
#! /usr/bin/env python """ Extract the raw gps communication from an ULog file. """ from __future__ import print_function import argparse import os from .core import ULog #pylint: disable=too-many-locals, unused-wildcard-import, wildcard-import
PX4/pyulog
pyulog/core.py
ULog.get_dataset
python
def get_dataset(self, name, multi_instance=0): return [elem for elem in self._data_list if elem.name == name and elem.multi_id == multi_instance][0]
get a specific dataset. example: try: gyro_data = ulog.get_dataset('sensor_gyro') except (KeyError, IndexError, ValueError) as error: print(type(error), "(sensor_gyro):", error) :param name: name of the dataset :param multi_instance: the multi_id, defaults to the first :raises KeyError, IndexError, ValueError: if name or instance not found
train
https://github.com/PX4/pyulog/blob/3bc4f9338d30e2e0a0dfbed58f54d200967e5056/pyulog/core.py#L178-L192
null
class ULog(object): """ This class parses an ulog file """ ## constants ## HEADER_BYTES = b'\x55\x4c\x6f\x67\x01\x12\x35' # message types MSG_TYPE_FORMAT = ord('F') MSG_TYPE_DATA = ord('D') MSG_TYPE_INFO = ord('I') MSG_TYPE_INFO_MULTIPLE = ord('M') MSG_TYPE_PARAMETER = ord('P') MSG_TYPE_ADD_LOGGED_MSG = ord('A') MSG_TYPE_REMOVE_LOGGED_MSG = ord('R') MSG_TYPE_SYNC = ord('S') MSG_TYPE_DROPOUT = ord('O') MSG_TYPE_LOGGING = ord('L') MSG_TYPE_FLAG_BITS = ord('B') _UNPACK_TYPES = { 'int8_t': ['b', 1, np.int8], 'uint8_t': ['B', 1, np.uint8], 'int16_t': ['h', 2, np.int16], 'uint16_t': ['H', 2, np.uint16], 'int32_t': ['i', 4, np.int32], 'uint32_t': ['I', 4, np.uint32], 'int64_t': ['q', 8, np.int64], 'uint64_t': ['Q', 8, np.uint64], 'float': ['f', 4, np.float32], 'double': ['d', 8, np.float64], 'bool': ['?', 1, np.int8], 'char': ['c', 1, np.int8] } @staticmethod def get_field_size(type_str): """ get the field size in bytes. :param type_str: type string, eg. 'int8_t' """ return ULog._UNPACK_TYPES[type_str][1] # pre-init unpack structs for quicker use _unpack_ushort_byte = struct.Struct('<HB').unpack _unpack_ushort = struct.Struct('<H').unpack _unpack_uint64 = struct.Struct('<Q').unpack def __init__(self, log_file, message_name_filter_list=None): """ Initialize the object & load the file. :param log_file: a file name (str) or a readable file object :param message_name_filter_list: list of strings, to only load messages with the given names. If None, load everything. """ self._debug = False self._file_corrupt = False self._start_timestamp = 0 self._last_timestamp = 0 self._msg_info_dict = {} self._msg_info_multiple_dict = {} self._initial_parameters = {} self._changed_parameters = [] self._message_formats = {} self._logged_messages = [] self._dropouts = [] self._data_list = [] self._subscriptions = {} # dict of key=msg_id, value=_MessageAddLogged self._filtered_message_ids = set() # _MessageAddLogged id's that are filtered self._missing_message_ids = set() # _MessageAddLogged id's that could not be found self._file_version = 0 self._compat_flags = [0] * 8 self._incompat_flags = [0] * 8 self._appended_offsets = [] # file offsets for appended data self._load_file(log_file, message_name_filter_list) ## parsed data @property def start_timestamp(self): """ timestamp of file start """ return self._start_timestamp @property def last_timestamp(self): """ timestamp of last message """ return self._last_timestamp @property def msg_info_dict(self): """ dictionary of all information messages (key is a string, value depends on the type, usually string or int) """ return self._msg_info_dict @property def msg_info_multiple_dict(self): """ dictionary of all information multiple messages (key is a string, value is a list of lists that contains the messages) """ return self._msg_info_multiple_dict @property def initial_parameters(self): """ dictionary of all initially set parameters (key=param name) """ return self._initial_parameters @property def changed_parameters(self): """ list of all changed parameters (tuple of (timestamp, name, value))""" return self._changed_parameters @property def message_formats(self): """ dictionary with key = format name (MessageFormat.name), value = MessageFormat object """ return self._message_formats @property def logged_messages(self): """ list of MessageLogging objects """ return self._logged_messages @property def dropouts(self): """ list of MessageDropout objects """ return self._dropouts @property def data_list(self): """ extracted data: list of Data objects """ return self._data_list @property def has_data_appended(self): """ returns True if the log has data appended, False otherwise """ return self._incompat_flags[0] & 0x1 @property def file_corruption(self): """ True if a file corruption got detected """ return self._file_corrupt class Data(object): """ contains the final topic data for a single topic and instance """ def __init__(self, message_add_logged_obj): self.multi_id = message_add_logged_obj.multi_id self.name = message_add_logged_obj.message_name self.field_data = message_add_logged_obj.field_data self.timestamp_idx = message_add_logged_obj.timestamp_idx # get data as numpy.ndarray np_array = np.frombuffer(message_add_logged_obj.buffer, dtype=message_add_logged_obj.dtype) # convert into dict of np.array (which is easier to handle) self.data = {} for name in np_array.dtype.names: self.data[name] = np_array[name] def list_value_changes(self, field_name): """ get a list of (timestamp, value) tuples, whenever the value changes. The first data point with non-zero timestamp is always included, messages with timestamp = 0 are ignored """ t = self.data['timestamp'] x = self.data[field_name] indices = t != 0 # filter out 0 values t = t[indices] x = x[indices] if len(t) == 0: return [] ret = [(t[0], x[0])] indices = np.where(x[:-1] != x[1:])[0] + 1 ret.extend(zip(t[indices], x[indices])) return ret ## Representations of the messages from the log file ## class _MessageHeader(object): """ 3 bytes ULog message header """ def __init__(self): self.msg_size = 0 self.msg_type = 0 def initialize(self, data): self.msg_size, self.msg_type = ULog._unpack_ushort_byte(data) class _MessageInfo(object): """ ULog info message representation """ def __init__(self, data, header, is_info_multiple=False): if is_info_multiple: # INFO_MULTIPLE message self.is_continued, = struct.unpack('<B', data[0:1]) data = data[1:] key_len, = struct.unpack('<B', data[0:1]) type_key = _parse_string(data[1:1+key_len]) type_key_split = type_key.split(' ') self.type = type_key_split[0] self.key = type_key_split[1] if self.type.startswith('char['): # it's a string self.value = _parse_string(data[1+key_len:]) elif self.type in ULog._UNPACK_TYPES: unpack_type = ULog._UNPACK_TYPES[self.type] self.value, = struct.unpack('<'+unpack_type[0], data[1+key_len:]) else: # probably an array (or non-basic type) self.value = data[1+key_len:] class _MessageFlagBits(object): """ ULog message flag bits """ def __init__(self, data, header): if header.msg_size > 8 + 8 + 3*8: # we can still parse it but might miss some information print('Warning: Flags Bit message is longer than expected') self.compat_flags = list(struct.unpack('<'+'B'*8, data[0:8])) self.incompat_flags = list(struct.unpack('<'+'B'*8, data[8:16])) self.appended_offsets = list(struct.unpack('<'+'Q'*3, data[16:16+3*8])) # remove the 0's at the end while len(self.appended_offsets) > 0 and self.appended_offsets[-1] == 0: self.appended_offsets.pop() class MessageFormat(object): """ ULog message format representation """ def __init__(self, data, header): format_arr = _parse_string(data).split(':') self.name = format_arr[0] types_str = format_arr[1].split(';') self.fields = [] # list of tuples (type, array_size, name) for t in types_str: if len(t) > 0: self.fields.append(self._extract_type(t)) @staticmethod def _extract_type(field_str): field_str_split = field_str.split(' ') type_str = field_str_split[0] name_str = field_str_split[1] a_pos = type_str.find('[') if a_pos == -1: array_size = 1 type_name = type_str else: b_pos = type_str.find(']') array_size = int(type_str[a_pos+1:b_pos]) type_name = type_str[:a_pos] return type_name, array_size, name_str class MessageLogging(object): """ ULog logged string message representation """ def __init__(self, data, header): self.log_level, = struct.unpack('<B', data[0:1]) self.timestamp, = struct.unpack('<Q', data[1:9]) self.message = _parse_string(data[9:]) def log_level_str(self): return {ord('0'): 'EMERGENCY', ord('1'): 'ALERT', ord('2'): 'CRITICAL', ord('3'): 'ERROR', ord('4'): 'WARNING', ord('5'): 'NOTICE', ord('6'): 'INFO', ord('7'): 'DEBUG'}.get(self.log_level, 'UNKNOWN') class MessageDropout(object): """ ULog dropout message representation """ def __init__(self, data, header, timestamp): self.duration, = struct.unpack('<H', data) self.timestamp = timestamp class _FieldData(object): """ Type and name of a single ULog data field """ def __init__(self, field_name, type_str): self.field_name = field_name self.type_str = type_str class _MessageAddLogged(object): """ ULog add logging data message representation """ def __init__(self, data, header, message_formats): self.multi_id, = struct.unpack('<B', data[0:1]) self.msg_id, = struct.unpack('<H', data[1:3]) self.message_name = _parse_string(data[3:]) self.field_data = [] # list of _FieldData self.timestamp_idx = -1 self._parse_format(message_formats) self.timestamp_offset = 0 for field in self.field_data: if field.field_name == 'timestamp': break self.timestamp_offset += ULog._UNPACK_TYPES[field.type_str][1] self.buffer = bytearray() # accumulate all message data here # construct types for numpy dtype_list = [] for field in self.field_data: numpy_type = ULog._UNPACK_TYPES[field.type_str][2] dtype_list.append((field.field_name, numpy_type)) self.dtype = np.dtype(dtype_list).newbyteorder('<') def _parse_format(self, message_formats): self._parse_nested_type('', self.message_name, message_formats) # remove padding fields at the end while (len(self.field_data) > 0 and self.field_data[-1].field_name.startswith('_padding')): self.field_data.pop() def _parse_nested_type(self, prefix_str, type_name, message_formats): # we flatten nested types message_format = message_formats[type_name] for (type_name_fmt, array_size, field_name) in message_format.fields: if type_name_fmt in ULog._UNPACK_TYPES: if array_size > 1: for i in range(array_size): self.field_data.append(ULog._FieldData( prefix_str+field_name+'['+str(i)+']', type_name_fmt)) else: self.field_data.append(ULog._FieldData( prefix_str+field_name, type_name_fmt)) if prefix_str+field_name == 'timestamp': self.timestamp_idx = len(self.field_data) - 1 else: # nested type if array_size > 1: for i in range(array_size): self._parse_nested_type(prefix_str+field_name+'['+str(i)+'].', type_name_fmt, message_formats) else: self._parse_nested_type(prefix_str+field_name+'.', type_name_fmt, message_formats) class _MessageData(object): def __init__(self): self.timestamp = 0 def initialize(self, data, header, subscriptions, ulog_object): msg_id, = ULog._unpack_ushort(data[:2]) if msg_id in subscriptions: subscription = subscriptions[msg_id] # accumulate data to a buffer, will be parsed later subscription.buffer += data[2:] t_off = subscription.timestamp_offset # TODO: the timestamp can have another size than uint64 self.timestamp, = ULog._unpack_uint64(data[t_off+2:t_off+10]) else: if not msg_id in ulog_object._filtered_message_ids: # this is an error, but make it non-fatal if not msg_id in ulog_object._missing_message_ids: ulog_object._missing_message_ids.add(msg_id) if ulog_object._debug: print(ulog_object._file_handle.tell()) print('Warning: no subscription found for message id {:}. Continuing,' ' but file is most likely corrupt'.format(msg_id)) self.timestamp = 0 def _add_message_info_multiple(self, msg_info): """ add a message info multiple to self._msg_info_multiple_dict """ if msg_info.key in self._msg_info_multiple_dict: if msg_info.is_continued: self._msg_info_multiple_dict[msg_info.key][-1].append(msg_info.value) else: self._msg_info_multiple_dict[msg_info.key].append([msg_info.value]) else: self._msg_info_multiple_dict[msg_info.key] = [[msg_info.value]] def _load_file(self, log_file, message_name_filter_list): """ load and parse an ULog file into memory """ if isinstance(log_file, str): self._file_handle = open(log_file, "rb") else: self._file_handle = log_file # parse the whole file self._read_file_header() self._last_timestamp = self._start_timestamp self._read_file_definitions() if self.has_data_appended and len(self._appended_offsets) > 0: if self._debug: print('This file has data appended') for offset in self._appended_offsets: self._read_file_data(message_name_filter_list, read_until=offset) self._file_handle.seek(offset) # read the whole file, or the rest if data appended self._read_file_data(message_name_filter_list) self._file_handle.close() del self._file_handle def _read_file_header(self): header_data = self._file_handle.read(16) if len(header_data) != 16: raise Exception("Invalid file format (Header too short)") if header_data[:7] != self.HEADER_BYTES: raise Exception("Invalid file format (Failed to parse header)") self._file_version, = struct.unpack('B', header_data[7:8]) if self._file_version > 1: print("Warning: unknown file version. Will attempt to read it anyway") # read timestamp self._start_timestamp, = ULog._unpack_uint64(header_data[8:]) def _read_file_definitions(self): header = self._MessageHeader() while True: data = self._file_handle.read(3) if not data: break header.initialize(data) data = self._file_handle.read(header.msg_size) if header.msg_type == self.MSG_TYPE_INFO: msg_info = self._MessageInfo(data, header) self._msg_info_dict[msg_info.key] = msg_info.value elif header.msg_type == self.MSG_TYPE_INFO_MULTIPLE: msg_info = self._MessageInfo(data, header, is_info_multiple=True) self._add_message_info_multiple(msg_info) elif header.msg_type == self.MSG_TYPE_FORMAT: msg_format = self.MessageFormat(data, header) self._message_formats[msg_format.name] = msg_format elif header.msg_type == self.MSG_TYPE_PARAMETER: msg_info = self._MessageInfo(data, header) self._initial_parameters[msg_info.key] = msg_info.value elif (header.msg_type == self.MSG_TYPE_ADD_LOGGED_MSG or header.msg_type == self.MSG_TYPE_LOGGING): self._file_handle.seek(-(3+header.msg_size), 1) break # end of section elif header.msg_type == self.MSG_TYPE_FLAG_BITS: # make sure this is the first message in the log if self._file_handle.tell() != 16 + 3 + header.msg_size: print('Error: FLAGS_BITS message must be first message. Offset:', self._file_handle.tell()) msg_flag_bits = self._MessageFlagBits(data, header) self._compat_flags = msg_flag_bits.compat_flags self._incompat_flags = msg_flag_bits.incompat_flags self._appended_offsets = msg_flag_bits.appended_offsets if self._debug: print('compat flags: ', self._compat_flags) print('incompat flags:', self._incompat_flags) print('appended offsets:', self._appended_offsets) # check if there are bits set that we don't know unknown_incompat_flag_msg = "Unknown incompatible flag set: cannot parse the log" if self._incompat_flags[0] & ~1: raise Exception(unknown_incompat_flag_msg) for i in range(1, 8): if self._incompat_flags[i]: raise Exception(unknown_incompat_flag_msg) else: if self._debug: print('read_file_definitions: unknown message type: %i (%s)' % (header.msg_type, chr(header.msg_type))) file_position = self._file_handle.tell() print('file position: %i (0x%x) msg size: %i' % ( file_position, file_position, header.msg_size)) if self._check_file_corruption(header): # seek back to advance only by a single byte instead of # skipping the message self._file_handle.seek(-2-header.msg_size, 1) def _read_file_data(self, message_name_filter_list, read_until=None): """ read the file data section :param read_until: an optional file offset: if set, parse only up to this offset (smaller than) """ if read_until is None: read_until = 1 << 50 # make it larger than any possible log file try: # pre-init reusable objects header = self._MessageHeader() msg_data = self._MessageData() while True: data = self._file_handle.read(3) header.initialize(data) data = self._file_handle.read(header.msg_size) if len(data) < header.msg_size: break # less data than expected. File is most likely cut if self._file_handle.tell() > read_until: if self._debug: print('read until offset=%i done, current pos=%i' % (read_until, self._file_handle.tell())) break if header.msg_type == self.MSG_TYPE_INFO: msg_info = self._MessageInfo(data, header) self._msg_info_dict[msg_info.key] = msg_info.value elif header.msg_type == self.MSG_TYPE_INFO_MULTIPLE: msg_info = self._MessageInfo(data, header, is_info_multiple=True) self._add_message_info_multiple(msg_info) elif header.msg_type == self.MSG_TYPE_PARAMETER: msg_info = self._MessageInfo(data, header) self._changed_parameters.append((self._last_timestamp, msg_info.key, msg_info.value)) elif header.msg_type == self.MSG_TYPE_ADD_LOGGED_MSG: msg_add_logged = self._MessageAddLogged(data, header, self._message_formats) if (message_name_filter_list is None or msg_add_logged.message_name in message_name_filter_list): self._subscriptions[msg_add_logged.msg_id] = msg_add_logged else: self._filtered_message_ids.add(msg_add_logged.msg_id) elif header.msg_type == self.MSG_TYPE_LOGGING: msg_logging = self.MessageLogging(data, header) self._logged_messages.append(msg_logging) elif header.msg_type == self.MSG_TYPE_DATA: msg_data.initialize(data, header, self._subscriptions, self) if msg_data.timestamp != 0 and msg_data.timestamp > self._last_timestamp: self._last_timestamp = msg_data.timestamp elif header.msg_type == self.MSG_TYPE_DROPOUT: msg_dropout = self.MessageDropout(data, header, self._last_timestamp) self._dropouts.append(msg_dropout) else: if self._debug: print('_read_file_data: unknown message type: %i (%s)' % (header.msg_type, chr(header.msg_type))) file_position = self._file_handle.tell() print('file position: %i (0x%x) msg size: %i' % ( file_position, file_position, header.msg_size)) if self._check_file_corruption(header): # seek back to advance only by a single byte instead of # skipping the message self._file_handle.seek(-2-header.msg_size, 1) except struct.error: pass #we read past the end of the file # convert into final representation while self._subscriptions: _, value = self._subscriptions.popitem() if len(value.buffer) > 0: # only add if we have data data_item = ULog.Data(value) self._data_list.append(data_item) def _check_file_corruption(self, header): """ check for file corruption based on an unknown message type in the header """ # We need to handle 2 cases: # - corrupt file (we do our best to read the rest of the file) # - new ULog message type got added (we just want to skip the message) if header.msg_type == 0 or header.msg_size == 0 or header.msg_size > 10000: if not self._file_corrupt and self._debug: print('File corruption detected') self._file_corrupt = True return self._file_corrupt def get_version_info(self, key_name='ver_sw_release'): """ get the (major, minor, patch, type) version information as tuple. Returns None if not found definition of type is: >= 0: development >= 64: alpha version >= 128: beta version >= 192: RC version == 255: release version """ if key_name in self._msg_info_dict: val = self._msg_info_dict[key_name] return ((val >> 24) & 0xff, (val >> 16) & 0xff, (val >> 8) & 0xff, val & 0xff) return None def get_version_info_str(self, key_name='ver_sw_release'): """ get version information in the form 'v1.2.3 (RC)', or None if version tag either not found or it's a development version """ version = self.get_version_info(key_name) if not version is None and version[3] >= 64: type_str = '' if version[3] < 128: type_str = ' (alpha)' elif version[3] < 192: type_str = ' (beta)' elif version[3] < 255: type_str = ' (RC)' return 'v{}.{}.{}{}'.format(version[0], version[1], version[2], type_str) return None
PX4/pyulog
pyulog/core.py
ULog._add_message_info_multiple
python
def _add_message_info_multiple(self, msg_info): if msg_info.key in self._msg_info_multiple_dict: if msg_info.is_continued: self._msg_info_multiple_dict[msg_info.key][-1].append(msg_info.value) else: self._msg_info_multiple_dict[msg_info.key].append([msg_info.value]) else: self._msg_info_multiple_dict[msg_info.key] = [[msg_info.value]]
add a message info multiple to self._msg_info_multiple_dict
train
https://github.com/PX4/pyulog/blob/3bc4f9338d30e2e0a0dfbed58f54d200967e5056/pyulog/core.py#L416-L424
null
class ULog(object): """ This class parses an ulog file """ ## constants ## HEADER_BYTES = b'\x55\x4c\x6f\x67\x01\x12\x35' # message types MSG_TYPE_FORMAT = ord('F') MSG_TYPE_DATA = ord('D') MSG_TYPE_INFO = ord('I') MSG_TYPE_INFO_MULTIPLE = ord('M') MSG_TYPE_PARAMETER = ord('P') MSG_TYPE_ADD_LOGGED_MSG = ord('A') MSG_TYPE_REMOVE_LOGGED_MSG = ord('R') MSG_TYPE_SYNC = ord('S') MSG_TYPE_DROPOUT = ord('O') MSG_TYPE_LOGGING = ord('L') MSG_TYPE_FLAG_BITS = ord('B') _UNPACK_TYPES = { 'int8_t': ['b', 1, np.int8], 'uint8_t': ['B', 1, np.uint8], 'int16_t': ['h', 2, np.int16], 'uint16_t': ['H', 2, np.uint16], 'int32_t': ['i', 4, np.int32], 'uint32_t': ['I', 4, np.uint32], 'int64_t': ['q', 8, np.int64], 'uint64_t': ['Q', 8, np.uint64], 'float': ['f', 4, np.float32], 'double': ['d', 8, np.float64], 'bool': ['?', 1, np.int8], 'char': ['c', 1, np.int8] } @staticmethod def get_field_size(type_str): """ get the field size in bytes. :param type_str: type string, eg. 'int8_t' """ return ULog._UNPACK_TYPES[type_str][1] # pre-init unpack structs for quicker use _unpack_ushort_byte = struct.Struct('<HB').unpack _unpack_ushort = struct.Struct('<H').unpack _unpack_uint64 = struct.Struct('<Q').unpack def __init__(self, log_file, message_name_filter_list=None): """ Initialize the object & load the file. :param log_file: a file name (str) or a readable file object :param message_name_filter_list: list of strings, to only load messages with the given names. If None, load everything. """ self._debug = False self._file_corrupt = False self._start_timestamp = 0 self._last_timestamp = 0 self._msg_info_dict = {} self._msg_info_multiple_dict = {} self._initial_parameters = {} self._changed_parameters = [] self._message_formats = {} self._logged_messages = [] self._dropouts = [] self._data_list = [] self._subscriptions = {} # dict of key=msg_id, value=_MessageAddLogged self._filtered_message_ids = set() # _MessageAddLogged id's that are filtered self._missing_message_ids = set() # _MessageAddLogged id's that could not be found self._file_version = 0 self._compat_flags = [0] * 8 self._incompat_flags = [0] * 8 self._appended_offsets = [] # file offsets for appended data self._load_file(log_file, message_name_filter_list) ## parsed data @property def start_timestamp(self): """ timestamp of file start """ return self._start_timestamp @property def last_timestamp(self): """ timestamp of last message """ return self._last_timestamp @property def msg_info_dict(self): """ dictionary of all information messages (key is a string, value depends on the type, usually string or int) """ return self._msg_info_dict @property def msg_info_multiple_dict(self): """ dictionary of all information multiple messages (key is a string, value is a list of lists that contains the messages) """ return self._msg_info_multiple_dict @property def initial_parameters(self): """ dictionary of all initially set parameters (key=param name) """ return self._initial_parameters @property def changed_parameters(self): """ list of all changed parameters (tuple of (timestamp, name, value))""" return self._changed_parameters @property def message_formats(self): """ dictionary with key = format name (MessageFormat.name), value = MessageFormat object """ return self._message_formats @property def logged_messages(self): """ list of MessageLogging objects """ return self._logged_messages @property def dropouts(self): """ list of MessageDropout objects """ return self._dropouts @property def data_list(self): """ extracted data: list of Data objects """ return self._data_list @property def has_data_appended(self): """ returns True if the log has data appended, False otherwise """ return self._incompat_flags[0] & 0x1 @property def file_corruption(self): """ True if a file corruption got detected """ return self._file_corrupt def get_dataset(self, name, multi_instance=0): """ get a specific dataset. example: try: gyro_data = ulog.get_dataset('sensor_gyro') except (KeyError, IndexError, ValueError) as error: print(type(error), "(sensor_gyro):", error) :param name: name of the dataset :param multi_instance: the multi_id, defaults to the first :raises KeyError, IndexError, ValueError: if name or instance not found """ return [elem for elem in self._data_list if elem.name == name and elem.multi_id == multi_instance][0] class Data(object): """ contains the final topic data for a single topic and instance """ def __init__(self, message_add_logged_obj): self.multi_id = message_add_logged_obj.multi_id self.name = message_add_logged_obj.message_name self.field_data = message_add_logged_obj.field_data self.timestamp_idx = message_add_logged_obj.timestamp_idx # get data as numpy.ndarray np_array = np.frombuffer(message_add_logged_obj.buffer, dtype=message_add_logged_obj.dtype) # convert into dict of np.array (which is easier to handle) self.data = {} for name in np_array.dtype.names: self.data[name] = np_array[name] def list_value_changes(self, field_name): """ get a list of (timestamp, value) tuples, whenever the value changes. The first data point with non-zero timestamp is always included, messages with timestamp = 0 are ignored """ t = self.data['timestamp'] x = self.data[field_name] indices = t != 0 # filter out 0 values t = t[indices] x = x[indices] if len(t) == 0: return [] ret = [(t[0], x[0])] indices = np.where(x[:-1] != x[1:])[0] + 1 ret.extend(zip(t[indices], x[indices])) return ret ## Representations of the messages from the log file ## class _MessageHeader(object): """ 3 bytes ULog message header """ def __init__(self): self.msg_size = 0 self.msg_type = 0 def initialize(self, data): self.msg_size, self.msg_type = ULog._unpack_ushort_byte(data) class _MessageInfo(object): """ ULog info message representation """ def __init__(self, data, header, is_info_multiple=False): if is_info_multiple: # INFO_MULTIPLE message self.is_continued, = struct.unpack('<B', data[0:1]) data = data[1:] key_len, = struct.unpack('<B', data[0:1]) type_key = _parse_string(data[1:1+key_len]) type_key_split = type_key.split(' ') self.type = type_key_split[0] self.key = type_key_split[1] if self.type.startswith('char['): # it's a string self.value = _parse_string(data[1+key_len:]) elif self.type in ULog._UNPACK_TYPES: unpack_type = ULog._UNPACK_TYPES[self.type] self.value, = struct.unpack('<'+unpack_type[0], data[1+key_len:]) else: # probably an array (or non-basic type) self.value = data[1+key_len:] class _MessageFlagBits(object): """ ULog message flag bits """ def __init__(self, data, header): if header.msg_size > 8 + 8 + 3*8: # we can still parse it but might miss some information print('Warning: Flags Bit message is longer than expected') self.compat_flags = list(struct.unpack('<'+'B'*8, data[0:8])) self.incompat_flags = list(struct.unpack('<'+'B'*8, data[8:16])) self.appended_offsets = list(struct.unpack('<'+'Q'*3, data[16:16+3*8])) # remove the 0's at the end while len(self.appended_offsets) > 0 and self.appended_offsets[-1] == 0: self.appended_offsets.pop() class MessageFormat(object): """ ULog message format representation """ def __init__(self, data, header): format_arr = _parse_string(data).split(':') self.name = format_arr[0] types_str = format_arr[1].split(';') self.fields = [] # list of tuples (type, array_size, name) for t in types_str: if len(t) > 0: self.fields.append(self._extract_type(t)) @staticmethod def _extract_type(field_str): field_str_split = field_str.split(' ') type_str = field_str_split[0] name_str = field_str_split[1] a_pos = type_str.find('[') if a_pos == -1: array_size = 1 type_name = type_str else: b_pos = type_str.find(']') array_size = int(type_str[a_pos+1:b_pos]) type_name = type_str[:a_pos] return type_name, array_size, name_str class MessageLogging(object): """ ULog logged string message representation """ def __init__(self, data, header): self.log_level, = struct.unpack('<B', data[0:1]) self.timestamp, = struct.unpack('<Q', data[1:9]) self.message = _parse_string(data[9:]) def log_level_str(self): return {ord('0'): 'EMERGENCY', ord('1'): 'ALERT', ord('2'): 'CRITICAL', ord('3'): 'ERROR', ord('4'): 'WARNING', ord('5'): 'NOTICE', ord('6'): 'INFO', ord('7'): 'DEBUG'}.get(self.log_level, 'UNKNOWN') class MessageDropout(object): """ ULog dropout message representation """ def __init__(self, data, header, timestamp): self.duration, = struct.unpack('<H', data) self.timestamp = timestamp class _FieldData(object): """ Type and name of a single ULog data field """ def __init__(self, field_name, type_str): self.field_name = field_name self.type_str = type_str class _MessageAddLogged(object): """ ULog add logging data message representation """ def __init__(self, data, header, message_formats): self.multi_id, = struct.unpack('<B', data[0:1]) self.msg_id, = struct.unpack('<H', data[1:3]) self.message_name = _parse_string(data[3:]) self.field_data = [] # list of _FieldData self.timestamp_idx = -1 self._parse_format(message_formats) self.timestamp_offset = 0 for field in self.field_data: if field.field_name == 'timestamp': break self.timestamp_offset += ULog._UNPACK_TYPES[field.type_str][1] self.buffer = bytearray() # accumulate all message data here # construct types for numpy dtype_list = [] for field in self.field_data: numpy_type = ULog._UNPACK_TYPES[field.type_str][2] dtype_list.append((field.field_name, numpy_type)) self.dtype = np.dtype(dtype_list).newbyteorder('<') def _parse_format(self, message_formats): self._parse_nested_type('', self.message_name, message_formats) # remove padding fields at the end while (len(self.field_data) > 0 and self.field_data[-1].field_name.startswith('_padding')): self.field_data.pop() def _parse_nested_type(self, prefix_str, type_name, message_formats): # we flatten nested types message_format = message_formats[type_name] for (type_name_fmt, array_size, field_name) in message_format.fields: if type_name_fmt in ULog._UNPACK_TYPES: if array_size > 1: for i in range(array_size): self.field_data.append(ULog._FieldData( prefix_str+field_name+'['+str(i)+']', type_name_fmt)) else: self.field_data.append(ULog._FieldData( prefix_str+field_name, type_name_fmt)) if prefix_str+field_name == 'timestamp': self.timestamp_idx = len(self.field_data) - 1 else: # nested type if array_size > 1: for i in range(array_size): self._parse_nested_type(prefix_str+field_name+'['+str(i)+'].', type_name_fmt, message_formats) else: self._parse_nested_type(prefix_str+field_name+'.', type_name_fmt, message_formats) class _MessageData(object): def __init__(self): self.timestamp = 0 def initialize(self, data, header, subscriptions, ulog_object): msg_id, = ULog._unpack_ushort(data[:2]) if msg_id in subscriptions: subscription = subscriptions[msg_id] # accumulate data to a buffer, will be parsed later subscription.buffer += data[2:] t_off = subscription.timestamp_offset # TODO: the timestamp can have another size than uint64 self.timestamp, = ULog._unpack_uint64(data[t_off+2:t_off+10]) else: if not msg_id in ulog_object._filtered_message_ids: # this is an error, but make it non-fatal if not msg_id in ulog_object._missing_message_ids: ulog_object._missing_message_ids.add(msg_id) if ulog_object._debug: print(ulog_object._file_handle.tell()) print('Warning: no subscription found for message id {:}. Continuing,' ' but file is most likely corrupt'.format(msg_id)) self.timestamp = 0 def _load_file(self, log_file, message_name_filter_list): """ load and parse an ULog file into memory """ if isinstance(log_file, str): self._file_handle = open(log_file, "rb") else: self._file_handle = log_file # parse the whole file self._read_file_header() self._last_timestamp = self._start_timestamp self._read_file_definitions() if self.has_data_appended and len(self._appended_offsets) > 0: if self._debug: print('This file has data appended') for offset in self._appended_offsets: self._read_file_data(message_name_filter_list, read_until=offset) self._file_handle.seek(offset) # read the whole file, or the rest if data appended self._read_file_data(message_name_filter_list) self._file_handle.close() del self._file_handle def _read_file_header(self): header_data = self._file_handle.read(16) if len(header_data) != 16: raise Exception("Invalid file format (Header too short)") if header_data[:7] != self.HEADER_BYTES: raise Exception("Invalid file format (Failed to parse header)") self._file_version, = struct.unpack('B', header_data[7:8]) if self._file_version > 1: print("Warning: unknown file version. Will attempt to read it anyway") # read timestamp self._start_timestamp, = ULog._unpack_uint64(header_data[8:]) def _read_file_definitions(self): header = self._MessageHeader() while True: data = self._file_handle.read(3) if not data: break header.initialize(data) data = self._file_handle.read(header.msg_size) if header.msg_type == self.MSG_TYPE_INFO: msg_info = self._MessageInfo(data, header) self._msg_info_dict[msg_info.key] = msg_info.value elif header.msg_type == self.MSG_TYPE_INFO_MULTIPLE: msg_info = self._MessageInfo(data, header, is_info_multiple=True) self._add_message_info_multiple(msg_info) elif header.msg_type == self.MSG_TYPE_FORMAT: msg_format = self.MessageFormat(data, header) self._message_formats[msg_format.name] = msg_format elif header.msg_type == self.MSG_TYPE_PARAMETER: msg_info = self._MessageInfo(data, header) self._initial_parameters[msg_info.key] = msg_info.value elif (header.msg_type == self.MSG_TYPE_ADD_LOGGED_MSG or header.msg_type == self.MSG_TYPE_LOGGING): self._file_handle.seek(-(3+header.msg_size), 1) break # end of section elif header.msg_type == self.MSG_TYPE_FLAG_BITS: # make sure this is the first message in the log if self._file_handle.tell() != 16 + 3 + header.msg_size: print('Error: FLAGS_BITS message must be first message. Offset:', self._file_handle.tell()) msg_flag_bits = self._MessageFlagBits(data, header) self._compat_flags = msg_flag_bits.compat_flags self._incompat_flags = msg_flag_bits.incompat_flags self._appended_offsets = msg_flag_bits.appended_offsets if self._debug: print('compat flags: ', self._compat_flags) print('incompat flags:', self._incompat_flags) print('appended offsets:', self._appended_offsets) # check if there are bits set that we don't know unknown_incompat_flag_msg = "Unknown incompatible flag set: cannot parse the log" if self._incompat_flags[0] & ~1: raise Exception(unknown_incompat_flag_msg) for i in range(1, 8): if self._incompat_flags[i]: raise Exception(unknown_incompat_flag_msg) else: if self._debug: print('read_file_definitions: unknown message type: %i (%s)' % (header.msg_type, chr(header.msg_type))) file_position = self._file_handle.tell() print('file position: %i (0x%x) msg size: %i' % ( file_position, file_position, header.msg_size)) if self._check_file_corruption(header): # seek back to advance only by a single byte instead of # skipping the message self._file_handle.seek(-2-header.msg_size, 1) def _read_file_data(self, message_name_filter_list, read_until=None): """ read the file data section :param read_until: an optional file offset: if set, parse only up to this offset (smaller than) """ if read_until is None: read_until = 1 << 50 # make it larger than any possible log file try: # pre-init reusable objects header = self._MessageHeader() msg_data = self._MessageData() while True: data = self._file_handle.read(3) header.initialize(data) data = self._file_handle.read(header.msg_size) if len(data) < header.msg_size: break # less data than expected. File is most likely cut if self._file_handle.tell() > read_until: if self._debug: print('read until offset=%i done, current pos=%i' % (read_until, self._file_handle.tell())) break if header.msg_type == self.MSG_TYPE_INFO: msg_info = self._MessageInfo(data, header) self._msg_info_dict[msg_info.key] = msg_info.value elif header.msg_type == self.MSG_TYPE_INFO_MULTIPLE: msg_info = self._MessageInfo(data, header, is_info_multiple=True) self._add_message_info_multiple(msg_info) elif header.msg_type == self.MSG_TYPE_PARAMETER: msg_info = self._MessageInfo(data, header) self._changed_parameters.append((self._last_timestamp, msg_info.key, msg_info.value)) elif header.msg_type == self.MSG_TYPE_ADD_LOGGED_MSG: msg_add_logged = self._MessageAddLogged(data, header, self._message_formats) if (message_name_filter_list is None or msg_add_logged.message_name in message_name_filter_list): self._subscriptions[msg_add_logged.msg_id] = msg_add_logged else: self._filtered_message_ids.add(msg_add_logged.msg_id) elif header.msg_type == self.MSG_TYPE_LOGGING: msg_logging = self.MessageLogging(data, header) self._logged_messages.append(msg_logging) elif header.msg_type == self.MSG_TYPE_DATA: msg_data.initialize(data, header, self._subscriptions, self) if msg_data.timestamp != 0 and msg_data.timestamp > self._last_timestamp: self._last_timestamp = msg_data.timestamp elif header.msg_type == self.MSG_TYPE_DROPOUT: msg_dropout = self.MessageDropout(data, header, self._last_timestamp) self._dropouts.append(msg_dropout) else: if self._debug: print('_read_file_data: unknown message type: %i (%s)' % (header.msg_type, chr(header.msg_type))) file_position = self._file_handle.tell() print('file position: %i (0x%x) msg size: %i' % ( file_position, file_position, header.msg_size)) if self._check_file_corruption(header): # seek back to advance only by a single byte instead of # skipping the message self._file_handle.seek(-2-header.msg_size, 1) except struct.error: pass #we read past the end of the file # convert into final representation while self._subscriptions: _, value = self._subscriptions.popitem() if len(value.buffer) > 0: # only add if we have data data_item = ULog.Data(value) self._data_list.append(data_item) def _check_file_corruption(self, header): """ check for file corruption based on an unknown message type in the header """ # We need to handle 2 cases: # - corrupt file (we do our best to read the rest of the file) # - new ULog message type got added (we just want to skip the message) if header.msg_type == 0 or header.msg_size == 0 or header.msg_size > 10000: if not self._file_corrupt and self._debug: print('File corruption detected') self._file_corrupt = True return self._file_corrupt def get_version_info(self, key_name='ver_sw_release'): """ get the (major, minor, patch, type) version information as tuple. Returns None if not found definition of type is: >= 0: development >= 64: alpha version >= 128: beta version >= 192: RC version == 255: release version """ if key_name in self._msg_info_dict: val = self._msg_info_dict[key_name] return ((val >> 24) & 0xff, (val >> 16) & 0xff, (val >> 8) & 0xff, val & 0xff) return None def get_version_info_str(self, key_name='ver_sw_release'): """ get version information in the form 'v1.2.3 (RC)', or None if version tag either not found or it's a development version """ version = self.get_version_info(key_name) if not version is None and version[3] >= 64: type_str = '' if version[3] < 128: type_str = ' (alpha)' elif version[3] < 192: type_str = ' (beta)' elif version[3] < 255: type_str = ' (RC)' return 'v{}.{}.{}{}'.format(version[0], version[1], version[2], type_str) return None
PX4/pyulog
pyulog/core.py
ULog._load_file
python
def _load_file(self, log_file, message_name_filter_list): if isinstance(log_file, str): self._file_handle = open(log_file, "rb") else: self._file_handle = log_file # parse the whole file self._read_file_header() self._last_timestamp = self._start_timestamp self._read_file_definitions() if self.has_data_appended and len(self._appended_offsets) > 0: if self._debug: print('This file has data appended') for offset in self._appended_offsets: self._read_file_data(message_name_filter_list, read_until=offset) self._file_handle.seek(offset) # read the whole file, or the rest if data appended self._read_file_data(message_name_filter_list) self._file_handle.close() del self._file_handle
load and parse an ULog file into memory
train
https://github.com/PX4/pyulog/blob/3bc4f9338d30e2e0a0dfbed58f54d200967e5056/pyulog/core.py#L426-L449
[ "def _read_file_header(self):\n header_data = self._file_handle.read(16)\n if len(header_data) != 16:\n raise Exception(\"Invalid file format (Header too short)\")\n if header_data[:7] != self.HEADER_BYTES:\n raise Exception(\"Invalid file format (Failed to parse header)\")\n self._file_version, = struct.unpack('B', header_data[7:8])\n if self._file_version > 1:\n print(\"Warning: unknown file version. Will attempt to read it anyway\")\n\n # read timestamp\n self._start_timestamp, = ULog._unpack_uint64(header_data[8:])\n", "def _read_file_definitions(self):\n header = self._MessageHeader()\n while True:\n data = self._file_handle.read(3)\n if not data:\n break\n header.initialize(data)\n data = self._file_handle.read(header.msg_size)\n if header.msg_type == self.MSG_TYPE_INFO:\n msg_info = self._MessageInfo(data, header)\n self._msg_info_dict[msg_info.key] = msg_info.value\n elif header.msg_type == self.MSG_TYPE_INFO_MULTIPLE:\n msg_info = self._MessageInfo(data, header, is_info_multiple=True)\n self._add_message_info_multiple(msg_info)\n elif header.msg_type == self.MSG_TYPE_FORMAT:\n msg_format = self.MessageFormat(data, header)\n self._message_formats[msg_format.name] = msg_format\n elif header.msg_type == self.MSG_TYPE_PARAMETER:\n msg_info = self._MessageInfo(data, header)\n self._initial_parameters[msg_info.key] = msg_info.value\n elif (header.msg_type == self.MSG_TYPE_ADD_LOGGED_MSG or\n header.msg_type == self.MSG_TYPE_LOGGING):\n self._file_handle.seek(-(3+header.msg_size), 1)\n break # end of section\n elif header.msg_type == self.MSG_TYPE_FLAG_BITS:\n # make sure this is the first message in the log\n if self._file_handle.tell() != 16 + 3 + header.msg_size:\n print('Error: FLAGS_BITS message must be first message. Offset:',\n self._file_handle.tell())\n msg_flag_bits = self._MessageFlagBits(data, header)\n self._compat_flags = msg_flag_bits.compat_flags\n self._incompat_flags = msg_flag_bits.incompat_flags\n self._appended_offsets = msg_flag_bits.appended_offsets\n if self._debug:\n print('compat flags: ', self._compat_flags)\n print('incompat flags:', self._incompat_flags)\n print('appended offsets:', self._appended_offsets)\n\n # check if there are bits set that we don't know\n unknown_incompat_flag_msg = \"Unknown incompatible flag set: cannot parse the log\"\n if self._incompat_flags[0] & ~1:\n raise Exception(unknown_incompat_flag_msg)\n for i in range(1, 8):\n if self._incompat_flags[i]:\n raise Exception(unknown_incompat_flag_msg)\n\n else:\n if self._debug:\n print('read_file_definitions: unknown message type: %i (%s)' %\n (header.msg_type, chr(header.msg_type)))\n file_position = self._file_handle.tell()\n print('file position: %i (0x%x) msg size: %i' % (\n file_position, file_position, header.msg_size))\n if self._check_file_corruption(header):\n # seek back to advance only by a single byte instead of\n # skipping the message\n self._file_handle.seek(-2-header.msg_size, 1)\n", "def _read_file_data(self, message_name_filter_list, read_until=None):\n \"\"\"\n read the file data section\n :param read_until: an optional file offset: if set, parse only up to\n this offset (smaller than)\n \"\"\"\n\n if read_until is None:\n read_until = 1 << 50 # make it larger than any possible log file\n\n try:\n # pre-init reusable objects\n header = self._MessageHeader()\n msg_data = self._MessageData()\n\n while True:\n data = self._file_handle.read(3)\n header.initialize(data)\n data = self._file_handle.read(header.msg_size)\n if len(data) < header.msg_size:\n break # less data than expected. File is most likely cut\n\n if self._file_handle.tell() > read_until:\n if self._debug:\n print('read until offset=%i done, current pos=%i' %\n (read_until, self._file_handle.tell()))\n break\n\n if header.msg_type == self.MSG_TYPE_INFO:\n msg_info = self._MessageInfo(data, header)\n self._msg_info_dict[msg_info.key] = msg_info.value\n elif header.msg_type == self.MSG_TYPE_INFO_MULTIPLE:\n msg_info = self._MessageInfo(data, header, is_info_multiple=True)\n self._add_message_info_multiple(msg_info)\n elif header.msg_type == self.MSG_TYPE_PARAMETER:\n msg_info = self._MessageInfo(data, header)\n self._changed_parameters.append((self._last_timestamp,\n msg_info.key, msg_info.value))\n elif header.msg_type == self.MSG_TYPE_ADD_LOGGED_MSG:\n msg_add_logged = self._MessageAddLogged(data, header,\n self._message_formats)\n if (message_name_filter_list is None or\n msg_add_logged.message_name in message_name_filter_list):\n self._subscriptions[msg_add_logged.msg_id] = msg_add_logged\n else:\n self._filtered_message_ids.add(msg_add_logged.msg_id)\n elif header.msg_type == self.MSG_TYPE_LOGGING:\n msg_logging = self.MessageLogging(data, header)\n self._logged_messages.append(msg_logging)\n elif header.msg_type == self.MSG_TYPE_DATA:\n msg_data.initialize(data, header, self._subscriptions, self)\n if msg_data.timestamp != 0 and msg_data.timestamp > self._last_timestamp:\n self._last_timestamp = msg_data.timestamp\n elif header.msg_type == self.MSG_TYPE_DROPOUT:\n msg_dropout = self.MessageDropout(data, header,\n self._last_timestamp)\n self._dropouts.append(msg_dropout)\n else:\n if self._debug:\n print('_read_file_data: unknown message type: %i (%s)' %\n (header.msg_type, chr(header.msg_type)))\n file_position = self._file_handle.tell()\n print('file position: %i (0x%x) msg size: %i' % (\n file_position, file_position, header.msg_size))\n\n if self._check_file_corruption(header):\n # seek back to advance only by a single byte instead of\n # skipping the message\n self._file_handle.seek(-2-header.msg_size, 1)\n\n except struct.error:\n pass #we read past the end of the file\n\n # convert into final representation\n while self._subscriptions:\n _, value = self._subscriptions.popitem()\n if len(value.buffer) > 0: # only add if we have data\n data_item = ULog.Data(value)\n self._data_list.append(data_item)\n" ]
class ULog(object): """ This class parses an ulog file """ ## constants ## HEADER_BYTES = b'\x55\x4c\x6f\x67\x01\x12\x35' # message types MSG_TYPE_FORMAT = ord('F') MSG_TYPE_DATA = ord('D') MSG_TYPE_INFO = ord('I') MSG_TYPE_INFO_MULTIPLE = ord('M') MSG_TYPE_PARAMETER = ord('P') MSG_TYPE_ADD_LOGGED_MSG = ord('A') MSG_TYPE_REMOVE_LOGGED_MSG = ord('R') MSG_TYPE_SYNC = ord('S') MSG_TYPE_DROPOUT = ord('O') MSG_TYPE_LOGGING = ord('L') MSG_TYPE_FLAG_BITS = ord('B') _UNPACK_TYPES = { 'int8_t': ['b', 1, np.int8], 'uint8_t': ['B', 1, np.uint8], 'int16_t': ['h', 2, np.int16], 'uint16_t': ['H', 2, np.uint16], 'int32_t': ['i', 4, np.int32], 'uint32_t': ['I', 4, np.uint32], 'int64_t': ['q', 8, np.int64], 'uint64_t': ['Q', 8, np.uint64], 'float': ['f', 4, np.float32], 'double': ['d', 8, np.float64], 'bool': ['?', 1, np.int8], 'char': ['c', 1, np.int8] } @staticmethod def get_field_size(type_str): """ get the field size in bytes. :param type_str: type string, eg. 'int8_t' """ return ULog._UNPACK_TYPES[type_str][1] # pre-init unpack structs for quicker use _unpack_ushort_byte = struct.Struct('<HB').unpack _unpack_ushort = struct.Struct('<H').unpack _unpack_uint64 = struct.Struct('<Q').unpack def __init__(self, log_file, message_name_filter_list=None): """ Initialize the object & load the file. :param log_file: a file name (str) or a readable file object :param message_name_filter_list: list of strings, to only load messages with the given names. If None, load everything. """ self._debug = False self._file_corrupt = False self._start_timestamp = 0 self._last_timestamp = 0 self._msg_info_dict = {} self._msg_info_multiple_dict = {} self._initial_parameters = {} self._changed_parameters = [] self._message_formats = {} self._logged_messages = [] self._dropouts = [] self._data_list = [] self._subscriptions = {} # dict of key=msg_id, value=_MessageAddLogged self._filtered_message_ids = set() # _MessageAddLogged id's that are filtered self._missing_message_ids = set() # _MessageAddLogged id's that could not be found self._file_version = 0 self._compat_flags = [0] * 8 self._incompat_flags = [0] * 8 self._appended_offsets = [] # file offsets for appended data self._load_file(log_file, message_name_filter_list) ## parsed data @property def start_timestamp(self): """ timestamp of file start """ return self._start_timestamp @property def last_timestamp(self): """ timestamp of last message """ return self._last_timestamp @property def msg_info_dict(self): """ dictionary of all information messages (key is a string, value depends on the type, usually string or int) """ return self._msg_info_dict @property def msg_info_multiple_dict(self): """ dictionary of all information multiple messages (key is a string, value is a list of lists that contains the messages) """ return self._msg_info_multiple_dict @property def initial_parameters(self): """ dictionary of all initially set parameters (key=param name) """ return self._initial_parameters @property def changed_parameters(self): """ list of all changed parameters (tuple of (timestamp, name, value))""" return self._changed_parameters @property def message_formats(self): """ dictionary with key = format name (MessageFormat.name), value = MessageFormat object """ return self._message_formats @property def logged_messages(self): """ list of MessageLogging objects """ return self._logged_messages @property def dropouts(self): """ list of MessageDropout objects """ return self._dropouts @property def data_list(self): """ extracted data: list of Data objects """ return self._data_list @property def has_data_appended(self): """ returns True if the log has data appended, False otherwise """ return self._incompat_flags[0] & 0x1 @property def file_corruption(self): """ True if a file corruption got detected """ return self._file_corrupt def get_dataset(self, name, multi_instance=0): """ get a specific dataset. example: try: gyro_data = ulog.get_dataset('sensor_gyro') except (KeyError, IndexError, ValueError) as error: print(type(error), "(sensor_gyro):", error) :param name: name of the dataset :param multi_instance: the multi_id, defaults to the first :raises KeyError, IndexError, ValueError: if name or instance not found """ return [elem for elem in self._data_list if elem.name == name and elem.multi_id == multi_instance][0] class Data(object): """ contains the final topic data for a single topic and instance """ def __init__(self, message_add_logged_obj): self.multi_id = message_add_logged_obj.multi_id self.name = message_add_logged_obj.message_name self.field_data = message_add_logged_obj.field_data self.timestamp_idx = message_add_logged_obj.timestamp_idx # get data as numpy.ndarray np_array = np.frombuffer(message_add_logged_obj.buffer, dtype=message_add_logged_obj.dtype) # convert into dict of np.array (which is easier to handle) self.data = {} for name in np_array.dtype.names: self.data[name] = np_array[name] def list_value_changes(self, field_name): """ get a list of (timestamp, value) tuples, whenever the value changes. The first data point with non-zero timestamp is always included, messages with timestamp = 0 are ignored """ t = self.data['timestamp'] x = self.data[field_name] indices = t != 0 # filter out 0 values t = t[indices] x = x[indices] if len(t) == 0: return [] ret = [(t[0], x[0])] indices = np.where(x[:-1] != x[1:])[0] + 1 ret.extend(zip(t[indices], x[indices])) return ret ## Representations of the messages from the log file ## class _MessageHeader(object): """ 3 bytes ULog message header """ def __init__(self): self.msg_size = 0 self.msg_type = 0 def initialize(self, data): self.msg_size, self.msg_type = ULog._unpack_ushort_byte(data) class _MessageInfo(object): """ ULog info message representation """ def __init__(self, data, header, is_info_multiple=False): if is_info_multiple: # INFO_MULTIPLE message self.is_continued, = struct.unpack('<B', data[0:1]) data = data[1:] key_len, = struct.unpack('<B', data[0:1]) type_key = _parse_string(data[1:1+key_len]) type_key_split = type_key.split(' ') self.type = type_key_split[0] self.key = type_key_split[1] if self.type.startswith('char['): # it's a string self.value = _parse_string(data[1+key_len:]) elif self.type in ULog._UNPACK_TYPES: unpack_type = ULog._UNPACK_TYPES[self.type] self.value, = struct.unpack('<'+unpack_type[0], data[1+key_len:]) else: # probably an array (or non-basic type) self.value = data[1+key_len:] class _MessageFlagBits(object): """ ULog message flag bits """ def __init__(self, data, header): if header.msg_size > 8 + 8 + 3*8: # we can still parse it but might miss some information print('Warning: Flags Bit message is longer than expected') self.compat_flags = list(struct.unpack('<'+'B'*8, data[0:8])) self.incompat_flags = list(struct.unpack('<'+'B'*8, data[8:16])) self.appended_offsets = list(struct.unpack('<'+'Q'*3, data[16:16+3*8])) # remove the 0's at the end while len(self.appended_offsets) > 0 and self.appended_offsets[-1] == 0: self.appended_offsets.pop() class MessageFormat(object): """ ULog message format representation """ def __init__(self, data, header): format_arr = _parse_string(data).split(':') self.name = format_arr[0] types_str = format_arr[1].split(';') self.fields = [] # list of tuples (type, array_size, name) for t in types_str: if len(t) > 0: self.fields.append(self._extract_type(t)) @staticmethod def _extract_type(field_str): field_str_split = field_str.split(' ') type_str = field_str_split[0] name_str = field_str_split[1] a_pos = type_str.find('[') if a_pos == -1: array_size = 1 type_name = type_str else: b_pos = type_str.find(']') array_size = int(type_str[a_pos+1:b_pos]) type_name = type_str[:a_pos] return type_name, array_size, name_str class MessageLogging(object): """ ULog logged string message representation """ def __init__(self, data, header): self.log_level, = struct.unpack('<B', data[0:1]) self.timestamp, = struct.unpack('<Q', data[1:9]) self.message = _parse_string(data[9:]) def log_level_str(self): return {ord('0'): 'EMERGENCY', ord('1'): 'ALERT', ord('2'): 'CRITICAL', ord('3'): 'ERROR', ord('4'): 'WARNING', ord('5'): 'NOTICE', ord('6'): 'INFO', ord('7'): 'DEBUG'}.get(self.log_level, 'UNKNOWN') class MessageDropout(object): """ ULog dropout message representation """ def __init__(self, data, header, timestamp): self.duration, = struct.unpack('<H', data) self.timestamp = timestamp class _FieldData(object): """ Type and name of a single ULog data field """ def __init__(self, field_name, type_str): self.field_name = field_name self.type_str = type_str class _MessageAddLogged(object): """ ULog add logging data message representation """ def __init__(self, data, header, message_formats): self.multi_id, = struct.unpack('<B', data[0:1]) self.msg_id, = struct.unpack('<H', data[1:3]) self.message_name = _parse_string(data[3:]) self.field_data = [] # list of _FieldData self.timestamp_idx = -1 self._parse_format(message_formats) self.timestamp_offset = 0 for field in self.field_data: if field.field_name == 'timestamp': break self.timestamp_offset += ULog._UNPACK_TYPES[field.type_str][1] self.buffer = bytearray() # accumulate all message data here # construct types for numpy dtype_list = [] for field in self.field_data: numpy_type = ULog._UNPACK_TYPES[field.type_str][2] dtype_list.append((field.field_name, numpy_type)) self.dtype = np.dtype(dtype_list).newbyteorder('<') def _parse_format(self, message_formats): self._parse_nested_type('', self.message_name, message_formats) # remove padding fields at the end while (len(self.field_data) > 0 and self.field_data[-1].field_name.startswith('_padding')): self.field_data.pop() def _parse_nested_type(self, prefix_str, type_name, message_formats): # we flatten nested types message_format = message_formats[type_name] for (type_name_fmt, array_size, field_name) in message_format.fields: if type_name_fmt in ULog._UNPACK_TYPES: if array_size > 1: for i in range(array_size): self.field_data.append(ULog._FieldData( prefix_str+field_name+'['+str(i)+']', type_name_fmt)) else: self.field_data.append(ULog._FieldData( prefix_str+field_name, type_name_fmt)) if prefix_str+field_name == 'timestamp': self.timestamp_idx = len(self.field_data) - 1 else: # nested type if array_size > 1: for i in range(array_size): self._parse_nested_type(prefix_str+field_name+'['+str(i)+'].', type_name_fmt, message_formats) else: self._parse_nested_type(prefix_str+field_name+'.', type_name_fmt, message_formats) class _MessageData(object): def __init__(self): self.timestamp = 0 def initialize(self, data, header, subscriptions, ulog_object): msg_id, = ULog._unpack_ushort(data[:2]) if msg_id in subscriptions: subscription = subscriptions[msg_id] # accumulate data to a buffer, will be parsed later subscription.buffer += data[2:] t_off = subscription.timestamp_offset # TODO: the timestamp can have another size than uint64 self.timestamp, = ULog._unpack_uint64(data[t_off+2:t_off+10]) else: if not msg_id in ulog_object._filtered_message_ids: # this is an error, but make it non-fatal if not msg_id in ulog_object._missing_message_ids: ulog_object._missing_message_ids.add(msg_id) if ulog_object._debug: print(ulog_object._file_handle.tell()) print('Warning: no subscription found for message id {:}. Continuing,' ' but file is most likely corrupt'.format(msg_id)) self.timestamp = 0 def _add_message_info_multiple(self, msg_info): """ add a message info multiple to self._msg_info_multiple_dict """ if msg_info.key in self._msg_info_multiple_dict: if msg_info.is_continued: self._msg_info_multiple_dict[msg_info.key][-1].append(msg_info.value) else: self._msg_info_multiple_dict[msg_info.key].append([msg_info.value]) else: self._msg_info_multiple_dict[msg_info.key] = [[msg_info.value]] def _read_file_header(self): header_data = self._file_handle.read(16) if len(header_data) != 16: raise Exception("Invalid file format (Header too short)") if header_data[:7] != self.HEADER_BYTES: raise Exception("Invalid file format (Failed to parse header)") self._file_version, = struct.unpack('B', header_data[7:8]) if self._file_version > 1: print("Warning: unknown file version. Will attempt to read it anyway") # read timestamp self._start_timestamp, = ULog._unpack_uint64(header_data[8:]) def _read_file_definitions(self): header = self._MessageHeader() while True: data = self._file_handle.read(3) if not data: break header.initialize(data) data = self._file_handle.read(header.msg_size) if header.msg_type == self.MSG_TYPE_INFO: msg_info = self._MessageInfo(data, header) self._msg_info_dict[msg_info.key] = msg_info.value elif header.msg_type == self.MSG_TYPE_INFO_MULTIPLE: msg_info = self._MessageInfo(data, header, is_info_multiple=True) self._add_message_info_multiple(msg_info) elif header.msg_type == self.MSG_TYPE_FORMAT: msg_format = self.MessageFormat(data, header) self._message_formats[msg_format.name] = msg_format elif header.msg_type == self.MSG_TYPE_PARAMETER: msg_info = self._MessageInfo(data, header) self._initial_parameters[msg_info.key] = msg_info.value elif (header.msg_type == self.MSG_TYPE_ADD_LOGGED_MSG or header.msg_type == self.MSG_TYPE_LOGGING): self._file_handle.seek(-(3+header.msg_size), 1) break # end of section elif header.msg_type == self.MSG_TYPE_FLAG_BITS: # make sure this is the first message in the log if self._file_handle.tell() != 16 + 3 + header.msg_size: print('Error: FLAGS_BITS message must be first message. Offset:', self._file_handle.tell()) msg_flag_bits = self._MessageFlagBits(data, header) self._compat_flags = msg_flag_bits.compat_flags self._incompat_flags = msg_flag_bits.incompat_flags self._appended_offsets = msg_flag_bits.appended_offsets if self._debug: print('compat flags: ', self._compat_flags) print('incompat flags:', self._incompat_flags) print('appended offsets:', self._appended_offsets) # check if there are bits set that we don't know unknown_incompat_flag_msg = "Unknown incompatible flag set: cannot parse the log" if self._incompat_flags[0] & ~1: raise Exception(unknown_incompat_flag_msg) for i in range(1, 8): if self._incompat_flags[i]: raise Exception(unknown_incompat_flag_msg) else: if self._debug: print('read_file_definitions: unknown message type: %i (%s)' % (header.msg_type, chr(header.msg_type))) file_position = self._file_handle.tell() print('file position: %i (0x%x) msg size: %i' % ( file_position, file_position, header.msg_size)) if self._check_file_corruption(header): # seek back to advance only by a single byte instead of # skipping the message self._file_handle.seek(-2-header.msg_size, 1) def _read_file_data(self, message_name_filter_list, read_until=None): """ read the file data section :param read_until: an optional file offset: if set, parse only up to this offset (smaller than) """ if read_until is None: read_until = 1 << 50 # make it larger than any possible log file try: # pre-init reusable objects header = self._MessageHeader() msg_data = self._MessageData() while True: data = self._file_handle.read(3) header.initialize(data) data = self._file_handle.read(header.msg_size) if len(data) < header.msg_size: break # less data than expected. File is most likely cut if self._file_handle.tell() > read_until: if self._debug: print('read until offset=%i done, current pos=%i' % (read_until, self._file_handle.tell())) break if header.msg_type == self.MSG_TYPE_INFO: msg_info = self._MessageInfo(data, header) self._msg_info_dict[msg_info.key] = msg_info.value elif header.msg_type == self.MSG_TYPE_INFO_MULTIPLE: msg_info = self._MessageInfo(data, header, is_info_multiple=True) self._add_message_info_multiple(msg_info) elif header.msg_type == self.MSG_TYPE_PARAMETER: msg_info = self._MessageInfo(data, header) self._changed_parameters.append((self._last_timestamp, msg_info.key, msg_info.value)) elif header.msg_type == self.MSG_TYPE_ADD_LOGGED_MSG: msg_add_logged = self._MessageAddLogged(data, header, self._message_formats) if (message_name_filter_list is None or msg_add_logged.message_name in message_name_filter_list): self._subscriptions[msg_add_logged.msg_id] = msg_add_logged else: self._filtered_message_ids.add(msg_add_logged.msg_id) elif header.msg_type == self.MSG_TYPE_LOGGING: msg_logging = self.MessageLogging(data, header) self._logged_messages.append(msg_logging) elif header.msg_type == self.MSG_TYPE_DATA: msg_data.initialize(data, header, self._subscriptions, self) if msg_data.timestamp != 0 and msg_data.timestamp > self._last_timestamp: self._last_timestamp = msg_data.timestamp elif header.msg_type == self.MSG_TYPE_DROPOUT: msg_dropout = self.MessageDropout(data, header, self._last_timestamp) self._dropouts.append(msg_dropout) else: if self._debug: print('_read_file_data: unknown message type: %i (%s)' % (header.msg_type, chr(header.msg_type))) file_position = self._file_handle.tell() print('file position: %i (0x%x) msg size: %i' % ( file_position, file_position, header.msg_size)) if self._check_file_corruption(header): # seek back to advance only by a single byte instead of # skipping the message self._file_handle.seek(-2-header.msg_size, 1) except struct.error: pass #we read past the end of the file # convert into final representation while self._subscriptions: _, value = self._subscriptions.popitem() if len(value.buffer) > 0: # only add if we have data data_item = ULog.Data(value) self._data_list.append(data_item) def _check_file_corruption(self, header): """ check for file corruption based on an unknown message type in the header """ # We need to handle 2 cases: # - corrupt file (we do our best to read the rest of the file) # - new ULog message type got added (we just want to skip the message) if header.msg_type == 0 or header.msg_size == 0 or header.msg_size > 10000: if not self._file_corrupt and self._debug: print('File corruption detected') self._file_corrupt = True return self._file_corrupt def get_version_info(self, key_name='ver_sw_release'): """ get the (major, minor, patch, type) version information as tuple. Returns None if not found definition of type is: >= 0: development >= 64: alpha version >= 128: beta version >= 192: RC version == 255: release version """ if key_name in self._msg_info_dict: val = self._msg_info_dict[key_name] return ((val >> 24) & 0xff, (val >> 16) & 0xff, (val >> 8) & 0xff, val & 0xff) return None def get_version_info_str(self, key_name='ver_sw_release'): """ get version information in the form 'v1.2.3 (RC)', or None if version tag either not found or it's a development version """ version = self.get_version_info(key_name) if not version is None and version[3] >= 64: type_str = '' if version[3] < 128: type_str = ' (alpha)' elif version[3] < 192: type_str = ' (beta)' elif version[3] < 255: type_str = ' (RC)' return 'v{}.{}.{}{}'.format(version[0], version[1], version[2], type_str) return None
PX4/pyulog
pyulog/core.py
ULog._read_file_data
python
def _read_file_data(self, message_name_filter_list, read_until=None): if read_until is None: read_until = 1 << 50 # make it larger than any possible log file try: # pre-init reusable objects header = self._MessageHeader() msg_data = self._MessageData() while True: data = self._file_handle.read(3) header.initialize(data) data = self._file_handle.read(header.msg_size) if len(data) < header.msg_size: break # less data than expected. File is most likely cut if self._file_handle.tell() > read_until: if self._debug: print('read until offset=%i done, current pos=%i' % (read_until, self._file_handle.tell())) break if header.msg_type == self.MSG_TYPE_INFO: msg_info = self._MessageInfo(data, header) self._msg_info_dict[msg_info.key] = msg_info.value elif header.msg_type == self.MSG_TYPE_INFO_MULTIPLE: msg_info = self._MessageInfo(data, header, is_info_multiple=True) self._add_message_info_multiple(msg_info) elif header.msg_type == self.MSG_TYPE_PARAMETER: msg_info = self._MessageInfo(data, header) self._changed_parameters.append((self._last_timestamp, msg_info.key, msg_info.value)) elif header.msg_type == self.MSG_TYPE_ADD_LOGGED_MSG: msg_add_logged = self._MessageAddLogged(data, header, self._message_formats) if (message_name_filter_list is None or msg_add_logged.message_name in message_name_filter_list): self._subscriptions[msg_add_logged.msg_id] = msg_add_logged else: self._filtered_message_ids.add(msg_add_logged.msg_id) elif header.msg_type == self.MSG_TYPE_LOGGING: msg_logging = self.MessageLogging(data, header) self._logged_messages.append(msg_logging) elif header.msg_type == self.MSG_TYPE_DATA: msg_data.initialize(data, header, self._subscriptions, self) if msg_data.timestamp != 0 and msg_data.timestamp > self._last_timestamp: self._last_timestamp = msg_data.timestamp elif header.msg_type == self.MSG_TYPE_DROPOUT: msg_dropout = self.MessageDropout(data, header, self._last_timestamp) self._dropouts.append(msg_dropout) else: if self._debug: print('_read_file_data: unknown message type: %i (%s)' % (header.msg_type, chr(header.msg_type))) file_position = self._file_handle.tell() print('file position: %i (0x%x) msg size: %i' % ( file_position, file_position, header.msg_size)) if self._check_file_corruption(header): # seek back to advance only by a single byte instead of # skipping the message self._file_handle.seek(-2-header.msg_size, 1) except struct.error: pass #we read past the end of the file # convert into final representation while self._subscriptions: _, value = self._subscriptions.popitem() if len(value.buffer) > 0: # only add if we have data data_item = ULog.Data(value) self._data_list.append(data_item)
read the file data section :param read_until: an optional file offset: if set, parse only up to this offset (smaller than)
train
https://github.com/PX4/pyulog/blob/3bc4f9338d30e2e0a0dfbed58f54d200967e5056/pyulog/core.py#L522-L600
null
class ULog(object): """ This class parses an ulog file """ ## constants ## HEADER_BYTES = b'\x55\x4c\x6f\x67\x01\x12\x35' # message types MSG_TYPE_FORMAT = ord('F') MSG_TYPE_DATA = ord('D') MSG_TYPE_INFO = ord('I') MSG_TYPE_INFO_MULTIPLE = ord('M') MSG_TYPE_PARAMETER = ord('P') MSG_TYPE_ADD_LOGGED_MSG = ord('A') MSG_TYPE_REMOVE_LOGGED_MSG = ord('R') MSG_TYPE_SYNC = ord('S') MSG_TYPE_DROPOUT = ord('O') MSG_TYPE_LOGGING = ord('L') MSG_TYPE_FLAG_BITS = ord('B') _UNPACK_TYPES = { 'int8_t': ['b', 1, np.int8], 'uint8_t': ['B', 1, np.uint8], 'int16_t': ['h', 2, np.int16], 'uint16_t': ['H', 2, np.uint16], 'int32_t': ['i', 4, np.int32], 'uint32_t': ['I', 4, np.uint32], 'int64_t': ['q', 8, np.int64], 'uint64_t': ['Q', 8, np.uint64], 'float': ['f', 4, np.float32], 'double': ['d', 8, np.float64], 'bool': ['?', 1, np.int8], 'char': ['c', 1, np.int8] } @staticmethod def get_field_size(type_str): """ get the field size in bytes. :param type_str: type string, eg. 'int8_t' """ return ULog._UNPACK_TYPES[type_str][1] # pre-init unpack structs for quicker use _unpack_ushort_byte = struct.Struct('<HB').unpack _unpack_ushort = struct.Struct('<H').unpack _unpack_uint64 = struct.Struct('<Q').unpack def __init__(self, log_file, message_name_filter_list=None): """ Initialize the object & load the file. :param log_file: a file name (str) or a readable file object :param message_name_filter_list: list of strings, to only load messages with the given names. If None, load everything. """ self._debug = False self._file_corrupt = False self._start_timestamp = 0 self._last_timestamp = 0 self._msg_info_dict = {} self._msg_info_multiple_dict = {} self._initial_parameters = {} self._changed_parameters = [] self._message_formats = {} self._logged_messages = [] self._dropouts = [] self._data_list = [] self._subscriptions = {} # dict of key=msg_id, value=_MessageAddLogged self._filtered_message_ids = set() # _MessageAddLogged id's that are filtered self._missing_message_ids = set() # _MessageAddLogged id's that could not be found self._file_version = 0 self._compat_flags = [0] * 8 self._incompat_flags = [0] * 8 self._appended_offsets = [] # file offsets for appended data self._load_file(log_file, message_name_filter_list) ## parsed data @property def start_timestamp(self): """ timestamp of file start """ return self._start_timestamp @property def last_timestamp(self): """ timestamp of last message """ return self._last_timestamp @property def msg_info_dict(self): """ dictionary of all information messages (key is a string, value depends on the type, usually string or int) """ return self._msg_info_dict @property def msg_info_multiple_dict(self): """ dictionary of all information multiple messages (key is a string, value is a list of lists that contains the messages) """ return self._msg_info_multiple_dict @property def initial_parameters(self): """ dictionary of all initially set parameters (key=param name) """ return self._initial_parameters @property def changed_parameters(self): """ list of all changed parameters (tuple of (timestamp, name, value))""" return self._changed_parameters @property def message_formats(self): """ dictionary with key = format name (MessageFormat.name), value = MessageFormat object """ return self._message_formats @property def logged_messages(self): """ list of MessageLogging objects """ return self._logged_messages @property def dropouts(self): """ list of MessageDropout objects """ return self._dropouts @property def data_list(self): """ extracted data: list of Data objects """ return self._data_list @property def has_data_appended(self): """ returns True if the log has data appended, False otherwise """ return self._incompat_flags[0] & 0x1 @property def file_corruption(self): """ True if a file corruption got detected """ return self._file_corrupt def get_dataset(self, name, multi_instance=0): """ get a specific dataset. example: try: gyro_data = ulog.get_dataset('sensor_gyro') except (KeyError, IndexError, ValueError) as error: print(type(error), "(sensor_gyro):", error) :param name: name of the dataset :param multi_instance: the multi_id, defaults to the first :raises KeyError, IndexError, ValueError: if name or instance not found """ return [elem for elem in self._data_list if elem.name == name and elem.multi_id == multi_instance][0] class Data(object): """ contains the final topic data for a single topic and instance """ def __init__(self, message_add_logged_obj): self.multi_id = message_add_logged_obj.multi_id self.name = message_add_logged_obj.message_name self.field_data = message_add_logged_obj.field_data self.timestamp_idx = message_add_logged_obj.timestamp_idx # get data as numpy.ndarray np_array = np.frombuffer(message_add_logged_obj.buffer, dtype=message_add_logged_obj.dtype) # convert into dict of np.array (which is easier to handle) self.data = {} for name in np_array.dtype.names: self.data[name] = np_array[name] def list_value_changes(self, field_name): """ get a list of (timestamp, value) tuples, whenever the value changes. The first data point with non-zero timestamp is always included, messages with timestamp = 0 are ignored """ t = self.data['timestamp'] x = self.data[field_name] indices = t != 0 # filter out 0 values t = t[indices] x = x[indices] if len(t) == 0: return [] ret = [(t[0], x[0])] indices = np.where(x[:-1] != x[1:])[0] + 1 ret.extend(zip(t[indices], x[indices])) return ret ## Representations of the messages from the log file ## class _MessageHeader(object): """ 3 bytes ULog message header """ def __init__(self): self.msg_size = 0 self.msg_type = 0 def initialize(self, data): self.msg_size, self.msg_type = ULog._unpack_ushort_byte(data) class _MessageInfo(object): """ ULog info message representation """ def __init__(self, data, header, is_info_multiple=False): if is_info_multiple: # INFO_MULTIPLE message self.is_continued, = struct.unpack('<B', data[0:1]) data = data[1:] key_len, = struct.unpack('<B', data[0:1]) type_key = _parse_string(data[1:1+key_len]) type_key_split = type_key.split(' ') self.type = type_key_split[0] self.key = type_key_split[1] if self.type.startswith('char['): # it's a string self.value = _parse_string(data[1+key_len:]) elif self.type in ULog._UNPACK_TYPES: unpack_type = ULog._UNPACK_TYPES[self.type] self.value, = struct.unpack('<'+unpack_type[0], data[1+key_len:]) else: # probably an array (or non-basic type) self.value = data[1+key_len:] class _MessageFlagBits(object): """ ULog message flag bits """ def __init__(self, data, header): if header.msg_size > 8 + 8 + 3*8: # we can still parse it but might miss some information print('Warning: Flags Bit message is longer than expected') self.compat_flags = list(struct.unpack('<'+'B'*8, data[0:8])) self.incompat_flags = list(struct.unpack('<'+'B'*8, data[8:16])) self.appended_offsets = list(struct.unpack('<'+'Q'*3, data[16:16+3*8])) # remove the 0's at the end while len(self.appended_offsets) > 0 and self.appended_offsets[-1] == 0: self.appended_offsets.pop() class MessageFormat(object): """ ULog message format representation """ def __init__(self, data, header): format_arr = _parse_string(data).split(':') self.name = format_arr[0] types_str = format_arr[1].split(';') self.fields = [] # list of tuples (type, array_size, name) for t in types_str: if len(t) > 0: self.fields.append(self._extract_type(t)) @staticmethod def _extract_type(field_str): field_str_split = field_str.split(' ') type_str = field_str_split[0] name_str = field_str_split[1] a_pos = type_str.find('[') if a_pos == -1: array_size = 1 type_name = type_str else: b_pos = type_str.find(']') array_size = int(type_str[a_pos+1:b_pos]) type_name = type_str[:a_pos] return type_name, array_size, name_str class MessageLogging(object): """ ULog logged string message representation """ def __init__(self, data, header): self.log_level, = struct.unpack('<B', data[0:1]) self.timestamp, = struct.unpack('<Q', data[1:9]) self.message = _parse_string(data[9:]) def log_level_str(self): return {ord('0'): 'EMERGENCY', ord('1'): 'ALERT', ord('2'): 'CRITICAL', ord('3'): 'ERROR', ord('4'): 'WARNING', ord('5'): 'NOTICE', ord('6'): 'INFO', ord('7'): 'DEBUG'}.get(self.log_level, 'UNKNOWN') class MessageDropout(object): """ ULog dropout message representation """ def __init__(self, data, header, timestamp): self.duration, = struct.unpack('<H', data) self.timestamp = timestamp class _FieldData(object): """ Type and name of a single ULog data field """ def __init__(self, field_name, type_str): self.field_name = field_name self.type_str = type_str class _MessageAddLogged(object): """ ULog add logging data message representation """ def __init__(self, data, header, message_formats): self.multi_id, = struct.unpack('<B', data[0:1]) self.msg_id, = struct.unpack('<H', data[1:3]) self.message_name = _parse_string(data[3:]) self.field_data = [] # list of _FieldData self.timestamp_idx = -1 self._parse_format(message_formats) self.timestamp_offset = 0 for field in self.field_data: if field.field_name == 'timestamp': break self.timestamp_offset += ULog._UNPACK_TYPES[field.type_str][1] self.buffer = bytearray() # accumulate all message data here # construct types for numpy dtype_list = [] for field in self.field_data: numpy_type = ULog._UNPACK_TYPES[field.type_str][2] dtype_list.append((field.field_name, numpy_type)) self.dtype = np.dtype(dtype_list).newbyteorder('<') def _parse_format(self, message_formats): self._parse_nested_type('', self.message_name, message_formats) # remove padding fields at the end while (len(self.field_data) > 0 and self.field_data[-1].field_name.startswith('_padding')): self.field_data.pop() def _parse_nested_type(self, prefix_str, type_name, message_formats): # we flatten nested types message_format = message_formats[type_name] for (type_name_fmt, array_size, field_name) in message_format.fields: if type_name_fmt in ULog._UNPACK_TYPES: if array_size > 1: for i in range(array_size): self.field_data.append(ULog._FieldData( prefix_str+field_name+'['+str(i)+']', type_name_fmt)) else: self.field_data.append(ULog._FieldData( prefix_str+field_name, type_name_fmt)) if prefix_str+field_name == 'timestamp': self.timestamp_idx = len(self.field_data) - 1 else: # nested type if array_size > 1: for i in range(array_size): self._parse_nested_type(prefix_str+field_name+'['+str(i)+'].', type_name_fmt, message_formats) else: self._parse_nested_type(prefix_str+field_name+'.', type_name_fmt, message_formats) class _MessageData(object): def __init__(self): self.timestamp = 0 def initialize(self, data, header, subscriptions, ulog_object): msg_id, = ULog._unpack_ushort(data[:2]) if msg_id in subscriptions: subscription = subscriptions[msg_id] # accumulate data to a buffer, will be parsed later subscription.buffer += data[2:] t_off = subscription.timestamp_offset # TODO: the timestamp can have another size than uint64 self.timestamp, = ULog._unpack_uint64(data[t_off+2:t_off+10]) else: if not msg_id in ulog_object._filtered_message_ids: # this is an error, but make it non-fatal if not msg_id in ulog_object._missing_message_ids: ulog_object._missing_message_ids.add(msg_id) if ulog_object._debug: print(ulog_object._file_handle.tell()) print('Warning: no subscription found for message id {:}. Continuing,' ' but file is most likely corrupt'.format(msg_id)) self.timestamp = 0 def _add_message_info_multiple(self, msg_info): """ add a message info multiple to self._msg_info_multiple_dict """ if msg_info.key in self._msg_info_multiple_dict: if msg_info.is_continued: self._msg_info_multiple_dict[msg_info.key][-1].append(msg_info.value) else: self._msg_info_multiple_dict[msg_info.key].append([msg_info.value]) else: self._msg_info_multiple_dict[msg_info.key] = [[msg_info.value]] def _load_file(self, log_file, message_name_filter_list): """ load and parse an ULog file into memory """ if isinstance(log_file, str): self._file_handle = open(log_file, "rb") else: self._file_handle = log_file # parse the whole file self._read_file_header() self._last_timestamp = self._start_timestamp self._read_file_definitions() if self.has_data_appended and len(self._appended_offsets) > 0: if self._debug: print('This file has data appended') for offset in self._appended_offsets: self._read_file_data(message_name_filter_list, read_until=offset) self._file_handle.seek(offset) # read the whole file, or the rest if data appended self._read_file_data(message_name_filter_list) self._file_handle.close() del self._file_handle def _read_file_header(self): header_data = self._file_handle.read(16) if len(header_data) != 16: raise Exception("Invalid file format (Header too short)") if header_data[:7] != self.HEADER_BYTES: raise Exception("Invalid file format (Failed to parse header)") self._file_version, = struct.unpack('B', header_data[7:8]) if self._file_version > 1: print("Warning: unknown file version. Will attempt to read it anyway") # read timestamp self._start_timestamp, = ULog._unpack_uint64(header_data[8:]) def _read_file_definitions(self): header = self._MessageHeader() while True: data = self._file_handle.read(3) if not data: break header.initialize(data) data = self._file_handle.read(header.msg_size) if header.msg_type == self.MSG_TYPE_INFO: msg_info = self._MessageInfo(data, header) self._msg_info_dict[msg_info.key] = msg_info.value elif header.msg_type == self.MSG_TYPE_INFO_MULTIPLE: msg_info = self._MessageInfo(data, header, is_info_multiple=True) self._add_message_info_multiple(msg_info) elif header.msg_type == self.MSG_TYPE_FORMAT: msg_format = self.MessageFormat(data, header) self._message_formats[msg_format.name] = msg_format elif header.msg_type == self.MSG_TYPE_PARAMETER: msg_info = self._MessageInfo(data, header) self._initial_parameters[msg_info.key] = msg_info.value elif (header.msg_type == self.MSG_TYPE_ADD_LOGGED_MSG or header.msg_type == self.MSG_TYPE_LOGGING): self._file_handle.seek(-(3+header.msg_size), 1) break # end of section elif header.msg_type == self.MSG_TYPE_FLAG_BITS: # make sure this is the first message in the log if self._file_handle.tell() != 16 + 3 + header.msg_size: print('Error: FLAGS_BITS message must be first message. Offset:', self._file_handle.tell()) msg_flag_bits = self._MessageFlagBits(data, header) self._compat_flags = msg_flag_bits.compat_flags self._incompat_flags = msg_flag_bits.incompat_flags self._appended_offsets = msg_flag_bits.appended_offsets if self._debug: print('compat flags: ', self._compat_flags) print('incompat flags:', self._incompat_flags) print('appended offsets:', self._appended_offsets) # check if there are bits set that we don't know unknown_incompat_flag_msg = "Unknown incompatible flag set: cannot parse the log" if self._incompat_flags[0] & ~1: raise Exception(unknown_incompat_flag_msg) for i in range(1, 8): if self._incompat_flags[i]: raise Exception(unknown_incompat_flag_msg) else: if self._debug: print('read_file_definitions: unknown message type: %i (%s)' % (header.msg_type, chr(header.msg_type))) file_position = self._file_handle.tell() print('file position: %i (0x%x) msg size: %i' % ( file_position, file_position, header.msg_size)) if self._check_file_corruption(header): # seek back to advance only by a single byte instead of # skipping the message self._file_handle.seek(-2-header.msg_size, 1) def _check_file_corruption(self, header): """ check for file corruption based on an unknown message type in the header """ # We need to handle 2 cases: # - corrupt file (we do our best to read the rest of the file) # - new ULog message type got added (we just want to skip the message) if header.msg_type == 0 or header.msg_size == 0 or header.msg_size > 10000: if not self._file_corrupt and self._debug: print('File corruption detected') self._file_corrupt = True return self._file_corrupt def get_version_info(self, key_name='ver_sw_release'): """ get the (major, minor, patch, type) version information as tuple. Returns None if not found definition of type is: >= 0: development >= 64: alpha version >= 128: beta version >= 192: RC version == 255: release version """ if key_name in self._msg_info_dict: val = self._msg_info_dict[key_name] return ((val >> 24) & 0xff, (val >> 16) & 0xff, (val >> 8) & 0xff, val & 0xff) return None def get_version_info_str(self, key_name='ver_sw_release'): """ get version information in the form 'v1.2.3 (RC)', or None if version tag either not found or it's a development version """ version = self.get_version_info(key_name) if not version is None and version[3] >= 64: type_str = '' if version[3] < 128: type_str = ' (alpha)' elif version[3] < 192: type_str = ' (beta)' elif version[3] < 255: type_str = ' (RC)' return 'v{}.{}.{}{}'.format(version[0], version[1], version[2], type_str) return None