diff --git a/.ci/retrofit-worktree.sh b/.ci/retrofit-worktree.sh index f926e59059e..b9c880a839f 100755 --- a/.ci/retrofit-worktree.sh +++ b/.ci/retrofit-worktree.sh @@ -12,6 +12,10 @@ export GIT_AUTHOR_EMAIL="ci-sage@example.com" export GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME" export GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL" +# Set globally for other parts of the workflow +git config --global user.name "$GIT_AUTHOR_NAME" +git config --global user.email "$GIT_AUTHOR_EMAIL" + set -ex # If actions/checkout downloaded our source tree using the GitHub REST API diff --git a/.github/sync_labels.py b/.github/sync_labels.py index 799b4985c5d..97ddf039a16 100755 --- a/.github/sync_labels.py +++ b/.github/sync_labels.py @@ -25,6 +25,7 @@ from subprocess import check_output, CalledProcessError datetime_format = '%Y-%m-%dT%H:%M:%SZ' +default_bot = 'github-actions' class Action(Enum): @@ -42,21 +43,41 @@ class Action(Enum): converted_to_draft = 'converted_to_draft' submitted = 'submitted' -class RevState(Enum): +class AuthorAssociation(Enum): r""" - Enum for GitHub event ``review_state``. + Enum for GitHub ``authorAssociation``. """ - commented = 'commented' - approved = 'approved' - changes_requested = 'changes_requested' + def is_valid(self): + r""" + Return whether ``self`` has valid permissions. + """ + c = self.__class__ + return self in [c.collaborator, c.member, c.owner] + + collaborator = 'COLLABORATOR' # Author has been invited to collaborate on the repository. + contributor = 'CONTRIBUTOR' # Author has previously committed to the repository. + first_timer = 'FIRST_TIMER' # Author has not previously committed to GitHub. + first_time_contributor = 'FIRST_TIME_CONTRIBUTOR' # Author has not previously committed to the repository. + mannequin = 'MANNEQUIN' # Author is a placeholder for an unclaimed user. + member = 'MEMBER' # Author is a member of the organization that owns the repository. + none = 'NONE' # Author has no association with the repository. + owner = 'OWNER' # Author is the owner of the repository. -class ReviewDecision(Enum): +class RevState(Enum): r""" - Enum for ``gh pr view`` results for ``reviewDecision``. + Enum for GitHub event ``review_state``. """ + def is_proper(self): + r""" + Return whether ``self`` is a proper review state. + """ + c = self.__class__ + return self in [c.changes_requested, c.approved] + + commented = 'COMMENTED' changes_requested = 'CHANGES_REQUESTED' approved = 'APPROVED' - unclear = 'UNCLEAR' + dismissed = 'DISMISSED' class Priority(Enum): r""" @@ -68,9 +89,9 @@ class Priority(Enum): minor = 'p: minor /4' trivial = 'p: trivial /5' -class State(Enum): +class Status(Enum): r""" - Enum for state labels. + Enum for status labels. """ positive_review = 's: positive review' needs_work = 's: needs work' @@ -90,7 +111,7 @@ def selection_list(label): r""" Return the selection list to which ``label`` belongs to. """ - for sel_list in [Priority, State, Resolution]: + for sel_list in [Priority, Status, Resolution]: for item in sel_list: if label == item.value: return sel_list @@ -108,22 +129,32 @@ def __init__(self, url, actor): self._url = url self._actor = actor self._warning_prefix = 'Label Sync Warning:' + self._hint_prefix = 'Label Sync Hint:' self._labels = None self._author = None self._draft = None self._open = None self._review_decision = None self._reviews = None + self._reviews_from_rest_api = None + self._review_requests = None self._commits = None self._commit_date = None + self._bot_login = None + + s = url.split('/') + self._owner = s[3] + self._repo = s[4] + self._number = os.path.basename(url) - number = os.path.basename(url) self._pr = True - self._issue = 'pull request #%s' % number + self._issue = 'pull request #%s' % self._number if url.rfind('issue') != -1: - self._issue = 'issue #%s' % number + self._issue = 'issue #%s' % self._number self._pr = False info('Create label handler for %s and actor %s' % (self._issue, self._actor)) + + self.bot_login() self.clean_warnings() # ------------------------------------------------------------------------- @@ -198,6 +229,30 @@ def is_draft(self): info('Issue %s is draft %s' % (self._issue, self._draft)) return self._draft + def bot_login(self): + r""" + Return the login name of the bot. + """ + if self._bot_login: + return self._bot_login + cmd = 'gh auth status' + from subprocess import run + capt = run(cmd, shell=True, capture_output=True) + l = str(capt.stderr).split() + if not 'as' in l: + l = str(capt.stdout).split() + self._bot_login = l[l.index('as')+1] + if self._bot_login.endswith('[bot]'): + self._bot_login = self._bot_login.split('[bot]')[0] + info('Bot is %s' % self._bot_login) + return self._bot_login + + def is_this_bot(self, login): + r""" + Check whether login is the bot itself. + """ + return login.startswith(self.bot_login()) + def is_auth_team_member(self, login): r""" Return ``True`` if the user with given login belongs to an authorized @@ -224,9 +279,43 @@ def verify_membership(team): def actor_authorized(self): r""" - Return ``True`` if the actor belongs to an authorized team. + Return ``True`` if the actor has sufficient permissions. + """ + if self.is_this_bot(default_bot): + # since the default bot is not a member of the SageMath + # organization it cannot test membership for private members. + # Therefore, we check here for public organization membership. + rev = self.get_latest_review() + if not rev: + return False + + if rev['author']['login'] == self._actor: + ass = rev['authorAssociation'] + info('Actor %s has association %s' % (self._actor, ass)) + return AuthorAssociation(ass).is_valid() + info('Actor %s did not create latest review' % self._actor) + return False + else: + return self.is_auth_team_member(self._actor) + + def query_multi_pages(self, path_args, since=None): + r""" + Query data from REST api from multiple pages. """ - return self.is_auth_team_member(self._actor) + per_page = 100 + if since: + query = '-f per_page=%s -f page={} -f since=%s' % (per_page, since.strftime(datetime_format)) + else: + query = '-f per_page=%s -f page={}' % per_page + page = 1 + results = [] + while True: + results_page = self.rest_api(path_args, query=query.format(page)) + results += results_page + if len(results_page) < per_page: + break + page += 1 + return results def clean_warnings(self): r""" @@ -235,22 +324,10 @@ def clean_warnings(self): """ warning_lifetime = timedelta(minutes=5) time_frame = timedelta(minutes=730) # timedelta to search for comments including 10 minutes overlap with cron-cycle - per_page = 100 today = datetime.today() since = today - time_frame - query = '-F per_page=%s -F page={} -f since=%s' % (per_page, since.strftime(datetime_format)) - s = self._url.split('/') - owner = s[3] - repo = s[4] - path_args = '/repos/%s/%s/issues/comments' % (owner, repo) - page = 1 - comments = [] - while True: - comments_page = self.rest_api(path_args, query=query.format(page)) - comments += comments_page - if len(comments_page) < per_page: - break - page += 1 + path_args = '/repos/%s/%s/issues/comments' % (self._owner, self._repo) + comments = self.query_multi_pages(path_args, since=since) info('Cleaning warning comments since %s (total found %s)' % (since, len(comments))) @@ -260,12 +337,17 @@ def clean_warnings(self): comment_id = c['id'] issue = c['issue_url'].split('/').pop() created_at = c['created_at'] - if login.startswith('github-actions'): - debug('github-actions comment %s created at %s on issue %s found' % (comment_id, created_at, issue)) + if self.is_this_bot(login): + debug('%s comment %s created at %s on issue %s found' % (self.bot_login(), comment_id, created_at, issue)) + prefix = None if body.startswith(self._warning_prefix): + prefix = self._warning_prefix + if body.startswith(self._hint_prefix): + prefix = self._hint_prefix + if prefix: created = datetime.strptime(created_at, datetime_format) lifetime = today - created - debug('github-actions %s %s is %s old' % (self._warning_prefix, comment_id, lifetime)) + debug('%s %s %s is %s old' % (self.bot_login(), prefix, comment_id, lifetime)) if lifetime > warning_lifetime: try: self.rest_api('%s/%s' % (path_args, comment_id), method='DELETE') @@ -311,26 +393,18 @@ def get_commits(self): info('Commits until %s for %s: %s' % (self._commit_date, self._issue, self._commits)) return self._commits - def get_review_decision(self): + def get_review_requests(self): r""" - Return the reviewDecision of the PR. + Return the list of review request of the PR. """ if not self.is_pull_request(): return None - if self._review_decision is not None: - if self._review_decision == ReviewDecision.unclear: - return None - return self._review_decision + if self._review_requests is None: + self._review_requests = self.view('reviewRequests') + debug('Review requests for %s: %s' % (self._issue, self._review_requests)) - data = self.view('reviewDecision') - if data: - self._review_decision = ReviewDecision(data) - else: - # To separate a not supplied value from not cached (see https://github.com/sagemath/sage/pull/36177#issuecomment-1704022893 ff) - self._review_decision = ReviewDecision.unclear - info('Review decision for %s: %s' % (self._issue, self._review_decision.value)) - return self._review_decision + return self._review_requests def get_reviews(self, complete=False): r""" @@ -358,6 +432,28 @@ def get_reviews(self, complete=False): info('Proper reviews after %s for %s: %s' % (date, self._issue, proper_new_revs)) return proper_new_revs + def get_latest_review(self, complete=False): + r""" + Return the latest review of the PR. Per default only those proper reviews + are considered which have been submitted after the most recent commit. Use + keyword ``complete`` to get the latest of all. + """ + revs = self.get_reviews(complete=complete) + if not revs: + return + res = revs[0] + max_date = res['submittedAt'] + for rev in revs: + cur_date = rev['submittedAt'] + if cur_date > max_date: + max_date = cur_date + res = rev + fill_in = '' + if not complete: + fill_in = ' proper' + info('PR %s had latest%s review at %s: %s' % (self._issue, fill_in, max_date, res)) + return res + def active_partners(self, item): r""" Return the list of other labels from the selection list @@ -369,47 +465,60 @@ def active_partners(self, item): return partners # ------------------------------------------------------------------------- - # methods to validate the issue state + # methods to validate the issue status # ------------------------------------------------------------------------- - def review_comment_to_state(self): + def review_comment_to_status(self): r""" - Return a State label if the most recent review comment + Return a status label if the most recent review comment starts with its value. """ - revs = self.get_reviews(complete=True) - date = max(rev['submittedAt'] for rev in revs) - - for rev in revs: - if rev['submittedAt'] == date: - for stat in State: - body = rev['body'] - if body.startswith(stat.value): - return stat - return None - - def needs_work_valid(self): + rev = self.get_latest_review(complete=True) + ass = AuthorAssociation(rev['authorAssociation']) + for status in Status: + body = rev['body'] + if body.startswith(status.value): + info('Latest review comment contains status label %s' % status) + return status, ass + return None, ass + + def review_by_actor(self): r""" - Return ``True`` if the PR needs work. This is the case if - there are reviews more recent than any commit and the review - decision requests changes or if there is any review reqesting - changes. + Return ``True`` if the actor authored the latest review directly or indirectly. """ - revs = self.get_reviews() - if not revs: + rev = self.get_latest_review() + if not rev: # no proper review since most recent commit. return False + answer = False + auth = rev['author']['login'] + if self._actor == auth: + answer = True + if self.is_this_bot(auth): + if rev['body'].find(self._actor) > 0: + answer = True + if answer: + node_id = rev['id'] + info('Ignore actor\'s review %s' % node_id) + self.dismiss_bot_reviews('@%s reverted decision.' % self._actor, node_id=node_id) + return answer + + def check_review_decision(self, rev_decision): + r""" + Return ``True`` if the latest proper review of the PR has the + given decision. + """ + rev = self.get_latest_review() + if not rev: + # no proper review since most recent commit. + return False + return rev['state'] == rev_decision.value - ch_req = ReviewDecision.changes_requested - rev_dec = self.get_review_decision() - if rev_dec: - if rev_dec == ch_req: - info('PR %s needs work (by decision)' % self._issue) - return True - else: - info('PR %s doesn\'t need work (by decision)' % self._issue) - return False - - if any(rev['state'] == ch_req.value for rev in revs): + def needs_work_valid(self): + r""" + Return ``True`` if the PR needs work. This is the case if + the latest proper review request changes. + """ + if self.check_review_decision(RevState.changes_requested): info('PR %s needs work' % self._issue) return True info('PR %s doesn\'t need work' % self._issue) @@ -417,27 +526,10 @@ def needs_work_valid(self): def positive_review_valid(self): r""" - Return ``True`` if the PR has positive review. This is the - case if there are reviews more recent than any commit and the - review decision is approved or if there is any approved review - but no changes requesting one. + Return ``True`` if the PR is positively reviewed. This is the case if + the latest proper review is approved. """ - revs = self.get_reviews() - if not revs: - # no proper review since most recent commit. - return False - - appr = ReviewDecision.approved - rev_dec = self.get_review_decision() - if rev_dec: - if rev_dec == appr: - info('PR %s has positve review (by decision)' % self._issue) - return True - else: - info('PR %s doesn\'t have positve review (by decision)' % self._issue) - return False - - if all(rev['state'] == appr.value for rev in revs): + if self.check_review_decision(RevState.approved): info('PR %s has positve review' % self._issue) return True info('PR %s doesn\'t have positve review' % self._issue) @@ -451,6 +543,10 @@ def needs_review_valid(self): if self.is_draft(): return False + if self.review_by_actor(): + info('PR %s needs review (because of actor review)' % self._issue) + return True + if self.needs_work_valid(): info('PR %s already under review (needs work)' % self._issue) return False @@ -467,13 +563,12 @@ def approve_allowed(self): Return if the actor has permission to approve this PR. """ revs = self.get_reviews() - revs = [rev for rev in revs if rev['author']['login'] != self._actor] - ch_req = ReviewDecision.changes_requested + revs = [rev for rev in revs if not self.review_by_actor()] + ch_req = RevState.changes_requested if any(rev['state'] == ch_req.value for rev in revs): info('PR %s can\'t be approved by %s since others reqest changes' % (self._issue, self._actor)) return False - - return self.actor_valid() + return True def actor_valid(self): r""" @@ -486,19 +581,26 @@ def actor_valid(self): return True revs = self.get_reviews() - revs = [rev for rev in revs if rev['author']['login'] != 'github-actions'] + revs = [rev for rev in revs if not self.is_this_bot(rev['author']['login'])] if not revs: info('PR %s can\'t be approved by the author %s since no other person reviewed it' % (self._issue, self._actor)) return False coms = self.get_commits() - authors = sum(com['authors'] for com in coms) - authors = [auth for auth in authors if not auth['login'] in (self._actor, 'github-actions')] + authors = [] + for com in coms: + for auth in com['authors']: + login = auth['login'] + if not login in authors: + if not self.is_this_bot(login) and login != author: + debug('PR %s has recent commit by %s' % (self._issue, login)) + authors.append(login) + if not authors: info('PR %s can\'t be approved by the author %s since no other person commited to it' % (self._issue, self._actor)) return False - info('PR %s can be approved by the author %s as co-author' % (self._issue, self._actor)) + info('PR %s can be approved by the author %s as co-author' % (self._issue, author)) return True # ------------------------------------------------------------------------- @@ -511,7 +613,10 @@ def gh_cmd(self, cmd, arg, option): issue = 'issue' if self._pr: issue = 'pr' - cmd_str = 'gh %s %s %s %s "%s"' % (issue, cmd, self._url, option, arg) + if arg: + cmd_str = 'gh %s %s %s %s "%s"' % (issue, cmd, self._url, option, arg) + else: + cmd_str = 'gh %s %s %s %s' % (issue, cmd, self._url, option) debug('Execute command: %s' % cmd_str) ex_code = os.system(cmd_str) if ex_code: @@ -529,26 +634,70 @@ def mark_as_ready(self): """ self.gh_cmd('ready', '', '') - def review(self, arg, text): + def review(self, arg, text=None): r""" Perform a system call to ``gh`` to review a PR. """ - self.gh_cmd('review', arg, '-b \"%s\"' % text) + if text: + self.gh_cmd('review', arg, '-b \"%s\"' % text) + else: + self.gh_cmd('review', arg, '') def approve(self): r""" Approve the PR by the actor. """ - self.review('--approve', '%s approved this PR' % self._actor) + self.review('--approve') info('PR %s approved by %s' % (self._issue, self._actor)) def request_changes(self): r""" Request changes for this PR by the actor. """ - self.review('--request-changes', '%s requested changes for this PR' % self._actor) + self.review('--request-changes', '@%s requested changes for this PR' % self._actor) info('Changes requested for PR %s by %s' % (self._issue, self._actor)) + def dismiss_bot_reviews(self, message, node_id=None, state=None, actor=None): + r""" + Dismiss all reviews of the bot matching the given features (``node_id``, ...). + """ + path_args = '/repos/%s/%s/pulls/%s/reviews' % (self._owner, self._repo, self._number) + if not self._reviews_from_rest_api: + # since the reviews queried with `gh pr view` don't contain the id + # we need to obtain them form REST api. + self._reviews_from_rest_api = self.query_multi_pages(path_args) + reviews = self._reviews_from_rest_api + + options = '-f message=\"%s\" -f event=\"DISMISS\"' % message + for rev in reviews: + rev_login = rev['user']['login'] + rev_id = rev['id'] + rev_node_id = rev['node_id'] + rev_state = RevState(rev['state']) + + if not self.is_this_bot(rev_login): + continue + if not rev_state.is_proper(): + continue + + debug('Bot review with node_id %s has id %s' % (rev_node_id, rev_id)) + if node_id: + if rev_node_id != node_id: + continue + if state: + if rev_state != state: + continue + if actor: + if not rev['body'].find(actor): + continue + path_args_dismiss = '%s/%s/dismissals' % (path_args, rev_id) + try: + self.rest_api(path_args_dismiss, method='PUT', query=options) + info('Review %s (node_id %s, state %s) on PR %s dismissed' % (rev_id, rev_node_id, rev_state, self._issue)) + except CalledProcessError: + # the comment may have been deleted by a bot running in parallel + info('Review %s (node_id %s, state %s) on PR %s cannot be dismissed' % (rev_id, rev_node_id, rev_state, self._issue)) + def review_comment(self, text): r""" Add a review comment. @@ -569,6 +718,12 @@ def add_warning(self, text): """ self.add_comment('%s %s' % (self._warning_prefix, text)) + def add_hint(self, text): + r""" + Perform a system call to ``gh`` to add a hint to an issue or PR. + """ + self.add_comment('%s %s' % (self._hint_prefix, text)) + def add_label(self, label): r""" Add the given label to the issue or PR. @@ -604,29 +759,35 @@ def remove_label(self, label): def reject_label_addition(self, item): r""" - Post a comment that the given label can not be added and select - a corresponding other one. + Post a comment that the given label can not be added and remove + it again. + """ + if item is Status.positive_review: + self.add_warning('Label *%s* cannot be added by the author of the PR.' % item.value) + self.remove_label(item.value) + return + + def warning_about_label_addition(self, item): + r""" + Post a comment that the given label my be incorrect. """ if not self.is_pull_request(): - self.add_warning('Label *%s* can not be added to an issue. Please use it on the corresponding PR' % item.value) - elif item is State.needs_review: - self.add_warning('Label *%s* can not be added, since there are unresolved reviews' % item.value) + self.add_warning('Label *%s* is not suitable for an issue. Please use it on the corresponding PR.' % item.value) + elif item is Status.needs_review: + self.add_warning('Label *%s* may be incorrect, since there are unresolved reviews.' % item.value) else: - self.add_warning('Label *%s* can not be added. Please use the GitHub review functionality' % item.value) - self.remove_label(item.value) + self.add_warning('Label *%s* does not match the state of GitHub\'s review system.' % item.value) return - def reject_label_removal(self, item): + def hint_about_label_removal(self, item): r""" - Post a comment that the given label can not be removed and select - a corresponding other one. + Post a comment that the given label must not be removed any more. """ - if type(item) == State: - sel_list = 'state' + if type(item) == Status: + sel_list = 'status' else: sel_list = 'priority' - self.add_warning('Label *%s* can not be removed. Please add the %s-label which should replace it' % (item.value, sel_list)) - self.add_label(item.value) + self.add_hint('You don\'t need to remove %s labels any more. You\'d better just add the label which replaces it.' % sel_list) return # ------------------------------------------------------------------------- @@ -635,7 +796,7 @@ def reject_label_removal(self, item): def on_label_add(self, label): r""" Check if the given label belongs to a selection list. If so, remove - all other labels of that list. In case of a state label reviews are + all other labels of that list. In case of a status label reviews are booked accordingly. """ sel_list = selection_list(label) @@ -655,13 +816,13 @@ def on_label_add(self, label): warning('Label %s of %s not found!' % (label, self._issue)) return - if sel_list is State: + if sel_list is Status: if not self.is_pull_request(): - if item != State.needs_info: - self.reject_label_addition(item) + if item != Status.needs_info: + self.warning_about_label_addition(item) return - if item == State.needs_review: + if item == Status.needs_review: if self.needs_review_valid(): # here we come for example after a sequence: # needs review -> needs info -> needs review @@ -669,10 +830,10 @@ def on_label_add(self, label): elif self.is_draft(): self.mark_as_ready() else: - self.reject_label_addition(item) + self.warning_about_label_addition(item) return - if item == State.needs_work: + if item == Status.needs_work: if self.needs_work_valid(): # here we come for example after a sequence: # needs work -> needs info -> needs work @@ -680,18 +841,21 @@ def on_label_add(self, label): elif not self.is_draft(): self.request_changes() else: - self.reject_label_addition(item) + self.warning_about_label_addition(item) return - if item == State.positive_review: + if item == Status.positive_review: if self.positive_review_valid(): # here we come for example after a sequence: # positive review -> needs info -> positive review pass + elif not self.actor_valid(): + self.reject_label_addition(item) + return elif self.approve_allowed(): self.approve() else: - self.reject_label_addition(item) + self.warning_about_label_addition(item) return if sel_list is Resolution: @@ -703,22 +867,25 @@ def on_label_add(self, label): def on_label_removal(self, label): r""" - Check if the given label belongs to a selection list. If so, the - removement is rejected and a comment is posted to instead add a - replacement for ``label`` from the list. Exceptions are State labels - on issues and State.needs_info on a PR. + Check if the given label belongs to a selection list. If so, a comment + is posted to instead add a replacement for ``label`` from the list. + Exceptions are status labels on issues and Status.needs_info on a PR. """ sel_list = selection_list(label) if not sel_list: return item = sel_list(label) - if sel_list is State: + + if len(self.active_partners(item)) > 0: + return + + if sel_list is Status: if self.is_pull_request(): - if item != State.needs_info: - self.reject_label_removal(item) + if item != Status.needs_info: + self.hint_about_label_removal(item) elif sel_list is Priority: - self.reject_label_removal(item) + self.hint_about_label_removal(item) return def on_review_comment(self): @@ -729,10 +896,21 @@ def on_review_comment(self): have permission to add labels (i.e. aren't a member of the Triage team). """ - rev_state = self.review_comment_to_state() - if rev_state in (State.needs_info, State.needs_review): - self.select_label(rev_state) - self.run(Action.labeled, label=rev_state.value) + status, ass = self.review_comment_to_status() + if ass is AuthorAssociation.owner: + if status is Status.positive_review: + # allow the repository owner to approve his own PR for testing + # the bot + info('Owner approves PR %s for testing the bot' % self._issue) + self.dismiss_bot_reviews('@%s approved the PR.' % self._actor, state=RevState.changes_requested, actor=self._actor) + self.approve() + elif ass.is_valid() or ass is Author.Assoziation.contributor: + if status in (Status.needs_info, Status.needs_review): + # allow contributors who are not Triage members to set + # these labels + info('Simulate label addition of %s for %s' % (label, self._issue)) + self.select_label(status) + self.run(Action.labeled, label=status.value) def remove_all_labels_of_sel_list(self, sel_list): r""" @@ -747,12 +925,16 @@ def run(self, action, label=None, rev_state=None): """ self.reset_view() # this is just needed for run_tests + if self.is_this_bot(self._actor): + info('Trigger %s of the bot %s is ignored' % (action, self._actor)) + return + if action is Action.opened and self.is_pull_request(): if not self.is_draft(): - self.add_default_label(State.needs_review) + self.add_default_label(Status.needs_review) if action in (Action.closed, Action.reopened, Action.converted_to_draft): - self.remove_all_labels_of_sel_list(State) + self.remove_all_labels_of_sel_list(Status) if action is Action.labeled: self.on_label_add(label) @@ -761,21 +943,27 @@ def run(self, action, label=None, rev_state=None): self.on_label_removal(label) if action in (Action.ready_for_review, Action.synchronize): + self.dismiss_bot_reviews('New changes ready for review.') if self.needs_review_valid(): - self.select_label(State.needs_review) + self.select_label(Status.needs_review) if action is Action.review_requested: - self.select_label(State.needs_review) + self.select_label(Status.needs_review) if action is Action.submitted: - rev_state = RevState(rev_state) + rev_state = RevState(rev_state.upper()) if rev_state is RevState.approved: - if self.actor_authorized() and self.positive_review_valid(): - self.select_label(State.positive_review) + self.dismiss_bot_reviews('@%s approved the PR.' % self._actor, state=RevState.changes_requested, actor=self._actor) + rev_req = self.get_review_requests() + if rev_req: + info('Waiting on pending review requests: %s' % rev_req) + elif self.actor_authorized() and self.positive_review_valid(): + self.select_label(Status.positive_review) if rev_state is RevState.changes_requested: + self.dismiss_bot_reviews('@%s requested changes.' % self._actor, state=RevState.approved) if self.needs_work_valid(): - self.select_label(State.needs_work) + self.select_label(Status.needs_work) if rev_state is RevState.commented: self.on_review_comment() @@ -794,12 +982,12 @@ def run_tests(self): for action in Action: self.add_comment('Test action %s' % action.value) if action in (Action.labeled, Action.unlabeled): - for stat in State: + for status in Status: if action is Action.labeled: - self.add_label(stat.value) + self.add_label(status.value) else: - self.remove_label(stat.value) - self.run(action, label=stat.value) + self.remove_label(status.value) + self.run(action, label=status.value) for prio in Priority: if action is Action.labeled: self.add_label(prio.value) @@ -811,17 +999,17 @@ def run_tests(self): self.add_label(res.value) self.run(action, label=prio.value) elif action == Action.submitted and self.is_pull_request(): - for rev_stat in RevState: - if rev_stat is RevState.approved: + for rev_state in RevState: + if rev_state is RevState.approved: self.approve() - self.run(action, rev_state=rev_stat.value) - elif rev_stat is RevState.changes_requested: + self.run(action, rev_state=rev_state.value) + elif rev_state is RevState.changes_requested: self.request_changes() - self.run(action, rev_state=rev_stat.value) - elif rev_stat is RevState.commented: - for stat in State: - self.review_comment(stat.value) - self.run(action, rev_state=rev_stat.value) + self.run(action, rev_state=rev_state.value) + elif rev_state is RevState.commented: + for status in Status: + self.review_comment(status.value) + self.run(action, rev_state=rev_state.value) elif self.is_pull_request(): self.run(action) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5242dfc06f9..7ac9c6154d0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -103,21 +103,30 @@ jobs: MAKE: make -j2 --output-sync=recurse SAGE_NUM_THREADS: 2 - - name: Set up node to install pyright + - name: Static code check with pyright if: always() && steps.worktree.outcome == 'success' - uses: actions/setup-node@v3 + uses: jakebailey/pyright-action@v1 with: - node-version: '12' - - - name: Install pyright - if: always() && steps.worktree.outcome == 'success' - # Fix to v232 due to bug https://github.com/microsoft/pyright/issues/3239 - run: npm install -g pyright@1.1.232 - - - name: Static code check with pyright + version: 1.1.332 + # Many warnings issued by pyright are not yet helpful because there is not yet enough type information. + no-comments: true + working-directory: ./worktree-image + env: + # To avoid out of memory errors + NODE_OPTIONS: --max-old-space-size=8192 + + - name: Static code check with pyright (annotated) if: always() && steps.worktree.outcome == 'success' - run: pyright - working-directory: ./worktree-image + uses: jakebailey/pyright-action@v1 + with: + version: 1.1.332 + # Issue errors + no-comments: false + level: error + working-directory: ./worktree-image + env: + # To avoid out of memory errors + NODE_OPTIONS: --max-old-space-size=8192 - name: Clean (fallback to non-incremental) id: clean diff --git a/.github/workflows/ci-linux-incremental.yml b/.github/workflows/ci-linux-incremental.yml index a4aa9ae99c7..7887597845c 100644 --- a/.github/workflows/ci-linux-incremental.yml +++ b/.github/workflows/ci-linux-incremental.yml @@ -24,6 +24,9 @@ on: - reopened # When a CI label is added - labeled + paths: + - 'build/pkgs/**' + - 'pkgs/**' workflow_dispatch: concurrency: diff --git a/.github/workflows/dist.yml b/.github/workflows/dist.yml index de49bbc69a3..fb2229ba7b4 100644 --- a/.github/workflows/dist.yml +++ b/.github/workflows/dist.yml @@ -111,11 +111,11 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-20.04 + - os: ubuntu-latest arch: x86_64 - - os: ubuntu-20.04 + - os: ubuntu-latest arch: i686 - - os: macos-10.15 + - os: macos-latest arch: auto env: # SPKGs to install as system packages @@ -128,7 +128,7 @@ jobs: # CIBW_ARCHS: ${{ matrix.arch }} # https://cibuildwheel.readthedocs.io/en/stable/options/#requires-python - CIBW_PROJECT_REQUIRES_PYTHON: ">=3.9" + CIBW_PROJECT_REQUIRES_PYTHON: ">=3.9, <3.12" # Environment during wheel build CIBW_ENVIRONMENT: "PATH=$(pwd)/local/bin:$PATH CPATH=$(pwd)/local/include:$CPATH LIBRARY_PATH=$(pwd)/local/lib:$LIBRARY_PATH PKG_CONFIG_PATH=$(pwd)/local/share/pkgconfig:$PKG_CONFIG_PATH ACLOCAL_PATH=/usr/share/aclocal" # Use 'build', not 'pip wheel' @@ -156,7 +156,7 @@ jobs: mkdir -p unpacked for pkg in sagemath-objects sagemath-categories; do (cd unpacked && tar xfz - ) < dist/$pkg*.tar.gz - pipx run cibuildwheel==2.7.0 unpacked/$pkg* + pipx run cibuildwheel==2.16.2 unpacked/$pkg* done - uses: actions/upload-artifact@v3 diff --git a/.github/workflows/doc-build.yml b/.github/workflows/doc-build.yml index dbd8c99ff30..5eb3998feee 100644 --- a/.github/workflows/doc-build.yml +++ b/.github/workflows/doc-build.yml @@ -56,9 +56,23 @@ jobs: git config --global --add safe.directory $(pwd) git config --global user.email "ci-sage@example.com" git config --global user.name "Build & Test workflow" + # mathjax path in old doc + mathjax_path_from=$(SAGE_USE_CDNS=no /sage/sage -python -c "from sage_docbuild.conf import mathjax_path; print(mathjax_path)") .ci/retrofit-worktree.sh worktree-image /sage - # Keep track of changes to built HTML - new_version=$(cat src/VERSION.txt); (cd /sage/local/share/doc/sage/html/en && find . -name "*.html" | xargs sed -i '/class="sidebar-brand-text"/s/Sage [0-9a-z.]* /Sage '$new_version' /'; git init && (echo "*.svg binary"; echo "*.pdf binary") >> .gitattributes && (echo ".buildinfo"; echo '*.inv'; echo '.git*'; echo '*.svg'; echo '*.pdf'; echo '*.png'; echo 'searchindex.js') > .gitignore; git add -A && git commit --quiet -m "old") + # mathjax path in new doc + mathjax_path_to=$(SAGE_USE_CDNS=yes /sage/sage -python -c "from sage_docbuild.conf import mathjax_path; print(mathjax_path)") + new_version=$(cat src/VERSION.txt) + # Wipe out chronic diffs between old doc and new doc + (cd /sage/local/share/doc/sage/html/en && \ + find . -name "*.html" | xargs sed -i -e '/class="sidebar-brand-text"/ s/Sage [0-9a-z.]* /Sage '"$new_version"' /' \ + -e 's;'"$mathjax_path_from"';'"$mathjax_path_to"';' \ + -e '\;; d') + # Create git repo from old doc + (cd /sage/local/share/doc/sage/html/en && \ + git init && \ + (echo "*.svg binary"; echo "*.pdf binary") >> .gitattributes && \ + (echo ".buildinfo"; echo '*.inv'; echo '.git*'; echo '*.svg'; echo '*.pdf'; echo '*.png'; echo 'searchindex.js') > .gitignore; \ + git add -A && git commit --quiet -m "old") - name: Download upstream artifact uses: actions/download-artifact@v3 @@ -77,7 +91,7 @@ jobs: id: incremental run: | # Now re-bootstrap and build. The build is incremental because we were careful with the timestamps. - ./bootstrap && make build + ./bootstrap && make sagemath_doc_html-build-deps working-directory: ./worktree-image env: MAKE: make -j2 --output-sync=recurse @@ -88,7 +102,7 @@ jobs: if: always() && steps.worktree.outcome == 'success' && steps.incremental.outcome != 'success' run: | set -ex - make sagelib-clean && git clean -fx src/sage && ./config.status && make build + make sagelib-clean && git clean -fx src/sage && ./config.status && make sagemath_doc_html-build-deps working-directory: ./worktree-image env: MAKE: make -j2 --output-sync=recurse @@ -105,7 +119,7 @@ jobs: mv /sage/local/share/doc/sage/html/en/.git /sage/.git-doc make doc-clean doc-uninstall mkdir -p /sage/local/share/doc/sage/html/en/ && mv /sage/.git-doc /sage/local/share/doc/sage/html/en/.git - ./config.status && make doc-html + ./config.status && make sagemath_doc_html-no-deps working-directory: ./worktree-image env: MAKE: make -j2 --output-sync=recurse @@ -117,12 +131,58 @@ jobs: run: | set -ex mkdir -p ./docs - # Create changelog - echo '## Preview of CHANGES.html' - (cd /sage/local/share/doc/sage/html/en && git diff --name-only) | tee ./docs/CHANGES.txt - (cd /sage/local/share/doc/sage/html/en && git diff; rm -rf .git) > ./docs/html.diff - echo '## Preview of html.diff'; head -n 400 ./docs/html.diff - (echo '

HTML diff'; sed -E 's,(.*),

\1,' ./docs/CHANGES.txt) > ./docs/CHANGES.html + (cd /sage/local/share/doc/sage/html/en && git commit -a -m 'new') + # Wipe out chronic diffs between old doc and new doc + (cd /sage/local/share/doc/sage/html/en && \ + find . -name "*.html" | xargs sed -i -e '\;; d') + # Create CHANGES.html + echo '' > ./docs/CHANGES.html + echo '' >> ./docs/CHANGES.html + echo '' >> ./docs/CHANGES.html + echo '' >> ./docs/CHANGES.html + echo '' >> ./docs/CHANGES.html + cat >> ./docs/CHANGES.html << EOF + + EOF + echo '' >> ./docs/CHANGES.html + echo '' >> ./docs/CHANGES.html + (cd /sage/local/share/doc/sage/html/en && git diff HEAD^; rm -rf .git) > ./docs/diff.txt + /sage/sage -python - << EOF + import re, html + with open('./docs/diff.txt', 'r') as f: + diff_text = f.read() + diff_blocks = re.split(r'^(?=diff --git)', diff_text, flags=re.MULTILINE) + out_blocks = [] + for block in diff_blocks: + match = re.search(r'^diff --git a/(.*) b/\1', block, flags=re.MULTILINE) + if match: + path = match.group(1) + out_blocks.append(f'

{path}

\n
' + html.escape(block).strip() + '
') + output_text = '\n'.join(out_blocks) + with open('./docs/diff.html', 'w') as f: + f.write(output_text) + EOF + cat ./docs/diff.html >> ./docs/CHANGES.html + echo '' >> ./docs/CHANGES.html + echo '' >>./docs/CHANGES.html + rm ./docs/diff.txt ./docs/diff.html + (cd /sage/local/share/doc/sage/html/en && git reset --hard HEAD) # For some reason the deploy step below cannot find /sage/... # So copy everything from there to local folder # We also need to replace the symlinks because netlify is not following them diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index afd0406341c..41560674b49 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -33,13 +33,17 @@ jobs: python-version: 3.9 - name: Install dependencies - run: pip install tox pycodestyle relint + id: deps + run: pip install tox - name: Code style check with pycodestyle + if: always() && steps.deps.outcome == 'success' run: tox -e pycodestyle-minimal - name: Code style check with relint + if: always() && steps.deps.outcome == 'success' run: tox -e relint -- src/sage/ - name: Validate docstring markup as RST + if: always() && steps.deps.outcome == 'success' run: tox -e rst diff --git a/.github/workflows/sync_labels.yml b/.github/workflows/sync_labels.yml index f9378d1fe9d..56fe526eb8e 100644 --- a/.github/workflows/sync_labels.yml +++ b/.github/workflows/sync_labels.yml @@ -29,6 +29,15 @@ jobs: with: files: .github/sync_labels.py + # Set special sync_labels bot token + - name: Get Tocken + run: | + TOKEN="${{ secrets.SYNC_LABELS_BOT_TOKEN }}" + if [ -z "$TOKEN" ]; then + TOKEN="${{ secrets.GITHUB_TOKEN }}" + fi + echo "TOKEN=$TOKEN" >> $GITHUB_ENV + # Perform synchronization - name: Call script for synchronization if: github.event.schedule == '' @@ -36,7 +45,7 @@ jobs: chmod a+x .github/sync_labels.py .github/sync_labels.py $ACTION $ISSUE_URL $PR_URL $ACTOR "$LABEL" "$REV_STATE" $LOG_LEVEL env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ env.TOKEN }} ACTION: ${{ github.event.action }} ISSUE_URL: ${{ github.event.issue.html_url }} PR_URL: ${{ github.event.pull_request.html_url }} @@ -52,6 +61,6 @@ jobs: chmod a+x .github/sync_labels.py .github/sync_labels.py $REPO_URL $LOG_LEVEL env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ env.TOKEN }} REPO_URL: ${{ github.event.repository.html_url }} LOG_LEVEL: ${{ vars.SYNC_LABELS_LOG_LEVEL }} # variable from repository settings, values can be "--debug", "--info" or "--warning" diff --git a/.vscode/settings.json b/.vscode/settings.json index be90c535c32..050be4ca5e5 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -8,13 +8,14 @@ "src/**/*.so": true }, "search.exclude": { - "build/pkgs/sagemath_categories/src": true, - "build/pkgs/sagemath_objects/src": true, - "build/pkgs/sagelib/src": true, - "pkgs/sage-conf_pypi/sage_root/build": true, - "pkgs/sagemath-categories/sage": true, - "pkgs/sagemath-objects/sage": true, - "pkgs/sagemath-standard/sage": true + // Exclude symbolic links into SAGE_ROOT/pkgs/ + "build/pkgs/*/src": true, + // Exclude symbolic links into SAGE_ROOT/src/ + "pkgs/sage-conf_conda/sage_root": true, + "pkgs/sage-conf_pypi/sage_root": true, + "pkgs/sage-docbuild/sage_docbuild": true, + "pkgs/sage-setup/sage_setup": true, + "pkgs/sagemath-*/sage": true }, "python.testing.pytestEnabled": true, "python.testing.pytestArgs": [ diff --git a/CITATION.cff b/CITATION.cff index 59a1b01420e..27438597f31 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -4,8 +4,8 @@ title: SageMath abstract: SageMath is a free open-source mathematics software system. authors: - name: "The SageMath Developers" -version: 10.2.beta8 +version: 10.2.beta9 doi: 10.5281/zenodo.593563 -date-released: 2023-10-21 +date-released: 2023-10-30 repository-code: "https://github.com/sagemath/sage" url: "https://www.sagemath.org/" diff --git a/README.md b/README.md index 533e7ac54c7..495365af6eb 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ below](#sagemath-docker-images)) or other virtualization solutions. If your Mac uses the Apple Silicon (M1, M2, arm64) architecture: -- If you set up your Mac by transfering files from an older Mac, make sure +- If you set up your Mac by transferring files from an older Mac, make sure that the directory ``/usr/local`` does not contain an old copy of Homebrew (or other software) for the x86_64 architecture that you may have copied over. Note that Homebrew for the M1 is installed in ``/opt/homebrew``, not diff --git a/VERSION.txt b/VERSION.txt index 6c7fa387f09..b2bf34c0be8 100644 --- a/VERSION.txt +++ b/VERSION.txt @@ -1 +1 @@ -SageMath version 10.2.beta8, Release Date: 2023-10-21 +SageMath version 10.2.beta9, Release Date: 2023-10-30 diff --git a/build/pkgs/configure/checksums.ini b/build/pkgs/configure/checksums.ini index 99e471b97f6..5b7360aa36d 100644 --- a/build/pkgs/configure/checksums.ini +++ b/build/pkgs/configure/checksums.ini @@ -1,4 +1,4 @@ tarball=configure-VERSION.tar.gz -sha1=aa7054a0e6a582d2db1475dc47f63a54e6ac569f -md5=40eab024557ad51e08dfb08e2753a465 -cksum=802824779 +sha1=0f90c993748bfc21ae382ac3ce6c19b434edb36c +md5=b8d9355c732997566f68b60c8a8eb9cc +cksum=2280021929 diff --git a/build/pkgs/configure/package-version.txt b/build/pkgs/configure/package-version.txt index f8291b5f3d7..d63934749a3 100644 --- a/build/pkgs/configure/package-version.txt +++ b/build/pkgs/configure/package-version.txt @@ -1 +1 @@ -c47788b02a42ef4907a0e61e702fbe9bbef27590 +c0221f90a86e4b4bea4b45ff8de54727313bd755 diff --git a/build/pkgs/cypari/checksums.ini b/build/pkgs/cypari/checksums.ini index 998c8a5e962..3f87b3fabb8 100644 --- a/build/pkgs/cypari/checksums.ini +++ b/build/pkgs/cypari/checksums.ini @@ -1,5 +1,5 @@ tarball=cypari2-VERSION.tar.gz -sha1=7208fd9d0b636ca7704d3b7d1167bc7c9af2637c -md5=605b157123bd8a498d53572e8096bb8c -cksum=2809951255 -upstream_url=https://pypi.io/packages/source/c/cypari2/cypari2-VERSION.tar.gz +sha1=0af00b66e3f1b77e932ad9cade6e4e9dc6f21eaa +md5=34c919aedb0a470c8b4e4b0c0ec788e3 +cksum=2760761148 +upstream_url=https://github.com/sagemath/cypari2/releases/download/VERSION/cypari2-VERSION.tar.gz diff --git a/build/pkgs/cypari/package-version.txt b/build/pkgs/cypari/package-version.txt index ac2cdeba013..7d2ed7c7020 100644 --- a/build/pkgs/cypari/package-version.txt +++ b/build/pkgs/cypari/package-version.txt @@ -1 +1 @@ -2.1.3 +2.1.4 diff --git a/build/pkgs/cypari/patches/cython3-legacy.patch b/build/pkgs/cypari/patches/cython3-legacy.patch deleted file mode 100644 index 41392fe80d7..00000000000 --- a/build/pkgs/cypari/patches/cython3-legacy.patch +++ /dev/null @@ -1,32 +0,0 @@ -commit 8ef356a4eb936c37f55a5c501f3a955e6740c0c5 -Author: Gonzalo Tornaría -Date: Wed Jul 19 19:45:23 2023 -0300 - - cython3 support using legacy directives - -diff --git a/cypari2/gen.pyx b/cypari2/gen.pyx -index 247b1ad..75050a0 100644 ---- a/cypari2/gen.pyx -+++ b/cypari2/gen.pyx -@@ -329,7 +329,7 @@ cdef class Gen(Gen_base): - >>> pari = Pari() - >>> L = pari("vector(10,i,i^2)") - >>> L.__iter__() -- -+ <...generator object at ...> - >>> [x for x in L] - [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] - >>> list(L) -diff --git a/setup.py b/setup.py -index 2188711..455337f 100755 ---- a/setup.py -+++ b/setup.py -@@ -36,6 +36,8 @@ class build_ext(_build_ext): - "binding": True, - "cdivision": True, - "language_level": 2, -+ "legacy_implicit_noexcept": True, -+ "c_api_binop_methods": True, - } - - _build_ext.finalize_options(self) diff --git a/build/pkgs/cython/checksums.ini b/build/pkgs/cython/checksums.ini index 5d0bc66c242..a728e447c9b 100644 --- a/build/pkgs/cython/checksums.ini +++ b/build/pkgs/cython/checksums.ini @@ -1,5 +1,5 @@ tarball=Cython-VERSION.tar.gz -sha1=08eb99f7c95b7ca667b1547575e7369d8064b4b3 -md5=00def3f2b96c393098e01eb2f1f169ad -cksum=2321746451 +sha1=9924cb41152a854124c264e2046b3d48ec8207a5 +md5=9bafc611be35748b17a62f47bc479b35 +cksum=1074764487 upstream_url=https://pypi.io/packages/source/C/Cython/Cython-VERSION.tar.gz diff --git a/build/pkgs/cython/package-version.txt b/build/pkgs/cython/package-version.txt index b5021469305..b0f2dcb32fc 100644 --- a/build/pkgs/cython/package-version.txt +++ b/build/pkgs/cython/package-version.txt @@ -1 +1 @@ -3.0.2 +3.0.4 diff --git a/build/pkgs/cython/patches/5690.patch b/build/pkgs/cython/patches/5690.patch deleted file mode 100644 index cc927879e1f..00000000000 --- a/build/pkgs/cython/patches/5690.patch +++ /dev/null @@ -1,48 +0,0 @@ -diff --git a/Cython/Debugger/DebugWriter.py b/Cython/Debugger/DebugWriter.py -index 8b1fb75b027..2c3c310fc64 100644 ---- a/Cython/Debugger/DebugWriter.py -+++ b/Cython/Debugger/DebugWriter.py -@@ -18,6 +18,21 @@ - etree = None - - from ..Compiler import Errors -+from ..Compiler.StringEncoding import EncodedString -+ -+ -+def is_valid_tag(name): -+ """ -+ Names like '.0' are used internally for arguments -+ to functions creating generator expressions, -+ however they are not identifiers. -+ -+ See https://github.com/cython/cython/issues/5552 -+ """ -+ if isinstance(name, EncodedString): -+ if name.startswith(".") and name[1:].isdecimal(): -+ return False -+ return True - - - class CythonDebugWriter(object): -@@ -39,14 +54,17 @@ def __init__(self, output_dir): - self.start('cython_debug', attrs=dict(version='1.0')) - - def start(self, name, attrs=None): -- self.tb.start(name, attrs or {}) -+ if is_valid_tag(name): -+ self.tb.start(name, attrs or {}) - - def end(self, name): -- self.tb.end(name) -+ if is_valid_tag(name): -+ self.tb.end(name) - - def add_entry(self, name, **attrs): -- self.tb.start(name, attrs) -- self.tb.end(name) -+ if is_valid_tag(name): -+ self.tb.start(name, attrs) -+ self.tb.end(name) - - def serialize(self): - self.tb.end('Module') diff --git a/build/pkgs/fpylll/distros/conda.txt b/build/pkgs/fpylll/distros/conda.txt index 8a3e3a7ecd0..aa483930c7a 100644 --- a/build/pkgs/fpylll/distros/conda.txt +++ b/build/pkgs/fpylll/distros/conda.txt @@ -1 +1 @@ -fpylll +fpylll>=0.5.9 diff --git a/build/pkgs/fpylll/install-requires.txt b/build/pkgs/fpylll/install-requires.txt index c97d0c2c71e..e040e7daa1e 100644 --- a/build/pkgs/fpylll/install-requires.txt +++ b/build/pkgs/fpylll/install-requires.txt @@ -1 +1 @@ -fpylll >=0.5.9, <=0.5.9 +fpylll >=0.5.9 diff --git a/build/pkgs/ipywidgets/distros/conda.txt b/build/pkgs/ipywidgets/distros/conda.txt index f943f9d4979..162744f2841 100644 --- a/build/pkgs/ipywidgets/distros/conda.txt +++ b/build/pkgs/ipywidgets/distros/conda.txt @@ -1 +1 @@ -ipywidgets<8.0.0 +ipywidgets>=7.5.1 diff --git a/build/pkgs/jupyter_sphinx/checksums.ini b/build/pkgs/jupyter_sphinx/checksums.ini index f53c5af453a..14f1bdf7594 100644 --- a/build/pkgs/jupyter_sphinx/checksums.ini +++ b/build/pkgs/jupyter_sphinx/checksums.ini @@ -1,5 +1,5 @@ tarball=jupyter_sphinx-VERSION.tar.gz -sha1=241f6dfcd3aae4f44f330e2ba76480011b382d3d -md5=e7ab370d9793be5b20bce5447ccbd45b -cksum=2021246952 +sha1=fb2abdd5e35da0886b12d45a6373c4dbcc24b244 +md5=130daa6be810976c9f8e30aa04011e50 +cksum=2882523000 upstream_url=https://pypi.io/packages/source/j/jupyter_sphinx/jupyter_sphinx-VERSION.tar.gz diff --git a/build/pkgs/jupyter_sphinx/package-version.txt b/build/pkgs/jupyter_sphinx/package-version.txt index d15723fbe8d..8af2848288a 100644 --- a/build/pkgs/jupyter_sphinx/package-version.txt +++ b/build/pkgs/jupyter_sphinx/package-version.txt @@ -1 +1 @@ -0.3.2 +0.4.0.p0 diff --git a/build/pkgs/jupyter_sphinx/patches/0001-Patch-for-sage-live-doc.patch b/build/pkgs/jupyter_sphinx/patches/0001-Patch-for-sage-live-doc.patch new file mode 100644 index 00000000000..afbb0c1273f --- /dev/null +++ b/build/pkgs/jupyter_sphinx/patches/0001-Patch-for-sage-live-doc.patch @@ -0,0 +1,57 @@ +From 5bffbe38302c695123779f87300d84090b4bd118 Mon Sep 17 00:00:00 2001 +From: Kwankyu Lee +Date: Mon, 28 Aug 2023 00:18:59 +0900 +Subject: [PATCH] Patch for sage live doc + +--- + jupyter_sphinx/__init__.py | 4 ++-- + jupyter_sphinx/execute.py | 11 +++++++++++ + 2 files changed, 13 insertions(+), 2 deletions(-) + +diff --git a/jupyter_sphinx/__init__.py b/jupyter_sphinx/__init__.py +index 34af884..b7ca8ee 100644 +--- a/jupyter_sphinx/__init__.py ++++ b/jupyter_sphinx/__init__.py +@@ -31,7 +31,7 @@ from .thebelab import ThebeButton, ThebeButtonNode, ThebeOutputNode, ThebeSource + REQUIRE_URL_DEFAULT = ( + "https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js" + ) +-THEBELAB_URL_DEFAULT = "https://unpkg.com/thebelab@^0.4.0" ++THEBELAB_URL_DEFAULT = "https://unpkg.com/thebe@latest/lib/index.js" + + logger = logging.getLogger(__name__) + +@@ -186,7 +186,7 @@ def setup(app): + app.add_config_value("jupyter_sphinx_embed_url", None, "html") + + # thebelab config, can be either a filename or a dict +- app.add_config_value("jupyter_sphinx_thebelab_config", None, "html") ++ app.add_config_value("jupyter_sphinx_thebelab_config", None, "env") + app.add_config_value("jupyter_sphinx_thebelab_url", THEBELAB_URL_DEFAULT, "html") + + # linenos config +diff --git a/jupyter_sphinx/execute.py b/jupyter_sphinx/execute.py +index 558a26b..de44455 100644 +--- a/jupyter_sphinx/execute.py ++++ b/jupyter_sphinx/execute.py +@@ -152,6 +152,17 @@ class ExecuteJupyterCells(SphinxTransform): + kernel_name = default_kernel + file_name = next(default_names) + ++ # Save time when jupyter notebook execution is not necessary ++ if not any(not "execute" in node or node["execute"] for node in nodes): ++ # mimics empty cell output for each node ++ for node in nodes: ++ source = node.children[0] ++ source.attributes["classes"].append("code_cell") ++ node.attributes["cm_language"] = kernel_name ++ node += CellOutputNode(classes=["cell_output"]) ++ apply_styling(node, thebe_config) ++ continue ++ + # Add empty placeholder cells for non-executed nodes so nodes + # and cells can be zipped and the provided input/output + # can be inserted later +-- +2.42.0 + diff --git a/build/pkgs/meson/checksums.ini b/build/pkgs/meson/checksums.ini index 97e3fe2c251..bbb4661c960 100644 --- a/build/pkgs/meson/checksums.ini +++ b/build/pkgs/meson/checksums.ini @@ -1,5 +1,5 @@ tarball=meson-VERSION.tar.gz -sha1=39b8a4bff467fdaa5f9ee87e04715bd97a148378 -md5=702bfd8b0648521322d3f145a8fc70ea -cksum=399123386 +sha1=97e766951553ec35315712f0a27d5554a010d4c3 +md5=69da4c63ef06c9d3bcc00ce89abb306f +cksum=2424401184 upstream_url=https://pypi.io/packages/source/m/meson/meson-VERSION.tar.gz diff --git a/build/pkgs/meson/package-version.txt b/build/pkgs/meson/package-version.txt index 23aa8390630..0495c4a88ca 100644 --- a/build/pkgs/meson/package-version.txt +++ b/build/pkgs/meson/package-version.txt @@ -1 +1 @@ -1.2.2 +1.2.3 diff --git a/build/pkgs/meson/spkg-configure.m4 b/build/pkgs/meson/spkg-configure.m4 index dbc575650fc..d85bd144a07 100644 --- a/build/pkgs/meson/spkg-configure.m4 +++ b/build/pkgs/meson/spkg-configure.m4 @@ -1,11 +1,12 @@ SAGE_SPKG_CONFIGURE( [meson], [ dnl scipy 1.11.2 needs meson >= 1.1.0 - AC_CACHE_CHECK([for meson >= 1.1.0], [ac_cv_path_MESON], [ + dnl contourpy needs meson >= 1.2.0 + AC_CACHE_CHECK([for meson >= 1.2.0], [ac_cv_path_MESON], [ AC_PATH_PROGS_FEATURE_CHECK([MESON], [meson], [ meson_version=`$ac_path_MESON --version 2>&1` AS_IF([test -n "$meson_version"], [ - AX_COMPARE_VERSION([$meson_version], [ge], [1.1.0], [ + AX_COMPARE_VERSION([$meson_version], [ge], [1.2.0], [ ac_cv_path_MESON="$ac_path_MESON" ac_path_MESON_found=: ]) diff --git a/build/pkgs/nauty/checksums.ini b/build/pkgs/nauty/checksums.ini index 644f4b75146..a9dd1246e91 100644 --- a/build/pkgs/nauty/checksums.ini +++ b/build/pkgs/nauty/checksums.ini @@ -1,5 +1,5 @@ tarball=nautyVERSION.tar.gz -sha1=c9fd2b4c99b8c624e430f3f4e1492a4219e3495e -md5=2ead635a417e20a18b3aabee83fac1ef -cksum=718823455 -upstream_url=http://pallini.di.uniroma1.it/nauty27r1.tar.gz +sha1=10c39117c55c69c18c6a107110e7c08f3d873652 +md5=7a82f4209f5d552da3078c67e5af872e +cksum=2164796643 +upstream_url=https://pallini.di.uniroma1.it/nauty2_8_6.tar.gz diff --git a/build/pkgs/nauty/package-version.txt b/build/pkgs/nauty/package-version.txt index 9a8067baa68..b6b3dcc5aa0 100644 --- a/build/pkgs/nauty/package-version.txt +++ b/build/pkgs/nauty/package-version.txt @@ -1 +1 @@ -27r1.p1 +2.8.6.p0 diff --git a/build/pkgs/nauty/patches/nauty-2.8.6-gentreeg-gentourng.patch b/build/pkgs/nauty/patches/nauty-2.8.6-gentreeg-gentourng.patch new file mode 100644 index 00000000000..322b25326ee --- /dev/null +++ b/build/pkgs/nauty/patches/nauty-2.8.6-gentreeg-gentourng.patch @@ -0,0 +1,144 @@ +From edb0474a4db8e69f971e4eebe18716309f5a7bb3 Mon Sep 17 00:00:00 2001 +From: Michael Orlitzky +Date: Tue, 17 Jan 2023 19:44:49 -0500 +Subject: [PATCH 1/1] Upstream fixes for gentreeg and gentourng. + +https://mailman.anu.edu.au/pipermail/nauty/2023-January/000903.html +--- + gentourng.c | 2 +- + gentreeg.c | 95 ++++++++++++++++++++++++++++------------------------- + 2 files changed, 51 insertions(+), 46 deletions(-) + +diff --git a/gentourng.c b/gentourng.c +index 634e5e8..5c7ffff 100644 +--- a/gentourng.c ++++ b/gentourng.c +@@ -1408,7 +1408,7 @@ PLUGIN_INIT + (*outproc)(outfile,g,1); + } + } +- else ++ else if (!connec || maxn != 2) + { + makeleveldata(); + +diff --git a/gentreeg.c b/gentreeg.c +index 946d5f8..15bf87b 100644 +--- a/gentreeg.c ++++ b/gentreeg.c +@@ -1,4 +1,4 @@ +-/* gentree version 1.3; Brendan McKay Oct 2022 */ ++/* gentree version 1.4; Brendan McKay Dec 2022 */ + /* This program is a wrapper for the program FreeTrees.c written + * by Gang Li & Frank Ruskey. See below for their original + * comments. */ +@@ -32,49 +32,54 @@ Counts for n=1..45: + 1: 1 + 2: 1 + 3: 1 +- 4: 1 +- 5: 2 +- 6: 3 +- 7: 6 +- 8: 11 +- 9: 23 +-10: 47 +-11: 106 +-12: 235 +-13: 551 +-14: 1301 +-15: 3159 +-16: 7741 +-17: 19320 +-18: 48629 +-19: 123867 +-20: 317955 +-21: 823065 +-22: 2144505 +-23: 5623756 +-24: 14828074 +-25: 39299897 +-26: 104636890 +-27: 279793450 +-28: 751065460 +-29: 2023443032 +-30: 5469566585 +-31: 14830871802 +-32: 40330829030 +-33: 109972410221 +-34: 300628862480 +-35: 823779631721 +-36: 2262366343746 +-37: 6226306037178 +-38: 17169677490714 +-39: 47436313524262 +-40: 131290543779126 +-41: 363990257783343 +-42: 1010748076717151 +-43: 2810986483493475 +-44: 7828986221515605 +-45: 21835027912963086 +-********************************/ ++ 4: 2 ++ 5: 3 ++ 6: 6 ++ 7: 11 ++ 8: 23 ++ 9: 47 ++10: 106 ++11: 235 ++12: 551 ++13: 1301 ++14: 3159 ++15: 7741 ++16: 19320 ++17: 48629 ++18: 123867 ++19: 317955 ++20: 823065 ++21: 2144505 ++22: 5623756 ++23: 14828074 ++24: 39299897 ++25: 104636890 ++26: 279793450 ++27: 751065460 ++28: 2023443032 ++29: 5469566585 ++30: 14830871802 ++31: 40330829030 ++32: 109972410221 ++33: 300628862480 ++34: 823779631721 ++35: 2262366343746 ++36: 6226306037178 ++37: 17169677490714 ++38: 47436313524262 ++39: 131290543779126 ++40: 363990257783343 ++41: 1010748076717151 ++42: 2810986483493475 ++43: 7828986221515605 ++44: 21835027912963086 ++45: 60978390985918906 ++46: 170508699155987862 ++47: 477355090753926460 ++48: 1337946100045842285 ++49: 3754194185716399992 ++50: 10545233702911509534 ++*******************************/ + + /* Comments on original program by original authors */ + /*==============================================================*/ +@@ -676,7 +681,7 @@ PLUGIN_INIT + } + else if (nv == 2) + { +- if (res == 0 && maxdeg >= 1 && mindiam <= 1 && maxdiam >= 2) ++ if (res == 0 && maxdeg >= 1 && mindiam <= 1 && maxdiam >= 1) + { + par[1] = 0; + par[2] = 1; +-- +2.38.2 + diff --git a/build/pkgs/nauty/spkg-configure.m4 b/build/pkgs/nauty/spkg-configure.m4 index d986105f2e3..4d5bbcf2091 100644 --- a/build/pkgs/nauty/spkg-configure.m4 +++ b/build/pkgs/nauty/spkg-configure.m4 @@ -1,8 +1,12 @@ # We don't use the "converseg" program, but we need to ensure that we # only detect nauty >= 2.6 because we use the digraph6 format from # that version -- and converseg was added in nauty-2.6. +# +# We also don't use the "genposetg" program (added in nauty 2.8) yet. +# We require it here to prepare Sage for the use of the major new features +# added in 2.7 and 2.8 (https://pallini.di.uniroma1.it/changes24-28.txt). AC_DEFUN([SAGE_TEST_NAUTY_PROGS], [ - m4_foreach([nautyprog], [directg, gentourng, geng, genbg, gentreeg, converseg], [ + m4_foreach([nautyprog], [directg, gentourng, geng, genbg, gentreeg, converseg, genposetg], [ AC_PATH_PROG([$2]nautyprog, [[$1]nautyprog]) AS_IF([test x$[$2]nautyprog = x], [sage_spkg_install_nauty=yes]) ]) diff --git a/build/pkgs/nauty/spkg-install.in b/build/pkgs/nauty/spkg-install.in index 6b25ac9d2ea..cf685ba5370 100644 --- a/build/pkgs/nauty/spkg-install.in +++ b/build/pkgs/nauty/spkg-install.in @@ -7,10 +7,10 @@ sdh_make # No install target so we resort to manual copy PROGRAMS=" -addedgeg amtog biplabg catg complg converseg copyg countg cubhamg deledgeg -delptg directg dreadnaut dretodot dretog genbg genbgL geng genquarticg genrang -genspecialg gentourng gentreeg hamheuristic labelg linegraphg listg multig -newedgeg pickg planarg ranlabg shortg showg subdivideg twohamg vcolg +addedgeg addptg amtog ancestorg assembleg biplabg catg complg converseg copyg countg cubhamg deledgeg +delptg dimacs2g directg dreadnaut dretodot dretog edgetransg genbg genbgL geng gengL genposetg genquarticg genrang +genspecialg gentourng gentreeg hamheuristic labelg linegraphg listg multig nbrhoodg +newedgeg pickg planarg productg ranlabg shortg showg subdivideg twohamg underlyingg vcolg watercluster2 NRswitchg" sdh_install $PROGRAMS "$SAGE_LOCAL/bin" diff --git a/build/pkgs/networkx/distros/conda.txt b/build/pkgs/networkx/distros/conda.txt index 67cbec89b21..96b0bbb2845 100644 --- a/build/pkgs/networkx/distros/conda.txt +++ b/build/pkgs/networkx/distros/conda.txt @@ -1 +1 @@ -networkx<3.0,>=2.4 +networkx<3.2,>=2.4 diff --git a/build/pkgs/numpy/checksums.ini b/build/pkgs/numpy/checksums.ini index 886bc13768b..67c13061038 100644 --- a/build/pkgs/numpy/checksums.ini +++ b/build/pkgs/numpy/checksums.ini @@ -1,5 +1,5 @@ tarball=numpy-VERSION.tar.gz -sha1=a3f9d79d7852f5d35ff35693fc31d17ea270d2d0 -md5=69bd28f07afbeed2bb6ecd467afcd469 -cksum=3599108965 +sha1=00f8e85fae2e2ccf8afa78e8da3a058831230ef1 +md5=2d770f4c281d405b690c4bcb3dbe99e2 +cksum=1663231076 upstream_url=https://pypi.io/packages/source/n/numpy/numpy-VERSION.tar.gz diff --git a/build/pkgs/numpy/package-version.txt b/build/pkgs/numpy/package-version.txt index 5ff8c4f5d2a..dd43a143f02 100644 --- a/build/pkgs/numpy/package-version.txt +++ b/build/pkgs/numpy/package-version.txt @@ -1 +1 @@ -1.26.0 +1.26.1 diff --git a/build/pkgs/openssl/checksums.ini b/build/pkgs/openssl/checksums.ini index a443f001e4a..9a4767ed76c 100644 --- a/build/pkgs/openssl/checksums.ini +++ b/build/pkgs/openssl/checksums.ini @@ -1,5 +1,5 @@ tarball=openssl-VERSION.tar.gz -sha1=580d8a7232327fe1fa6e7db54ac060d4321f40ab -md5=61e017cf4fea1b599048f621f1490fbd -cksum=1708357994 +sha1=b48e20c07facfdf6da9ad43a6c5126d51897699b +md5=e6a199cdf867873eef2c6491b674edbc +cksum=391245670 upstream_url=https://www.openssl.org/source/openssl-VERSION.tar.gz diff --git a/build/pkgs/openssl/package-version.txt b/build/pkgs/openssl/package-version.txt index 67786e246ef..f93fc9f42ea 100644 --- a/build/pkgs/openssl/package-version.txt +++ b/build/pkgs/openssl/package-version.txt @@ -1 +1 @@ -3.0.8 +3.0.12 diff --git a/build/pkgs/packaging/checksums.ini b/build/pkgs/packaging/checksums.ini index 83ab122e324..7d9afce62d3 100644 --- a/build/pkgs/packaging/checksums.ini +++ b/build/pkgs/packaging/checksums.ini @@ -1,5 +1,5 @@ tarball=packaging-VERSION.tar.gz -sha1=1245c28c10ae6cb80164f081daece224b6fa89bc -md5=f7d5c39c6f92cc2dfa1293ba8f6c097c -cksum=11867377 +sha1=603cbd6e3416f1f4b6c0f924216f96fe67d9f6da +md5=d54eeff8c7ca86980528f4132f258d54 +cksum=307392791 upstream_url=https://pypi.io/packages/source/p/packaging/packaging-VERSION.tar.gz diff --git a/build/pkgs/packaging/package-version.txt b/build/pkgs/packaging/package-version.txt index a12b18e4372..3c8ce91a469 100644 --- a/build/pkgs/packaging/package-version.txt +++ b/build/pkgs/packaging/package-version.txt @@ -1 +1 @@ -23.1 +23.2 diff --git a/build/pkgs/pari/checksums.ini b/build/pkgs/pari/checksums.ini index d72e5246cf7..b6fc05baa1a 100644 --- a/build/pkgs/pari/checksums.ini +++ b/build/pkgs/pari/checksums.ini @@ -1,5 +1,5 @@ tarball=pari-VERSION.tar.gz -sha1=498e3cd0b7ded8be3fa1cba1125ca5213ed39453 -md5=562a6e973ca3980dc6c1eb2c4f252e92 -cksum=4081416981 +sha1=ae962671b5bf86849d2021113dfb5b2f59331a10 +md5=4ab5c81d93f4bccb94e483b8b48fc336 +cksum=598072677 upstream_url=https://pari.math.u-bordeaux.fr/pub/pari/unix/pari-VERSION.tar.gz diff --git a/build/pkgs/pari/package-version.txt b/build/pkgs/pari/package-version.txt index c06afc0ba5f..86fbeafcc20 100644 --- a/build/pkgs/pari/package-version.txt +++ b/build/pkgs/pari/package-version.txt @@ -1 +1 @@ -2.15.2.p1 +2.15.4 diff --git a/build/pkgs/pari/patches/bug2441.patch b/build/pkgs/pari/patches/bug2441.patch deleted file mode 100644 index 01047180d19..00000000000 --- a/build/pkgs/pari/patches/bug2441.patch +++ /dev/null @@ -1,14 +0,0 @@ -diff --git a/src/basemath/ellsea.c b/src/basemath/ellsea.c -index a6871fa6a7..05f148eadd 100644 ---- a/src/basemath/ellsea.c -+++ b/src/basemath/ellsea.c -@@ -852,7 +852,8 @@ find_isogenous_from_Atkin(GEN a4, GEN a6, ulong ell, struct meqn *MEQN, GEN g, G - GEN a4t, a6t, h; - a4a6t(&a4t, &a6t, ell, E4t, E6t, T, p); - h = find_kernel(a4, a6, ell, a4t, a6t, pp1, T, p, pp, e); -- if (h) return gerepilecopy(ltop, mkvec3(a4t, a6t, h)); -+ if (h && signe(Fq_elldivpolmod(a4, a6, ell, h, T, pp))==0) -+ return gerepilecopy(ltop, mkvec3(a4t, a6t, h)); - } - } - pari_err_BUG("find_isogenous_from_Atkin, kernel not found"); diff --git a/build/pkgs/pari/spkg-configure.m4 b/build/pkgs/pari/spkg-configure.m4 index e1a022a26ab..1404defc518 100644 --- a/build/pkgs/pari/spkg-configure.m4 +++ b/build/pkgs/pari/spkg-configure.m4 @@ -67,6 +67,25 @@ SAGE_SPKG_CONFIGURE([pari], [ AC_MSG_NOTICE([Otherwise Sage will build its own pari/GP.]) sage_spkg_install_pari=yes fi + + AC_MSG_CHECKING([whether factor() bug 2469 of pari 2.15.3 is fixed]) + result=`echo "f=factor(2^2203-1); print(\"ok\")" | timeout 1 $GP -qf` + if test x"$result" = xok; then + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no; cannot use system pari/GP with known bug]) + sage_spkg_install_pari=yes + fi + + AC_MSG_CHECKING([whether qfbclassno() bug 2466 of pari 2.15.3 is fixed]) + result=`echo "qfbclassno(33844)" | $GP -qf` + if test x"$result" = x3; then + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no; cannot use system pari/GP with known bug]) + sage_spkg_install_pari=yes + fi + fi dnl end GP test if test x$sage_spkg_install_pari = xno; then dnl main PARI test diff --git a/build/pkgs/patchelf/distros/conda.txt b/build/pkgs/patchelf/distros/conda.txt deleted file mode 100644 index fca4680084f..00000000000 --- a/build/pkgs/patchelf/distros/conda.txt +++ /dev/null @@ -1 +0,0 @@ -patchelf diff --git a/build/pkgs/pip/checksums.ini b/build/pkgs/pip/checksums.ini index 9b6376d1abb..52c2edb31f2 100644 --- a/build/pkgs/pip/checksums.ini +++ b/build/pkgs/pip/checksums.ini @@ -1,5 +1,5 @@ tarball=pip-VERSION.tar.gz -sha1=4bdfd8e976b5122cf55f4f4740f7305f1ffa4310 -md5=e9b1226701a56ee3fcc81aba60d25d75 -cksum=1940746834 +sha1=d1400a4eb662e4741ac68957f47bc97d600743f8 +md5=f0c9fba61e9d9badcc9921062e993d84 +cksum=309527365 upstream_url=https://pypi.io/packages/source/p/pip/pip-VERSION.tar.gz diff --git a/build/pkgs/pip/install-requires.txt b/build/pkgs/pip/install-requires.txt index 5e76a10f694..25a92d4b832 100644 --- a/build/pkgs/pip/install-requires.txt +++ b/build/pkgs/pip/install-requires.txt @@ -1,3 +1,4 @@ -pip >=22.1 +pip >=23.1.0 # for use of the "in-tree-build" feature, default since 21.3, by the Sage distribution # for use of --config-settings, 22.1 +# for use of -C as a shortcut for --config-settings, 23.1.0 diff --git a/build/pkgs/pip/package-version.txt b/build/pkgs/pip/package-version.txt index 3f833b5b536..a9a57c82265 100644 --- a/build/pkgs/pip/package-version.txt +++ b/build/pkgs/pip/package-version.txt @@ -1 +1 @@ -23.2.1 +23.3.1 diff --git a/build/pkgs/platformdirs/checksums.ini b/build/pkgs/platformdirs/checksums.ini index 288483e8fc2..99113c48626 100644 --- a/build/pkgs/platformdirs/checksums.ini +++ b/build/pkgs/platformdirs/checksums.ini @@ -1,5 +1,5 @@ tarball=platformdirs-VERSION.tar.gz -sha1=c4e0f8486e67a97affbc1b6b267a1f196c4177fa -md5=1c1c8c05e9bc370b78e0a95103523b75 -cksum=4231977838 +sha1=82e215dc9c45eedf9168584fede36d795714f677 +md5=a6ba3a442347fac346982acb597c8bf8 +cksum=2465457023 upstream_url=https://pypi.io/packages/source/p/platformdirs/platformdirs-VERSION.tar.gz diff --git a/build/pkgs/platformdirs/package-version.txt b/build/pkgs/platformdirs/package-version.txt index 30291cba223..afad818663d 100644 --- a/build/pkgs/platformdirs/package-version.txt +++ b/build/pkgs/platformdirs/package-version.txt @@ -1 +1 @@ -3.10.0 +3.11.0 diff --git a/build/pkgs/sage_conf/install-requires.txt b/build/pkgs/sage_conf/install-requires.txt index af1494990e7..1387216d0d4 100644 --- a/build/pkgs/sage_conf/install-requires.txt +++ b/build/pkgs/sage_conf/install-requires.txt @@ -1,2 +1,2 @@ # This file is updated on every release by the sage-update-version script -sage-conf ~= 10.2b8 +sage-conf ~= 10.2b9 diff --git a/build/pkgs/sage_docbuild/install-requires.txt b/build/pkgs/sage_docbuild/install-requires.txt index 3cd4fa3a1cc..530594cb2f7 100644 --- a/build/pkgs/sage_docbuild/install-requires.txt +++ b/build/pkgs/sage_docbuild/install-requires.txt @@ -1,2 +1,2 @@ # This file is updated on every release by the sage-update-version script -sage-docbuild ~= 10.2b8 +sage-docbuild ~= 10.2b9 diff --git a/build/pkgs/sage_setup/install-requires.txt b/build/pkgs/sage_setup/install-requires.txt index 513270bef9b..5a9a50b1773 100644 --- a/build/pkgs/sage_setup/install-requires.txt +++ b/build/pkgs/sage_setup/install-requires.txt @@ -1,2 +1,2 @@ # This file is updated on every release by the sage-update-version script -sage-setup ~= 10.2b8 +sage-setup ~= 10.2b9 diff --git a/build/pkgs/sage_sws2rst/install-requires.txt b/build/pkgs/sage_sws2rst/install-requires.txt index 59a489617cb..8f0dd4150d7 100644 --- a/build/pkgs/sage_sws2rst/install-requires.txt +++ b/build/pkgs/sage_sws2rst/install-requires.txt @@ -1,2 +1,2 @@ # This file is updated on every release by the sage-update-version script -sage-sws2rst ~= 10.2b8 +sage-sws2rst ~= 10.2b9 diff --git a/build/pkgs/sagelib/install-requires.txt b/build/pkgs/sagelib/install-requires.txt index 254cd68ca8b..fe389de2e2e 100644 --- a/build/pkgs/sagelib/install-requires.txt +++ b/build/pkgs/sagelib/install-requires.txt @@ -1,2 +1,2 @@ # This file is updated on every release by the sage-update-version script -sagemath-standard ~= 10.2b8 +sagemath-standard ~= 10.2b9 diff --git a/build/pkgs/sagemath_bliss/install-requires.txt b/build/pkgs/sagemath_bliss/install-requires.txt index eb77a2780ee..dabe7e52643 100644 --- a/build/pkgs/sagemath_bliss/install-requires.txt +++ b/build/pkgs/sagemath_bliss/install-requires.txt @@ -1,2 +1,2 @@ # This file is updated on every release by the sage-update-version script -sagemath-bliss ~= 10.2b8 +sagemath-bliss ~= 10.2b9 diff --git a/build/pkgs/sagemath_categories/install-requires.txt b/build/pkgs/sagemath_categories/install-requires.txt index e087dd7435e..eab5b455322 100644 --- a/build/pkgs/sagemath_categories/install-requires.txt +++ b/build/pkgs/sagemath_categories/install-requires.txt @@ -1,2 +1,2 @@ # This file is updated on every release by the sage-update-version script -sagemath-categories ~= 10.2b8 +sagemath-categories ~= 10.2b9 diff --git a/build/pkgs/sagemath_coxeter3/install-requires.txt b/build/pkgs/sagemath_coxeter3/install-requires.txt index 5fbdb88a3e4..c07ca4d5a32 100644 --- a/build/pkgs/sagemath_coxeter3/install-requires.txt +++ b/build/pkgs/sagemath_coxeter3/install-requires.txt @@ -1,2 +1,2 @@ # This file is updated on every release by the sage-update-version script -sagemath-coxeter3 ~= 10.2b8 +sagemath-coxeter3 ~= 10.2b9 diff --git a/build/pkgs/sagemath_environment/install-requires.txt b/build/pkgs/sagemath_environment/install-requires.txt index 16b0a20b583..7745d13c50c 100644 --- a/build/pkgs/sagemath_environment/install-requires.txt +++ b/build/pkgs/sagemath_environment/install-requires.txt @@ -1,2 +1,2 @@ # This file is updated on every release by the sage-update-version script -sagemath-environment ~= 10.2b8 +sagemath-environment ~= 10.2b9 diff --git a/build/pkgs/sagemath_mcqd/install-requires.txt b/build/pkgs/sagemath_mcqd/install-requires.txt index cc5aee92b75..34d46c650c9 100644 --- a/build/pkgs/sagemath_mcqd/install-requires.txt +++ b/build/pkgs/sagemath_mcqd/install-requires.txt @@ -1,2 +1,2 @@ # This file is updated on every release by the sage-update-version script -sagemath-mcqd ~= 10.2b8 +sagemath-mcqd ~= 10.2b9 diff --git a/build/pkgs/sagemath_meataxe/install-requires.txt b/build/pkgs/sagemath_meataxe/install-requires.txt index 952fc3c6fa8..3012f831c3a 100644 --- a/build/pkgs/sagemath_meataxe/install-requires.txt +++ b/build/pkgs/sagemath_meataxe/install-requires.txt @@ -1,2 +1,2 @@ # This file is updated on every release by the sage-update-version script -sagemath-meataxe ~= 10.2b8 +sagemath-meataxe ~= 10.2b9 diff --git a/build/pkgs/sagemath_objects/install-requires.txt b/build/pkgs/sagemath_objects/install-requires.txt index 1c578b75a97..35022da8fde 100644 --- a/build/pkgs/sagemath_objects/install-requires.txt +++ b/build/pkgs/sagemath_objects/install-requires.txt @@ -1,2 +1,2 @@ # This file is updated on every release by the sage-update-version script -sagemath-objects ~= 10.2b8 +sagemath-objects ~= 10.2b9 diff --git a/build/pkgs/sagemath_repl/install-requires.txt b/build/pkgs/sagemath_repl/install-requires.txt index b2037903a68..4c33d1b3eb0 100644 --- a/build/pkgs/sagemath_repl/install-requires.txt +++ b/build/pkgs/sagemath_repl/install-requires.txt @@ -1,2 +1,2 @@ # This file is updated on every release by the sage-update-version script -sagemath-repl ~= 10.2b8 +sagemath-repl ~= 10.2b9 diff --git a/build/pkgs/sagemath_sirocco/install-requires.txt b/build/pkgs/sagemath_sirocco/install-requires.txt index c62e361e6aa..bd55a958d68 100644 --- a/build/pkgs/sagemath_sirocco/install-requires.txt +++ b/build/pkgs/sagemath_sirocco/install-requires.txt @@ -1,2 +1,2 @@ # This file is updated on every release by the sage-update-version script -sagemath-sirocco ~= 10.2b8 +sagemath-sirocco ~= 10.2b9 diff --git a/build/pkgs/sagemath_tdlib/install-requires.txt b/build/pkgs/sagemath_tdlib/install-requires.txt index 745ea5ccfe1..2e291c70e25 100644 --- a/build/pkgs/sagemath_tdlib/install-requires.txt +++ b/build/pkgs/sagemath_tdlib/install-requires.txt @@ -1,2 +1,2 @@ # This file is updated on every release by the sage-update-version script -sagemath-tdlib ~= 10.2b8 +sagemath-tdlib ~= 10.2b9 diff --git a/build/pkgs/sagenb_export/install-requires.txt b/build/pkgs/sagenb_export/install-requires.txt index 0592ab651b1..9c94d6990d1 100644 --- a/build/pkgs/sagenb_export/install-requires.txt +++ b/build/pkgs/sagenb_export/install-requires.txt @@ -1 +1 @@ -sagenb_export >=3.3 +git+https://github.com/vbraun/ExportSageNB.git#egg=sagenb_export diff --git a/build/pkgs/scipy/distros/conda.txt b/build/pkgs/scipy/distros/conda.txt index 21b2670008a..175cd197f8c 100644 --- a/build/pkgs/scipy/distros/conda.txt +++ b/build/pkgs/scipy/distros/conda.txt @@ -1 +1 @@ -scipy<1.11,>=1.5 +scipy<1.12,>=1.5 diff --git a/build/pkgs/wheel/checksums.ini b/build/pkgs/wheel/checksums.ini index b01f275c477..b12a1973b0c 100644 --- a/build/pkgs/wheel/checksums.ini +++ b/build/pkgs/wheel/checksums.ini @@ -1,5 +1,5 @@ tarball=wheel-VERSION.tar.gz -sha1=ff9a5efeabf8e73e8b1a8646eaa829154f834726 -md5=83bb4e7bd4d687d398733f341a64ab91 -cksum=518943238 +sha1=34a787f7069762e267e5ed62ed31cc9c87ea910b +md5=06271a9e90c948b7e93dd7ce0fd90272 +cksum=444550709 upstream_url=https://pypi.io/packages/source/w/wheel/wheel-VERSION.tar.gz diff --git a/build/pkgs/wheel/package-version.txt b/build/pkgs/wheel/package-version.txt index 87f0b954e35..6599454d402 100644 --- a/build/pkgs/wheel/package-version.txt +++ b/build/pkgs/wheel/package-version.txt @@ -1 +1 @@ -0.38.4 +0.41.2 diff --git a/pkgs/sage-conf/VERSION.txt b/pkgs/sage-conf/VERSION.txt index 66f8b2a93e1..d0cd2bc56e3 100644 --- a/pkgs/sage-conf/VERSION.txt +++ b/pkgs/sage-conf/VERSION.txt @@ -1 +1 @@ -10.2.beta8 +10.2.beta9 diff --git a/pkgs/sage-conf_conda/VERSION.txt b/pkgs/sage-conf_conda/VERSION.txt index 66f8b2a93e1..d0cd2bc56e3 100644 --- a/pkgs/sage-conf_conda/VERSION.txt +++ b/pkgs/sage-conf_conda/VERSION.txt @@ -1 +1 @@ -10.2.beta8 +10.2.beta9 diff --git a/pkgs/sage-conf_pypi/VERSION.txt b/pkgs/sage-conf_pypi/VERSION.txt index 66f8b2a93e1..d0cd2bc56e3 100644 --- a/pkgs/sage-conf_pypi/VERSION.txt +++ b/pkgs/sage-conf_pypi/VERSION.txt @@ -1 +1 @@ -10.2.beta8 +10.2.beta9 diff --git a/pkgs/sage-docbuild/VERSION.txt b/pkgs/sage-docbuild/VERSION.txt index 66f8b2a93e1..d0cd2bc56e3 100644 --- a/pkgs/sage-docbuild/VERSION.txt +++ b/pkgs/sage-docbuild/VERSION.txt @@ -1 +1 @@ -10.2.beta8 +10.2.beta9 diff --git a/pkgs/sage-setup/VERSION.txt b/pkgs/sage-setup/VERSION.txt index 66f8b2a93e1..d0cd2bc56e3 100644 --- a/pkgs/sage-setup/VERSION.txt +++ b/pkgs/sage-setup/VERSION.txt @@ -1 +1 @@ -10.2.beta8 +10.2.beta9 diff --git a/pkgs/sage-sws2rst/VERSION.txt b/pkgs/sage-sws2rst/VERSION.txt index 66f8b2a93e1..d0cd2bc56e3 100644 --- a/pkgs/sage-sws2rst/VERSION.txt +++ b/pkgs/sage-sws2rst/VERSION.txt @@ -1 +1 @@ -10.2.beta8 +10.2.beta9 diff --git a/pkgs/sagemath-bliss/MANIFEST.in b/pkgs/sagemath-bliss/MANIFEST.in index 6d981b9d30e..2572c2b46f7 100644 --- a/pkgs/sagemath-bliss/MANIFEST.in +++ b/pkgs/sagemath-bliss/MANIFEST.in @@ -1,6 +1,9 @@ +prune sage + include VERSION.txt graft sage/graphs/bliss_cpp +include sage/graphs/bliss.p* global-exclude *.c global-exclude *.cpp diff --git a/pkgs/sagemath-bliss/VERSION.txt b/pkgs/sagemath-bliss/VERSION.txt index 66f8b2a93e1..d0cd2bc56e3 100644 --- a/pkgs/sagemath-bliss/VERSION.txt +++ b/pkgs/sagemath-bliss/VERSION.txt @@ -1 +1 @@ -10.2.beta8 +10.2.beta9 diff --git a/pkgs/sagemath-categories/VERSION.txt b/pkgs/sagemath-categories/VERSION.txt index 66f8b2a93e1..d0cd2bc56e3 100644 --- a/pkgs/sagemath-categories/VERSION.txt +++ b/pkgs/sagemath-categories/VERSION.txt @@ -1 +1 @@ -10.2.beta8 +10.2.beta9 diff --git a/pkgs/sagemath-coxeter3/VERSION.txt b/pkgs/sagemath-coxeter3/VERSION.txt index 66f8b2a93e1..d0cd2bc56e3 100644 --- a/pkgs/sagemath-coxeter3/VERSION.txt +++ b/pkgs/sagemath-coxeter3/VERSION.txt @@ -1 +1 @@ -10.2.beta8 +10.2.beta9 diff --git a/pkgs/sagemath-environment/VERSION.txt b/pkgs/sagemath-environment/VERSION.txt index 66f8b2a93e1..d0cd2bc56e3 100644 --- a/pkgs/sagemath-environment/VERSION.txt +++ b/pkgs/sagemath-environment/VERSION.txt @@ -1 +1 @@ -10.2.beta8 +10.2.beta9 diff --git a/pkgs/sagemath-mcqd/VERSION.txt b/pkgs/sagemath-mcqd/VERSION.txt index 66f8b2a93e1..d0cd2bc56e3 100644 --- a/pkgs/sagemath-mcqd/VERSION.txt +++ b/pkgs/sagemath-mcqd/VERSION.txt @@ -1 +1 @@ -10.2.beta8 +10.2.beta9 diff --git a/pkgs/sagemath-meataxe/VERSION.txt b/pkgs/sagemath-meataxe/VERSION.txt index 66f8b2a93e1..d0cd2bc56e3 100644 --- a/pkgs/sagemath-meataxe/VERSION.txt +++ b/pkgs/sagemath-meataxe/VERSION.txt @@ -1 +1 @@ -10.2.beta8 +10.2.beta9 diff --git a/pkgs/sagemath-objects/VERSION.txt b/pkgs/sagemath-objects/VERSION.txt index 66f8b2a93e1..d0cd2bc56e3 100644 --- a/pkgs/sagemath-objects/VERSION.txt +++ b/pkgs/sagemath-objects/VERSION.txt @@ -1 +1 @@ -10.2.beta8 +10.2.beta9 diff --git a/pkgs/sagemath-repl/VERSION.txt b/pkgs/sagemath-repl/VERSION.txt index 66f8b2a93e1..d0cd2bc56e3 100644 --- a/pkgs/sagemath-repl/VERSION.txt +++ b/pkgs/sagemath-repl/VERSION.txt @@ -1 +1 @@ -10.2.beta8 +10.2.beta9 diff --git a/pkgs/sagemath-sirocco/MANIFEST.in b/pkgs/sagemath-sirocco/MANIFEST.in index 815a868524d..8ac89baa796 100644 --- a/pkgs/sagemath-sirocco/MANIFEST.in +++ b/pkgs/sagemath-sirocco/MANIFEST.in @@ -1,5 +1,9 @@ +prune sage + include VERSION.txt +include sage/libs/sirocco.p* + global-exclude *.c global-exclude *.cpp diff --git a/pkgs/sagemath-sirocco/VERSION.txt b/pkgs/sagemath-sirocco/VERSION.txt index 66f8b2a93e1..d0cd2bc56e3 100644 --- a/pkgs/sagemath-sirocco/VERSION.txt +++ b/pkgs/sagemath-sirocco/VERSION.txt @@ -1 +1 @@ -10.2.beta8 +10.2.beta9 diff --git a/pkgs/sagemath-tdlib/MANIFEST.in b/pkgs/sagemath-tdlib/MANIFEST.in index 614186d89ab..156e1c3b85a 100644 --- a/pkgs/sagemath-tdlib/MANIFEST.in +++ b/pkgs/sagemath-tdlib/MANIFEST.in @@ -1,9 +1,12 @@ +prune sage + include VERSION.txt global-exclude *.c global-exclude *.cpp include sage/graphs/graph_decompositions/sage_tdlib.cpp +include sage/graphs/graph_decompositions/tdlib.p* global-exclude all__sagemath_*.* global-include all__sagemath_tdlib.py diff --git a/pkgs/sagemath-tdlib/VERSION.txt b/pkgs/sagemath-tdlib/VERSION.txt index 66f8b2a93e1..d0cd2bc56e3 100644 --- a/pkgs/sagemath-tdlib/VERSION.txt +++ b/pkgs/sagemath-tdlib/VERSION.txt @@ -1 +1 @@ -10.2.beta8 +10.2.beta9 diff --git a/src/MANIFEST.in b/src/MANIFEST.in index bbed8838199..07a135dbf07 100644 --- a/src/MANIFEST.in +++ b/src/MANIFEST.in @@ -49,6 +49,7 @@ prune sage/graphs/bliss_cpp prune sage/libs/coxeter3 exclude sage/graphs/mcqd.p* exclude sage/libs/meataxe.p* +exclude sage/libs/sirocco.p* exclude sage/matrix/matrix_gfpn_dense.p* exclude sage/graphs/graph_decomposition/tdlib.p* diff --git a/src/VERSION.txt b/src/VERSION.txt index 66f8b2a93e1..d0cd2bc56e3 100644 --- a/src/VERSION.txt +++ b/src/VERSION.txt @@ -1 +1 @@ -10.2.beta8 +10.2.beta9 diff --git a/src/bin/sage-notebook b/src/bin/sage-notebook index 2e8b12e1a1c..801b0a6a6a3 100755 --- a/src/bin/sage-notebook +++ b/src/bin/sage-notebook @@ -29,7 +29,12 @@ class NotebookJupyter(): def __init__(self, argv): self.print_banner() try: - from notebook.notebookapp import main + try: + # notebook 6 + from notebook.notebookapp import main + except ImportError: + # notebook 7 + from notebook.app import main except ImportError: import traceback traceback.print_exc() diff --git a/src/bin/sage-version.sh b/src/bin/sage-version.sh index e627d6e96d2..392f585e5de 100644 --- a/src/bin/sage-version.sh +++ b/src/bin/sage-version.sh @@ -4,6 +4,6 @@ # which stops "setup.py develop" from rewriting it as a Python file. : # This file is auto-generated by the sage-update-version script, do not edit! -SAGE_VERSION='10.2.beta8' -SAGE_RELEASE_DATE='2023-10-21' -SAGE_VERSION_BANNER='SageMath version 10.2.beta8, Release Date: 2023-10-21' +SAGE_VERSION='10.2.beta9' +SAGE_RELEASE_DATE='2023-10-30' +SAGE_VERSION_BANNER='SageMath version 10.2.beta9, Release Date: 2023-10-30' diff --git a/src/doc/common/static/custom-codemirror-monokai.css b/src/doc/common/static/custom-codemirror-monokai.css new file mode 100644 index 00000000000..3489e3d61e5 --- /dev/null +++ b/src/doc/common/static/custom-codemirror-monokai.css @@ -0,0 +1,42 @@ +/* from https://codemirror.net/5/theme/monokai.css */ +/* Based on Sublime Text's Monokai theme */ + +.cm-s-monokai.CodeMirror { background: #272822; color: #f8f8f2; } +.cm-s-monokai div.CodeMirror-selected { background: #49483E; } +.cm-s-monokai .CodeMirror-line::selection, .cm-s-monokai .CodeMirror-line > span::selection, .cm-s-monokai .CodeMirror-line > span > span::selection { background: rgba(73, 72, 62, .99); } +.cm-s-monokai .CodeMirror-line::-moz-selection, .cm-s-monokai .CodeMirror-line > span::-moz-selection, .cm-s-monokai .CodeMirror-line > span > span::-moz-selection { background: rgba(73, 72, 62, .99); } +.cm-s-monokai .CodeMirror-gutters { background: #272822; border-right: 0px; } +.cm-s-monokai .CodeMirror-guttermarker { color: white; } +.cm-s-monokai .CodeMirror-guttermarker-subtle { color: #d0d0d0; } +.cm-s-monokai .CodeMirror-linenumber { color: #d0d0d0; } +.cm-s-monokai .CodeMirror-cursor { border-left: 1px solid #f8f8f0; } + +.cm-s-monokai span.cm-comment { color: #75715e; } +.cm-s-monokai span.cm-atom { color: #ae81ff; } +.cm-s-monokai span.cm-number { color: #ae81ff; } + +.cm-s-monokai span.cm-comment.cm-attribute { color: #97b757; } +.cm-s-monokai span.cm-comment.cm-def { color: #bc9262; } +.cm-s-monokai span.cm-comment.cm-tag { color: #bc6283; } +.cm-s-monokai span.cm-comment.cm-type { color: #5998a6; } + +.cm-s-monokai span.cm-property, .cm-s-monokai span.cm-attribute { color: #a6e22e; } +.cm-s-monokai span.cm-keyword { color: #f92672; } +.cm-s-monokai span.cm-builtin { color: #66d9ef; } +.cm-s-monokai span.cm-string { color: #e6db74; } + +.cm-s-monokai span.cm-variable { color: #f8f8f2; } +.cm-s-monokai span.cm-variable-2 { color: #9effff; } +.cm-s-monokai span.cm-variable-3, .cm-s-monokai span.cm-type { color: #66d9ef; } +.cm-s-monokai span.cm-def { color: #fd971f; } +.cm-s-monokai span.cm-bracket { color: #f8f8f2; } +.cm-s-monokai span.cm-tag { color: #f92672; } +.cm-s-monokai span.cm-header { color: #ae81ff; } +.cm-s-monokai span.cm-link { color: #ae81ff; } +.cm-s-monokai span.cm-error { background: #f92672; color: #f8f8f0; } + +.cm-s-monokai .CodeMirror-activeline-background { background: #373831; } +.cm-s-monokai .CodeMirror-matchingbracket { + text-decoration: underline; + color: white !important; +} diff --git a/src/doc/common/static/custom-jupyter-sphinx.css b/src/doc/common/static/custom-jupyter-sphinx.css new file mode 100644 index 00000000000..a68a5cb05aa --- /dev/null +++ b/src/doc/common/static/custom-jupyter-sphinx.css @@ -0,0 +1,140 @@ +div.jupyter_container { + margin: .5rem 0; +} + +div.jupyter_container + div.jupyter_container { + margin: 0 0 .5rem 0; +} + +div.jupyter_container div.cell_input pre { + margin: .5rem; +} + +div.jupyter_container div.cell_output div.output { + margin: .5rem; +} + +.thebelab-cell .jp-OutputArea { + margin: 0 .5rem; +} + +.thebelab-cell .jp-OutputArea-output { + margin: 0 0 .5rem 0; + overflow-x: auto; +} + +.thebelab-button { + margin: .5rem 0 .5rem .5rem; + padding: 0 .5rem; + min-width: 2rem; +} + +.thebelab-button:active { + color: #0f0fff; +} + +.thebelab-busy { + margin-left: .5rem; +} + +#thebelab-activate-button { + position: fixed; + right: -5.1rem; + top: calc(50% - 1.5rem); + width: 6rem; + border-radius: 1rem; + transition-property: right; + transition-duration: 300ms; + transition-timing-function: ease-out; + z-index: 100; +} + +#thebelab-activate-button:hover { + right: .4rem; +} + +#thebelab-activate-button:active { + color: #0f0fff; +} + +body[data-theme="dark"] { + .jupyter_container { + color: white; + background-color: black; + } + + .jupyter_container .highlight { + background-color: black; + } + + .thebelab-button { + color: #d0d0d0; + background-color: #383838; + } + + .thebelab-button:active { + color: #368ce2; + } + + #thebelab-activate-button { + background-color: #383838; + } + + #thebelab-activate-button:active { + color: #368ce2; + } + + .thebelab-cell .jp-OutputArea-output { + color: white; + background-color: black; + } + + .thebelab-cell .jp-OutputArea-output pre { + color: white; + background-color: black; + } +} + +@media (prefers-color-scheme: dark) { + body[data-theme="auto"] { /* the same styles with body[data-theme="dark"] */ + .jupyter_container { + color: white; + background-color: black; + } + + .jupyter_container .highlight { + background-color: black; + } + + .thebelab-button { + color: #d0d0d0; + background-color: #383838; + } + + .thebelab-button:active { + color: #368ce2; + } + + #thebelab-activate-button { + background-color: #383838; + } + + #thebelab-activate-button:active { + color: #368ce2; + } + + .thebelab-cell .jp-OutputArea-output { + color: white; + background-color: black; + } + + .thebelab-cell .jp-OutputArea-output pre { + color: white; + background-color: black; + } + } +} + + + + diff --git a/src/doc/common/static/jupyter-sphinx-furo.js b/src/doc/common/static/jupyter-sphinx-furo.js new file mode 100644 index 00000000000..5194ff470fc --- /dev/null +++ b/src/doc/common/static/jupyter-sphinx-furo.js @@ -0,0 +1,114 @@ +// Change the editor theme according to the furo light/dark/auto mode +function changeTheme(editor, theme) { + if (theme === 'dark') { + editor.setOption('theme', 'monokai'); // the same with pygments dark style in conf.py + } else if (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches) { + editor.setOption('theme', 'monokai'); + } else { + editor.setOption('theme', 'default'); + } +} + +// Change the editor theme of all CodeMirror cells +function changeThemeAll(theme) { + const querySet = document.querySelectorAll('.CodeMirror'); + for (var i = 0; i < querySet.length; i++) { + changeTheme(querySet[i].CodeMirror, theme); + } +} + +// Use the theme data of the body element set by setTheme function +// defined in https://github.com/pradyunsg/furo/blob/main/src/furo/assets/scripts/furo.js +const body = document.body; +const observer1 = new MutationObserver((mutationsList) => { + for (let mutation of mutationsList) { + if (mutation.type === 'attributes' && mutation.attributeName === 'data-theme') { + const theme = body.dataset.theme; + changeThemeAll(theme); + } + } +}); +observer1.observe(body, { attributes: true }); + + +// In the furo auto mode, we watch prefers-color-scheme and use the theme data +// of the body element to change the CodeMirror editor theme +const prefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)'); + +function handlePrefersColorSchemeChange(e) { + const theme = body.dataset.theme; + if (theme === 'auto') { + changeThemeAll(theme); + } +} + +prefersDarkMode.addEventListener('change', handlePrefersColorSchemeChange); + + +// Change the editor theme of a new CodeMirror cell. +const callback = function(mutationsList, observer) { + for(const mutation of mutationsList) { + if (mutation.type === 'childList') { + const theme = body.dataset.theme; + for (const addedNode of mutation.addedNodes) { + if (addedNode.classList && addedNode.classList.contains('CodeMirror')) { + changeTheme(addedNode.CodeMirror, theme); + }}}}}; +const observer2 = new MutationObserver(callback); +observer2.observe(document.getElementsByClassName("content")[0], { childList: true, subtree: true }); + + +// Listen to the kernel status changes +// https://thebe.readthedocs.io/en/stable/events.html +thebelab.on("status", function (evt, data) { + if (data.status === 'building') { + const elements = document.querySelectorAll('.thebelab-cell'); + elements.forEach(element => { + element.style.filter = 'opacity(50%)'; + }); + const element = document.getElementById("thebelab-activate-button"); + element.innerHTML = "Building"; + element.style.right = '.4rem'; + } + else if (data.status === 'built') { + const elements = document.querySelectorAll('.thebelab-cell'); + elements.forEach(element => { + element.style.filter = 'opacity(60%)'; + }); + const element = document.getElementById("thebelab-activate-button"); + element.innerHTML = "Built"; + element.style.right = '.4rem'; + } + else if (data.status === 'launching') { + const elements = document.querySelectorAll('.thebelab-cell'); + elements.forEach(element => { + element.style.filter = 'opacity(70%)'; + }); + const element = document.getElementById("thebelab-activate-button"); + element.innerHTML = "Launching"; + element.style.right = '.4rem'; + } + else if (data.status === 'failed') { + const elements = document.querySelectorAll('.thebelab-cell'); + elements.forEach(element => { + element.style.filter = 'opacity(50%)'; + }); + const element = document.getElementById("thebelab-activate-button"); + element.innerHTML = 'Failed: ' + data.message; + element.style.right = '.4rem'; + element.style.width = 'auto'; + element.style.color = 'red'; + } + else if (data.status === 'ready') { + const elements = document.querySelectorAll('.thebelab-cell'); + elements.forEach(element => { + element.style.filter = 'opacity(100%)'; + }); + const element = document.getElementById("thebelab-activate-button"); + element.innerHTML = "Ready"; + element.style.right = null; + // Run custom code when the kernel is ready + const kernel = data.kernel; + kernel.requestExecute({code: "%display latex"}); + } +}); diff --git a/src/doc/common/static/thebe-sage.js b/src/doc/common/static/thebe-sage.js deleted file mode 100644 index 567e3488802..00000000000 --- a/src/doc/common/static/thebe-sage.js +++ /dev/null @@ -1,147 +0,0 @@ -/** - * @overview - * This file aims at replacing the document's Sage code blocks by executable - * notebook cells. Users are presented a dedicated button in the top right - * corner. When they click on it, each code block is appended a "Run" button - * to execute the corresponding code. - * - * This is based on the Thebe library (https://github.com/oreillymedia/thebe/) - * installed in ${SAGE_ROOT}/local/share/thebe/thebe.js by Sage's thebe package. - */ - -$(function() { - - /** - * Build and return the Thebe instance that will communicate with the - * Jupyter notebook (or tmpnb server). - * - * This function categorizes the cells lines into "code" and "result" - * categories to refine the given cell selector and pass only the code - * lines to Thebe. - * - * @param {String} cellSelector - A jQuery selector that matches the cells - * @param {Object} thebeOptions - Thebe options, must not contain "selector" - */ - function setupThebeSage(cellSelector, thebeOptions) { - var lineClass = 'sage-cell-line', - codeClass = 'sage-code', - codeBlockClass = 'sage-code-block', - resultClass = 'sage-expected-result', - resultBlockClass = 'sage-expect-result-block'; - $(cellSelector).each(function() { - wrapEachCellLine(this, lineClass); - categorizeCellLines(this, lineClass, codeClass, resultClass); - wrapLineBlocks(this, lineClass, codeClass, codeBlockClass); - wrapLineBlocks(this, lineClass, resultClass, resultBlockClass); - $('.' + resultBlockClass, this).hide(); - sanitizeCode(this, codeClass); - }); - thebeOptions.selector = '.' + codeBlockClass; - return new Thebe(thebeOptions); - } - - /** - * Sanitize the code before executing. For now, transforms the code line - * into pure text, also stripping out the Sage prompts and continuation - * characters at line start, if any. - * - * @param {Element} cellNode - The DOM element of the cell - * @param {String} codeClass - The class name associated to code line - */ - function sanitizeCode(cellNode, codeClass) { - var rgx = /^(sage: )|(\.\.\.\.: )|(\.\.\. )/; - var codeLines = cellNode.getElementsByClassName(codeClass); - Array.prototype.forEach.call(codeLines, function(line) { - line.textContent = line.textContent.replace(rgx, ''); - }); - } - - /** - * Wrap consecutive lines of the same type in a given cell in line blocks. - * - * @param {Element} cellNode - The DOM element of the cell - * @param {String} lineClass - The class name that identifies all cell lines - * @param {String} specificClass - The class name that identifies the lines - * to be wrapped - * @param {String} blockClass - The class name to be given to the add - * wrapper blocks - */ - function wrapLineBlocks(cellNode, lineClass, specificClass, blockClass) { - var wrapper, - lines = cellNode.getElementsByClassName(lineClass); - Array.prototype.forEach.call(lines, function(line) { - if (line.classList.contains(specificClass)) { - if (! wrapper) { - wrapper = document.createElement('span'); - wrapper.classList.add(blockClass); - cellNode.insertBefore(wrapper, line); - } - wrapper.appendChild(line); - } else { - wrapper = null; - } - }); - } - - /** - * Add a class on each line of a cell to categorize them as code or result. - * - * @param {Element} cellNode - The DOM element of the cell to categorize the - * lines of - * @param {String} lineClass - A class name to identify each cell line - * @param {String} codeClass - A class name to be added on code lines - * @param {String} resultClass - A class name to be added on result lines - */ - function categorizeCellLines(cellNode, lineClass, codeClass, resultClass) { - var lines = cellNode.getElementsByClassName(lineClass); - var previousCategory; - Array.prototype.forEach.call(lines, function(line) { - var lineText = line.textContent; - if (lineText.startsWith('sage: ')) { - line.classList.add(codeClass); - previousCategory = 'code'; - return; - } - if (previousCategory === 'code' - && (lineText.startsWith('....: ') - || lineText.startsWith('... '))) { - line.classList.add(codeClass); - return; - } - line.classList.add(resultClass); - previousCategory = 'result'; - }); - } - - /** - * Add a (span) DOM element around each line of an executable cell - * - * @param {Element} cellNode - cell to wrap the lines of - * @param {String} lineClass - class attribute value for the added span tags - */ - function wrapEachCellLine(cellNode, lineClass) { - var html = ''; - cellNode.innerHTML.split('\n').forEach(function(htmlLine) { - html += '' + htmlLine + '\n'; - }); - cellNode.innerHTML = html; - } - - if (window.location.protocol.startsWith('http')) { - var cellSelector = "pre:contains('sage: ')"; - if ($(cellSelector).length > 0) { - $('') - .css({position: 'absolute', right: 0}) - .click(function() { - setupThebeSage(cellSelector, { - tmpnb_mode: false, - load_css: false, - url: window.location.origin, - kernel_name: "sagemath" - }); - $(this).attr('disabled', 'disabled'); - }) - .prependTo('div.body'); - } - } -}); diff --git a/src/doc/common/themes/sage-classic/layout.html b/src/doc/common/themes/sage-classic/layout.html index ab9a05261aa..1cea7f178a9 100644 --- a/src/doc/common/themes/sage-classic/layout.html +++ b/src/doc/common/themes/sage-classic/layout.html @@ -17,8 +17,6 @@ {% block extrahead %} - - {% endblock %} {%- block footer %} diff --git a/src/doc/en/a_tour_of_sage/index.rst b/src/doc/en/a_tour_of_sage/index.rst index 15e9d2aae46..8f638378130 100644 --- a/src/doc/en/a_tour_of_sage/index.rst +++ b/src/doc/en/a_tour_of_sage/index.rst @@ -1,38 +1,35 @@ .. _a-tour-of-sage: -========================= -Welcome to a Tour of Sage -========================= +=============== +Welcome to Sage +=============== -This is a tour of Sage that closely follows the tour of Mathematica -that is at the beginning of the Mathematica Book. +This is a short tour of Sage as a calculator. - -Sage as a Calculator -==================== - -The Sage command line has a ``sage:`` prompt; you do not have to add -it. If you use the Sage notebook, then put everything after the -``sage:`` prompt in an input cell, and press shift-enter to compute the -corresponding output. +The Sage command line has a prompt "``sage:``". To experiment with the +following examples, you only enter the part after the prompt. :: sage: 3 + 5 8 +If you use Sage on the Jupyter notebook, then likewise put everything after the +prompt in an input cell, and press :kbd:`Shift-Enter` to get the corresponding +output. + The caret symbol means "raise to a power". :: - sage: 57.1 ^ 100 + sage: 57.1^100 4.60904368661396e175 We compute the inverse of a :math:`2 \times 2` matrix in Sage. :: - sage: matrix([[1,2], [3,4]])^(-1) + sage: matrix([[1, 2], [3, 4]])^(-1) [ -2 1] [ 3/2 -1/2] @@ -41,11 +38,11 @@ Here we integrate a simple function. :: sage: x = var('x') # create a symbolic variable - sage: integrate(sqrt(x)*sqrt(1+x), x) - 1/4*((x + 1)^(3/2)/x^(3/2) + sqrt(x + 1)/sqrt(x))/((x + 1)^2/x^2 - 2*(x + 1)/x + 1) - 1/8*log(sqrt(x + 1)/sqrt(x) + 1) + 1/8*log(sqrt(x + 1)/sqrt(x) - 1) + sage: integrate(sqrt(x) * sqrt(1 + x), x) + 1/4*((x + 1)^(3/2)/x^(3/2) + sqrt(x + 1)/sqrt(x))/((x + 1)^2/x^2 - 2*(x + 1)/x + 1) + - 1/8*log(sqrt(x + 1)/sqrt(x) + 1) + 1/8*log(sqrt(x + 1)/sqrt(x) - 1) -This asks Sage to solve a quadratic equation. The symbol ``==`` -represents equality in Sage. +This asks Sage to solve a quadratic equation. The symbol ``==`` represents equality in Sage. :: @@ -59,10 +56,10 @@ The result is a list of equalities. :: - sage: S[0].rhs() + sage: S[0].rhs() # right hand side of the equation -1/2*sqrt(4*a + 1) - 1/2 -Naturally, Sage can plot various useful functions. +Sage can plot various useful functions, of course. :: @@ -71,39 +68,39 @@ Naturally, Sage can plot various useful functions. .. image:: sin_plot.* -Power Computing with Sage -========================= - -First we create a :math:`500 \times 500` matrix of random -numbers. +Sage is a very powerful calculator. To experience it, first we create a :math:`500 \times 500` +matrix of random numbers. :: - sage: m = random_matrix(RDF,500) + sage: m = random_matrix(RDF, 500) -It takes Sage a few seconds to compute the eigenvalues of the -matrix and plot them. +It takes Sage a second to compute the eigenvalues of the matrix and plot them. .. link :: - sage: e = m.eigenvalues() #about 2 seconds + sage: e = m.eigenvalues() # about 1 second sage: w = [(i, abs(e[i])) for i in range(len(e))] sage: show(points(w)) .. image:: eigen_plot.* -Thanks to the GNU Multiprecision Library (GMP), Sage can handle -very large numbers, even numbers with millions or billions of +Sage can handle very large numbers, even numbers with millions or billions of digits. :: sage: factorial(100) 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 - sage: n = factorial(1000000) #about 2.5 seconds + +:: + + sage: n = factorial(1000000) # about 1 second + sage: len(n.digits()) + 5565709 This computes at least 100 digits of :math:`\pi`. @@ -131,17 +128,13 @@ This asks Sage to factor a polynomial in two variables. sage: F.expand() x^99 + y^99 -Sage takes just under 5 seconds to compute the numbers of ways to -partition one hundred million as a sum of positive integers. +Sage takes less than 1 second to compute the numbers of ways to partition one +hundred million as a sum of positive integers. :: - sage: z = Partitions(10^8).cardinality() #about 4.5 seconds - sage: str(z)[:40] - '1760517045946249141360373894679135204009' - -Accessing Algorithms in Sage -============================ + sage: z = Partitions(10^8).cardinality() # about .1 second + sage: z + 1760517045946249141360373894679135204009... -Whenever you use Sage you are accessing one of the world's largest -collections of open source computational algorithms. +Sage is the world's most advanced open source math software. diff --git a/src/doc/en/developer/packaging_sage_library.rst b/src/doc/en/developer/packaging_sage_library.rst index abda71bbed8..0244d96e5ac 100644 --- a/src/doc/en/developer/packaging_sage_library.rst +++ b/src/doc/en/developer/packaging_sage_library.rst @@ -190,9 +190,6 @@ The technique of using symbolic links pointing into ``SAGE_ROOT/src`` has allowed the modularization effort to keep the ``SAGE_ROOT/src`` tree monolithic: Modularization has been happening behind the scenes and will not change where Sage developers find the source files. -When adding a new distribution package that uses a symbolic link pointing into -``SAGE_ROOT/src``, please update ``search.exclude`` in -``SAGE_ROOT/.vscode/settings.json``. Some of these files may actually be generated from source files with suffix ``.m4`` by the ``SAGE_ROOT/bootstrap`` script via the ``m4`` macro processor. @@ -472,6 +469,17 @@ requiring all of Sage to be present. mechanism mentioned above can also be used for this. +Dependencies of the Sage documentation +-------------------------------------- + +The documentation will not be modularized. + +However, some parts of the Sage reference manual may depend on functionality +provided by optional packages. These portions of the reference manual +should be conditionalized using the Sphinx directive ``.. ONLY::``, +as explained in :ref:`section-documentation-conditional`. + + Version constraints of dependencies ----------------------------------- diff --git a/src/doc/en/developer/sage_manuals.rst b/src/doc/en/developer/sage_manuals.rst index 30e8114175d..578419384c7 100644 --- a/src/doc/en/developer/sage_manuals.rst +++ b/src/doc/en/developer/sage_manuals.rst @@ -166,6 +166,32 @@ procedure is different: * Add your file to the index contained in ``SAGE_ROOT/src/doc/en/reference/combinat/module_list.rst``. +.. _section-documentation-conditional: + +Making portions of the reference manual conditional on optional features +======================================================================== + +For every dynamically detectable feature such as :class:`graphviz +<~sage.features.graphviz.Graphviz>` or :class:`sage.symbolic +` (see :mod:`sage.features`), +Sage defines a Sphinx tag that can be used with the `Sphinx +directive ".. ONLY::" +`_. +Because Sphinx tags have to use Python identifier syntax, Sage uses +the format ``feature_``, followed by the feature name where dots are +replaced by underscores. Hence, conditionalizing on the features of +the previous examples would look as follows: + +.. CODE-BLOCK:: rest + + .. ONLY:: feature_graphviz + +and: + +.. CODE-BLOCK:: rest + + .. ONLY:: feature_sage_symbolic + .. _section-building-manuals: Building the manuals diff --git a/src/doc/en/developer/tools.rst b/src/doc/en/developer/tools.rst index 20878a6175d..fca5d5ef4c1 100644 --- a/src/doc/en/developer/tools.rst +++ b/src/doc/en/developer/tools.rst @@ -327,7 +327,10 @@ Pyright - Tox: Run ``./sage -tox -e pyright path/to/the/file.py`` -- Manual: Run ``pyright path/to/the/file.py`` +- Manual: Run ``pyright path/to/the/file.py``. If you want to check the whole Sage library, you most likely run out of memory with the default settings. + You can use the following command to check the whole library:: + + NODE_OPTIONS="--max-old-space-size=8192" pyright - VS Code: Install the `Pylance `__ extension. diff --git a/src/doc/en/installation/binary.rst b/src/doc/en/installation/binary.rst index 5fcce7d5943..4943245a845 100644 --- a/src/doc/en/installation/binary.rst +++ b/src/doc/en/installation/binary.rst @@ -1,6 +1,6 @@ .. _sec-installation-from-binaries: -Install from Pre-built Binaries +Install from Pre-Built Binaries =============================== Linux diff --git a/src/doc/en/installation/index.rst b/src/doc/en/installation/index.rst index 9baf654f457..50d0af27341 100644 --- a/src/doc/en/installation/index.rst +++ b/src/doc/en/installation/index.rst @@ -127,16 +127,17 @@ Linux In the cloud ============ -- `CoCalc `_: an online service that provides SageMath and - many other tools. +- `Sage Binder repo `_ provides a + Binder badge to launch JupyterLab environment with Sage. + +- `Sage Cell Server `_ is a free online service for + quick computations with Sage. -- On any system that allows you to bring your own Docker images to run - in a container: Use the `Docker image sagemathinc/cocalc - `_ or :trac:`another Docker - image providing SageMath `. +- `CoCalc `_ is an online commercial service that provides Sage and + many other tools. -- `Sage Cell Server `_: an online service for - elementary SageMath computations. +- `Docker image sagemathinc/cocalc + `_ can be used on any system with Docker to run CoCalc locally. More information: diff --git a/src/doc/en/installation/linux.rst b/src/doc/en/installation/linux.rst index ec3b5e07ecf..2b2e7bafe2b 100644 --- a/src/doc/en/installation/linux.rst +++ b/src/doc/en/installation/linux.rst @@ -1,6 +1,6 @@ .. _sec-GNU-Linux: -Linux package managers +Linux Package Managers ====================== SageMath is available from various distributions and can be installed diff --git a/src/doc/en/installation/source.rst b/src/doc/en/installation/source.rst index b156165778b..b16fd8e7295 100644 --- a/src/doc/en/installation/source.rst +++ b/src/doc/en/installation/source.rst @@ -1,9 +1,3 @@ -.. comment: - *************************************************************************** - If you alter this document, please change the last line: - **This page was last updated in MONTH YEAR (Sage X.Y).** - *************************************************************************** - .. HIGHLIGHT:: shell-session .. _sec-installation-from-sources: @@ -11,27 +5,23 @@ Install from Source Code ======================== -.. contents:: Table of contents - :depth: 2 - :class: this-will-duplicate-information-and-it-is-still-useful-here - -Some familiarity with the use of the Unix command line may be required to -build Sage from the :wikipedia:`source code `. - -Building Sage from the source code has the major advantage that your install -will be optimized for your particular computer and should therefore offer -better performance and compatibility than a binary install. +Building Sage from the :wikipedia:`source code ` has the major +advantage that your install will be optimized for your particular computer and +should therefore offer better performance and compatibility than a binary +install. -Moreover, it offers you full development capabilities: -you can change absolutely any part of Sage or the programs on which it depends, -and recompile the modified parts. +Moreover, it offers you full development capabilities: you can change +absolutely any part of Sage or the packages on which it depends, and recompile +the modified parts. See the file `README.md `_ in ``SAGE_ROOT`` for information on supported platforms and step-by-step instructions. -The following sections provide some additional details. Most users -will not need to read them. +The following sections provide some additional details. Most users will not +need to read them. Some familiarity with the use of the Unix command line may +be required to build Sage from the source code. + .. _section-prereqs: @@ -436,7 +426,6 @@ On other systems, check the documentation for your particular operating system. .. _section_conda_compilers: - Notes on using conda ^^^^^^^^^^^^^^^^^^^^ @@ -457,70 +446,12 @@ If you don't want conda to be used by sage, deactivate conda (for the current sh operating system, or its own compilers. -Additional software -------------------- - -Recommended programs -^^^^^^^^^^^^^^^^^^^^ - -The following programs are recommended. -They are not strictly required at build time or at run time, -but provide additional capabilities: - -- **dvipng**. -- **ffmpeg**. -- **ImageMagick**. -- **LaTeX**: highly recommended. - -It is highly recommended that you have -:wikipedia:`LaTeX ` -installed, but it is not required. -The most popular packaging is `TeX Live `_, -which can be installed following the directions on their web site. -On Linux systems you can alternatively install your distribution's -texlive packages:: - - $ sudo apt-get install texlive # debian - $ sudo yum install texlive # redhat - -or similar commands. In addition to the base TeX Live install, you may -need some optional TeX Live packages, for example -country-specific babel packages for the localized Sage -documentation. - -If you don't have either ImageMagick or ffmpeg, you won't be able to -view animations. -ffmpeg can produce animations in more different formats than ImageMagick, -and seems to be faster than ImageMagick when creating animated GIFs. -Either ImageMagick or dvipng is used for displaying some LaTeX output in the -Sage notebook. - -On Debian/Ubuntu, the following system packages are recommended. - -- ``texlive-generic-extra`` (to generate pdf documentation) - -- ``texlive-xetex`` (to convert Jupyter notebooks to pdf) - -- ``latexmk`` (to generate pdf documentation) - -- ``pandoc`` (to convert Jupyter notebooks to pdf) - -- ``dvipng`` (to render text with LaTeX in Matplotlib) - -- ``default-jdk`` (to run the Jmol 3D viewer from the console and generate images for 3D plots in the documentation) - -- ``ffmpeg`` (to produce animations) - -- ``libavdevice-dev`` (to produce animations) - Tcl/Tk ^^^^^^ -If you want to use `Tcl/Tk `_ libraries in Sage, -you need to install the Tcl/Tk and its development headers before building -Sage. -Sage's Python will then automatically recognize your system's install of -Tcl/Tk. +If you want to use `Tcl/Tk `_ libraries in Sage, you need +to install the Tcl/Tk and its development headers before building Sage. Sage's +Python will then automatically recognize your system's install of Tcl/Tk. On Linux systems, these are usually provided by the **tk** and **tk-dev** (or **tk-devel**) packages which can be installed using:: @@ -548,13 +479,11 @@ If does not raise an :class:`ImportError`, then it worked. -.. _build-from-source-step-by-step: -Step-by-step installation procedure ------------------------------------ +.. _build-from-source-step-by-step: -General procedure -^^^^^^^^^^^^^^^^^ +Installation steps +------------------ #. Follow the procedure in the file `README.md `_ in ``SAGE_ROOT``. @@ -936,23 +865,6 @@ Here are some of the more commonly used variables affecting the build process: Python-level profiling is always available; This option enables profiling in Cython modules. -- :envvar:`SAGE_SPKG_INSTALL_DOCS` - if set to ``yes``, then install - package-specific documentation to - :file:`$SAGE_ROOT/local/share/doc/PACKAGE_NAME/` when an spkg is - installed. - This option may not be supported by all spkgs. - Some spkgs might also assume that certain programs are available on the - system (for example, ``latex`` or ``pdflatex``). - -- :envvar:`SAGE_DOCBUILD_OPTS` - the value of this variable is passed as an - argument to ``sage --docbuild all html`` or ``sage --docbuild all pdf`` when - you run ``make``, ``make doc``, or ``make doc-pdf``. - For example, you can add ``--no-plot`` to this variable to avoid building - the graphics coming from the ``.. PLOT`` directive within the documentation, - or you can add ``--include-tests-blocks`` to include all "TESTS" blocks in the - reference manual. Run ``sage --docbuild help`` to see the full list - of options. - - :envvar:`SAGE_BUILD_DIR` - the default behavior is to build each spkg in a subdirectory of :file:`$SAGE_ROOT/local/var/tmp/sage/build/`; for example, build version 7.27.0 of @@ -1034,6 +946,67 @@ Here are some of the more commonly used variables affecting the build process: supports :envvar:`SAGE_SUDO`, into a root-owned installation hierarchy (:envvar:`SAGE_LOCAL`). +Environment variables for documentation build: + +- :envvar:`SAGE_DOCBUILD_OPTS` - the value of this variable is passed as an + argument to ``sage --docbuild all html`` or ``sage --docbuild all pdf`` when + you run ``make``, ``make doc``, or ``make doc-pdf``. For example, you can + add ``--no-plot`` to this variable to avoid building the graphics coming from + the ``.. PLOT`` directive within the documentation, or you can add + ``--include-tests-blocks`` to include all "TESTS" blocks in the reference + manual. Run ``sage --docbuild help`` to see the full list of options. + +- :envvar:`SAGE_SPKG_INSTALL_DOCS` - if set to ``yes``, then install + package-specific documentation to + :file:`$SAGE_ROOT/local/share/doc/PACKAGE_NAME/` when an spkg is installed. + This option may not be supported by all spkgs. Some spkgs might also assume + that certain programs are available on the system (for example, ``latex`` or + ``pdflatex``). + +- :envvar:`SAGE_USE_CDNS` -- if set to ``yes``, then build the documentation + using CDNs (Content Distribution Networks) for scripts necessary for HTML + documentation, such as `MathJax `_. + +- :envvar:`SAGE_LIVE_DOC` -- if set to ``yes``, then build live Sage + documentation. If the ``Make live`` button on any webpage of the live doc is + clicked, every example code gets a `CodeMirror `_ + code cell runnable via `Thebe `_. + Thebe is responsible in sending the code to the Sage computing environment + built by `Binder `_ and showing the output result. + The Sage computing environment can be specified to either a Binder repo or a + local Jupyter server. The environment variable :envvar:`SAGE_JUPYTER_SERVER` + is used for this purpose. + + :envvar:`SAGE_JUPYTER_SERVER` - set this to either ``binder``, + ``binder:repo`` with ``repo`` specifying a Binder repo or the URL to a local + Jupyter server. + + - ``binder`` refers to `Sage's official Binder repo + `_. This is assumed if the + environment variable :envvar:`SAGE_JUPYTER_SERVER` is not set. + + - ``binder:repo`` specifies a Binder repo with ``repo``, which is a GitHub + repository name, optionally added with a branch name with ``/`` separator. + + - To use a local Jupyter server instead of Binder, then set the URL to + :envvar:`SAGE_JUPYTER_SERVER` and the secret token to environment variable + :envvar:`SAGE_JUPYTER_SERVER_TOKEN`, which can be left unset if the default + token ``secret`` is used. If the live doc was built with + ``SAGE_JUPYTER_SERVER=http://localhost:8889``, run a local Jupyter server + by + + .. CODE-BLOCK:: bash + + ./sage --notebook=jupyterlab \ + --ServerApp.token='secret' \ + --ServerApp.allow_origin='null' \ + --ServerApp.disable_check_xsrf=true \ + --ServerApp.port=8889 \ + --ServerApp.open_browser=false + + before opening the Sage documentation webpage. + + Environment variables dealing with specific Sage packages: - :envvar:`SAGE_MATPLOTLIB_GUI` - if set to anything non-empty except ``no``, @@ -1045,14 +1018,14 @@ Environment variables dealing with specific Sage packages: support (which is disabled by default). See the file :file:`build/pkgs/pari/spkg-install` for more information. -- :envvar:`SAGE_TUNE_PARI`: If yes, enable PARI self-tuning. Note that +- :envvar:`SAGE_TUNE_PARI` - if yes, enable PARI self-tuning. Note that this can be time-consuming. If you set this variable to "yes", you will also see this: ``WARNING: Tuning PARI/GP is unreliable. You may find your build of PARI fails, or PARI/GP does not work properly once built. We recommend to build this package with SAGE_CHECK="yes".`` -- :envvar:`PARI_MAKEFLAGS`: The value of this variable is passed as an +- :envvar:`PARI_MAKEFLAGS` - The value of this variable is passed as an argument to the ``$MAKE`` command when compiling PARI. Some standard environment variables which are used by Sage: @@ -1094,7 +1067,7 @@ Some standard environment variables which are used by Sage: - :envvar:`OPENBLAS_CONFIGURE` - adds additional configuration flags for the OpenBLAS package that gets added to the make command. (see :trac:`23272`) -Variables dealing with doctesting: +Environment variables dealing with doctesting: - :envvar:`SAGE_TIMEOUT` - used for Sage's doctesting: the number of seconds to allow a doctest before timing it out. @@ -1105,7 +1078,7 @@ Variables dealing with doctesting: ``sage -t --long``. If this isn't set, the default is 1800 seconds (30 minutes). -- :envvar:`SAGE_TEST_GLOBAL_ITER`, :envvar:`SAGE_TEST_ITER`: these can +- :envvar:`SAGE_TEST_GLOBAL_ITER`, :envvar:`SAGE_TEST_ITER` - these can be used instead of passing the flags ``--global-iterations`` and ``--file-iterations``, respectively, to ``sage -t``. Indeed, these variables are only used if the flags are unset. Run ``sage -t -h`` @@ -1146,7 +1119,7 @@ see a list, execute ``sage.env.[TAB]`` while running Sage. *************************************************************************** -Installation in a Multiuser Environment +Installation in a multiuser environment --------------------------------------- This section addresses the question of how a system administrator can install @@ -1183,4 +1156,54 @@ a single copy of Sage in a multi-user computer network. $ sudo chown -R root SAGE_LOCAL -**This page was last updated in September 2022 (Sage 9.8).** +Additional software +------------------- + +The following programs are not strictly required at build time or at run time, +but provide additional capabilities to Sage. We highly recommend a Sage user to +install them. + +LaTeX +^^^^^ + +It is highly recommended that you have :wikipedia:`LaTeX ` installed, +but it is not required. The most popular packaging is `TeX Live +`_, which can be installed following the +directions on their web site. On Linux systems you can alternatively install +your distribution's texlive packages:: + + $ sudo apt-get install texlive # debian + $ sudo yum install texlive # redhat + +or similar commands. In addition to the base TeX Live install, you may +need some optional TeX Live packages, for example +country-specific Babel packages for the localized Sage +documentation. + +Additionally, the following system packages are recommended on Debian/Ubuntu: + +- ``texlive-generic-extra`` (to generate pdf documentation) + +- ``texlive-xetex`` (to convert Jupyter notebooks to pdf) + +- ``latexmk`` (to generate pdf documentation) + +- ``dvipng`` (to render text with LaTeX in Matplotlib) + +pandoc +^^^^^^ + +This is useful to convert Jupyter notebooks to pdf. + +ffmpeg, ImageMagick +^^^^^^^^^^^^^^^^^^^ + +If you don't have either ImageMagick or ffmpeg, you won't be able to view +animations. ffmpeg can produce animations in more different formats than +ImageMagick, and seems to be faster than ImageMagick when creating animated +GIFs. + +``libavdevice-dev`` is a component of ffmpeg to produce animations, and +recommended to install on Debian/Ubuntu. + + diff --git a/src/doc/en/reference/polynomial_rings/index.rst b/src/doc/en/reference/polynomial_rings/index.rst index b03fa4279ca..0035c50021f 100644 --- a/src/doc/en/reference/polynomial_rings/index.rst +++ b/src/doc/en/reference/polynomial_rings/index.rst @@ -65,9 +65,11 @@ Infinite Polynomial Rings Boolean Polynomials ------------------- -.. toctree:: - :maxdepth: 1 +.. ONLY:: feature_sage_rings_polynomial_pbori + + .. toctree:: + :maxdepth: 1 - sage/rings/polynomial/pbori/pbori + sage/rings/polynomial/pbori/pbori .. include:: ../footer.txt diff --git a/src/doc/en/tutorial/latex.rst b/src/doc/en/tutorial/latex.rst index aafaaea6ac5..a173afd75c5 100644 --- a/src/doc/en/tutorial/latex.rst +++ b/src/doc/en/tutorial/latex.rst @@ -1,71 +1,99 @@ -********************************* +*********************** Sage, LaTeX and Friends -********************************* +*********************** Sage and the LaTeX dialect of TeX have an intensely synergistic relationship. This section aims to introduce the variety of interactions, beginning with the most basic and proceeding to the more unusual. -Overview -======== - -It may be easiest to understand the various uses of LaTeX with a -brief overview of the mechanics of the three principal methods -employed by Sage. - - #. Every "object" in Sage is required to have a LaTeX representation. You - can access this representation by executing ``latex(foo)`` where - ``foo`` is some object in Sage. The output is a string that should - render a reasonably accurate representation of ``foo`` when used in - TeX's math-mode (for example, when enclosed between a pair of single - dollar signs). Some examples of this follow below. - - In this way, Sage can be used effectively for constructing portions of - a LaTeX document: create or compute an object in Sage, print ``latex()`` - of the object and cut/paste it into your document. - - #. The Jupyter notebook interface uses `MathJax `_ - to render mathematics cleanly in a web browser. You can start this - automatic rendering by executing ``%display latex`` (and stop by - executing ``%display plain``). - - MathJax is an open source JavaScript display engine for mathematics that - works in all modern browsers. It is able to render a large, but not - totally complete, subset of TeX. It has no support for things like - complicated tables, sectioning or document management, as it is oriented - towards accurately rendering "snippets" of TeX. Seemingly automatic - rendering of math in the notebook is provided by converting the - ``latex()`` representation of an object (as described above) into a form - of HTML palatable to MathJax. - - #. A system-wide installation of LaTeX can be employed. Sage includes - almost everything you need to build and use Sage, but a significant - exception is TeX itself. So in these situations you need to have - TeX installed, along with some associated conversion utilities, to - utilize the full power. - -Here we demonstrate some basic uses of the ``latex()`` function. :: +Basic Use +========= + +Every "object" in Sage is required to have a LaTeX representation. You can +access this representation by executing ``latex(foo)`` where ``foo`` is some +object in Sage. The output is a string that should render a reasonably +accurate representation of ``foo`` when used in TeX's math-mode (for example, +when enclosed between a pair of single dollar signs). Some examples of this +follow below. :: sage: var('z') z sage: latex(z^12) z^{12} - sage: latex(integrate(z^4, z)) - \frac{1}{5} \, z^{5} + sage: latex(sqrt(z^2 + 1/2)) + \sqrt{z^{2} + \frac{1}{2}} sage: latex('a string') \text{\texttt{a{ }string}} sage: latex(QQ) \Bold{Q} + sage: latex(ZZ['x']) + \Bold{Z}[x] sage: latex(matrix(QQ, 2, 3, [[2,4,6],[-1,-1,-1]])) \left(\begin{array}{rrr} 2 & 4 & 6 \\ -1 & -1 & -1 \end{array}\right) -Basic MathJax functionality is largely automatic in the notebook, but we can -partially demonstrate this support with the ``MathJax`` class. The object of -this class converts a Sage object to its LaTeX representation and then wraps it -in HTML. :: +In this way, Sage can be used effectively for constructing portions of +a LaTeX document: create or compute an object in Sage, do ``latex(foo)`` +of the object ``foo`` and cut/paste the LaTeX string into your document. + +The command ``view(foo)`` will show the rendered LaTeX +representation of ``foo``. In the background, the command runs ``latex(foo)`` +and incorporates the LaTeX string into a simple LaTeX document, processes that +document with the system-wide TeX installation, and finally an appropriate +viewer will be called to display the output. + +In the Jupyter notebook, you can see the rendered LaTeX representation of the +output of the entered commands automatically. You can start this +automatic rendering by executing ``%display latex`` (and stop by executing +``%display plain``). + +.. ONLY:: html + + Thus, in the Jupyter notebook, you get + + .. JUPYTER-EXECUTE:: + + %display latex + var('z') + z^12 + + .. JUPYTER-EXECUTE:: + + sqrt(z^2 + 1/2) + + .. JUPYTER-EXECUTE:: + + 'a string' + + .. JUPYTER-EXECUTE:: + + QQ + + .. JUPYTER-EXECUTE:: + + ZZ['x'] + + .. JUPYTER-EXECUTE:: + + matrix(QQ, 2, 3, [[2,4,6],[-1,-1,-1]]) + + .. JUPYTER-EXECUTE:: + + %display plain + +The Jupyter notebook uses `MathJax `_ to render +mathematics cleanly in a web browser. MathJax is an open source JavaScript +display engine for mathematics that works in all modern browsers. It is able +to render a large, but not totally complete, subset of LaTeX. It has no +support for things like complicated tables, sectioning or document management, +as it is oriented towards accurately rendering math snippets of LaTeX. + +The automatic LaTeX rendering in the Jupyter notebook (with ``%display latex`` +on) is internally done via the :class:`sage.misc.html.MathJax` class. The +object of this class converts a Sage object through ``latex()`` to a form of +HTML palatable to MathJax and then wraps it in HTML. :: sage: from sage.misc.html import MathJax sage: mj = MathJax() @@ -73,28 +101,22 @@ in HTML. :: z sage: mj(z^12) \[z^{12}\] + sage: mj(sqrt(z^2 + 1/2)) + \[\sqrt{z^{2} + \frac{1}{2}}\] + sage: mj('a string') + \[\verb|a|\verb| |\verb|string|\] sage: mj(QQ) \[\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Q}\] sage: mj(ZZ['x']) \[\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}[x]\] - sage: mj(integrate(z^4, z)) - \[\frac{1}{5} \, z^{5}\] - -Basic Use -========= + sage: mj(matrix(QQ, 2, 3, [[2,4,6],[-1,-1,-1]])) + \[\left(\begin{array}{rrr} + 2 & 4 & 6 \\ + -1 & -1 & -1 + \end{array}\right)\] -As indicated in the overview, the simplest way to exploit Sage's support of -LaTeX is to use the ``latex()`` function to create legitimate LaTeX code to -represent mathematical objects. These strings can then be incorporated into -standalone LaTeX documents. +This is useful to know if you need to understand the LaTeX rendering of a Sage object. -At the other extreme is the ``view()`` command. The command ``view(foo)`` will -create the LaTeX representation of ``foo``, incorporate this into a simple -LaTeX document, and then process that document with your system-wide TeX -installation. Finally, the appropriate viewer will be called to display the -output from the TeX command. Which version of TeX is used, and therefore the -nature of the output and associated viewer, can be customized (see -:ref:`sec-custom-processing`). .. _sec-custom-generation: @@ -152,30 +174,74 @@ done in written work. This is accomplished by redefining the \[\newcommand{\Bold}[1]{\mathbb{#1}}\Bold{Q}\] sage: latex.blackboard_bold(False) -It is possible to take advantage of the extensible nature of TeX by adding in -new macros and new packages. First, individual macros can be added so that -they are used when MathJax interprets a snippet of TeX in the notebook. :: +.. ONLY:: html + In the Jupyter notebook, + + .. JUPYTER-EXECUTE:: + + %display latex + QQ + + .. JUPYTER-EXECUTE:: + + latex.blackboard_bold(True) + QQ + + .. JUPYTER-EXECUTE:: + + latex.blackboard_bold(False) + %display plain + +It is possible to take advantage of the extensible nature of LaTeX by adding in +new macros. Individual macros can be added so that they are used when MathJax +interprets a LaTeX snippet. :: + + sage: latex.add_macro(r"\newcommand{\sqrt}[1]{(#1)^\frac{1}{2}}") sage: latex.extra_macros() - '' - sage: latex.add_macro("\\newcommand{\\foo}{bar}") - sage: latex.extra_macros() - '\\newcommand{\\foo}{bar}' + '\\newcommand{\\sqrt}[1]{(#1)^\\frac{1}{2}}' sage: var('x y') (x, y) - sage: latex(x+y) - x + y + sage: latex(sqrt(x+y)) + \sqrt{x + y} sage: from sage.misc.html import MathJax sage: mj = MathJax() - sage: mj(x+y) - \[\newcommand{\foo}{bar}x + y\] + sage: mj(sqrt(x + y)) + \[\newcommand{\sqrt}[1]{(#1)^\frac{1}{2}}\sqrt{x + y}\] + sage: latex.extra_macros('') + +.. ONLY:: html + + In the Jupyter notebook, -Additional macros added this way will also be used in the event that the -system-wide version of TeX is called on something larger than MathJax can -handle. The command ``latex_extra_preamble`` is used to build the preamble of -a complete LaTeX document, so the following illustrates how this is -accomplished. As usual note the need for the double-backslashes in the Python -strings. :: + .. JUPYTER-EXECUTE:: + + %display latex + var('x y') + sqrt(x + y) + + .. JUPYTER-EXECUTE:: + + latex.add_macro(r"\newcommand{\sqrt}[1]{(#1)^\frac{1}{2}}") + sqrt(x + y) + + .. JUPYTER-EXECUTE:: + + latex.extra_macros('') + %display plain + + +.. _sec-custom-processing: + +Customizing LaTeX Processing +============================ + +The system-wide TeX is called to process a complete LaTeX document, such as +when you ``view(foo)``, where ``foo`` is a complicated Sage object, too +complicated for ``MathJax`` to handle. The command ``latex_extra_preamble`` is +used to build the preamble of the complete LaTeX document, so the following +illustrates how this is accomplished. As usual note the need for the +double-backslashes in the Python strings. :: sage: latex.extra_macros('') sage: latex.extra_preamble('') @@ -229,38 +295,40 @@ package that presumably does not exist. :: sage: latex.extra_preamble() '\\usepackage{foo-bar-unchecked}' -.. _sec-custom-processing: +Which dialect of TeX is used, and therefore the nature of the output and +associated viewer, can also be customized. -Customizing LaTeX Processing -============================ +.. NOTE:: -It is also possible to control which variant of TeX is used for system-wide -invocations, thus also influencing the nature of the output. + Sage includes almost everything you need to build and use Sage, but a + significant exception is TeX itself. So in the following situations you + need to have a full TeX system installed, along with some associated + conversion utilities. Many versions of Linux have packages based on + TeXLive, for macOS there is MacTeX and for Windows there is MiKTeX. The ``latex.engine()`` command can be used to control if the system-wide -executables ``latex``, ``pdflatex`` or ``xelatex`` are employed for more -complicated LaTeX expressions. When ``view()`` is called and the engine is set -to ``latex``, a dvi file is produced and Sage will use a dvi viewer (like xdvi) -to display the result. In contrast, using ``view()`` when the engine is set to -``pdflatex`` will produce a PDF as the result and Sage will call your system's -utility for displaying PDF files (acrobat, okular, evince, etc.). - -For a concrete example of how complicated LaTeX expressions can be processed, -see the example in the next section (:ref:`sec-tkz-graph`) for using the LaTeX -``tkz-graph`` package to produce high-quality renderings of combinatorial -graphs. For other examples, there are some pre-packaged test cases. To use -these, it is necessary to import the ``sage.misc.latex.latex_examples`` object, -which is an instance of the ``sage.misc.latex.LatexExamples`` class, as -illustrated below. This class currently has examples of commutative diagrams, -combinatorial graphs, knot theory and pstricks, which respectively exercise the -following packages: xy, tkz-graph, xypic, pstricks. After the import, use -tab-completion on ``latex_examples`` to see the pre-packaged examples. Calling -each example will give you back some explanation about what is required to make -the example render properly. To actually see the examples, it is necessary to -use ``view()`` (once the preamble, engine, etc are all set properly). :: +executables ``latex``, ``pdflatex`` or ``xelatex`` are employed. When +``view()`` is called and the engine is set to ``latex``, a dvi file is produced +and Sage will use a dvi viewer (like xdvi) to display the result. In contrast, +using ``view()`` when the engine is set to ``pdflatex`` will produce a PDF as +the result and Sage will call your system's utility for displaying PDF files +(acrobat, okular, evince, etc.). + +For your exercises with these facilities, there are some pre-packaged examples. +To use these, it is necessary to import the ``sage.misc.latex.latex_examples`` +object, which is an instance of the :class:`sage.misc.latex.LatexExamples` +class, as illustrated below. This class currently has examples of commutative +diagrams, combinatorial graphs, knot theory and pstricks, which respectively +exercise the following packages: xy, tkz-graph, xypic, pstricks. After the +import, use tab-completion on ``latex_examples`` to see the pre-packaged +examples. Calling each example will give you back some explanation about what +is required to make the example render properly. To actually see the examples, +it is necessary to use ``view(foo)`` (once the preamble, engine, etc are all set +properly). :: sage: from sage.misc.latex import latex_examples - sage: latex_examples.diagram() + sage: foo = latex_examples.diagram() + sage: foo LaTeX example for testing display of a commutative diagram produced by xypic. @@ -269,63 +337,47 @@ use ``view()`` (once the preamble, engine, etc are all set properly). :: and try viewing again. You should get a picture (a part of the diagram arising from a filtered chain complex). -.. _sec-tkz-graph: - -An Example: Combinatorial Graphs with tkz-graph -=============================================== - -High-quality illustrations of combinatorial graphs (henceforth just "graphs") -are possible with the ``tkz-graph`` package. This package is built on top of -the ``tikz`` front-end to the ``pgf`` library. So all of these components need -to be part of a system-wide TeX installation, and it may be possible that these -components may not be at their most current versions as packaged in some TeX -implementations. So for best results, it could be necessary or advisable to -install these as part of your personal texmf tree. Creating, maintaining and -customizing a system-wide or personal TeX installation is beyond the scope of -this document, but it should be easy to find instructions. The necessary files -are listed in :ref:`sec-system-wide-tex`. - -Thus, to start we need to insure that the relevant packages are included by -adding them to the preamble of the eventual LaTeX document. The images of -graphs do not form properly when a dvi file is used as an intermediate format, -so it is best to set the latex engine to the ``pdflatex`` executable. At this -point a command like ``view(graphs.CompleteGraph(4))`` should produce a PDF -with an appropriate image of the complete graph `K_4`. +For an example of how complicated LaTeX expressions can be processed, let us see the +example of combinatorial graphs, that use ``tkz-graph`` LaTeX package. + +.. NOTE:: + + ``tkz-graph`` LaTeX package is built on top of the ``tikz`` front-end to + the ``pgf`` library. Rendering combinatorial graphs requires the ``pgf`` + library, and the files ``tkz-graph.sty`` and ``tkz-berge.sty``. It is + highly likely that they are already part of your system-wide TeX + installation. Even if not, it should be easy to find instructions to + install them. + +First, we ensure that the relevant packages are included by adding them to the +preamble of the LaTeX document. :: + + sage: latex.extra_preamble('\\usepackage{tikz}\n\\usepackage{tkz-graph}\n' + ....: '\\usepackage{tkz-berge}\n\\usetikzlibrary{arrows,shapes}') + +The images of graphs do not form properly when a dvi file is used as an +intermediate format, so it is best to set the latex engine to the ``pdflatex`` +executable:: + + sage: latex.engine('pdflatex') + +At this point a command like ``view(graphs.CompleteGraph(4))`` should produce a +PDF with an appropriate image of the complete graph `K_4`. + +Actually the preliminary steps could be omitted as the preamble is +automatically set up properly for graphs and ``pdflatex`` is the default LaTeX +engine in Sage. Try the command again after restarting Sage. Note that there is a variety of options to affect how a graph is rendered in -LaTeX via ``tkz-graph``, which is again outside the scope of this section, see -the section of the Reference manual titled "LaTeX Options for Graphs" for -instructions and details. - -.. _sec-system-wide-tex: - -A Fully Capable TeX Installation -================================ - -Many of the more advanced features of the integration of TeX with Sage requires -a system-wide installation of TeX. Many versions of Linux have base TeX -packages based on TeX Live, for macOS there is TeXShop and for Windows there is -MiKTeX. The ``convert`` utility is part of the `ImageMagick -`_ suite (which should be a package or an easy -download), and the three programs ``dvipng``, ``ps2pdf``, and ``dvips`` may be -included with your TeX distribution. The first two may also be obtained, -respectively, from http://sourceforge.net/projects/dvipng/ and as part of -`Ghostscript `_. - -Rendering combinatorial graphs requires a recent version of the PGF library, -the file ``tkz-graph.sty`` from https://www.ctan.org/pkg/tkz-graph, and the -files ``tkz-arith.sty`` and perhaps ``tkz-berge.sty`` from -https://www.ctan.org/pkg/tkz-berge. +LaTeX via ``tkz-graph``, which is outside the scope of this section. See the +section :ref:`sage.graphs.graph_latex` of the Reference Manual for instructions +and details. + SageTeX ======= -SageTeX is a program available to further integrate TeX and Sage. A concise -description of SageTeX is that it is a collection of TeX macros that allow a -LaTeX document to include instructions to have Sage compute various objects -and/or format objects using the ``latex()`` support built into Sage. So as an -intermediate step of compiling a LaTeX document, all of the computational and -LaTeX-formatting features of Sage can be handled automatically. As an example, -a mathematics examination can maintain a correct correspondence between -questions and answers by using SageTeX to have Sage compute one from the other. +SageTeX is a program available to further integrate TeX and Sage. It is a +collection of TeX macros that allow a LaTeX document to include instructions to +have Sage compute various objects and format objects using the ``latex()``. See :ref:`sec-sagetex` for more information. diff --git a/src/doc/en/website/templates/index_furo.html b/src/doc/en/website/templates/index_furo.html index ae70b6ea4df..922068b9b52 100644 --- a/src/doc/en/website/templates/index_furo.html +++ b/src/doc/en/website/templates/index_furo.html @@ -49,9 +49,7 @@


- This is a tour of Sage that closely follows the tour of - Mathematica that is at the beginning of the Mathematica - Book. + A one page introduction to Sage as a handy calculator.

@@ -85,7 +83,7 @@


- This tutorial is the best way to become familiar with Sage + The best way to become familiar with Sage in only a few hours.

diff --git a/src/doc/it/faq/faq-contribute.rst b/src/doc/it/faq/faq-contribute.rst index 0acda9b03da..63c67a8e264 100644 --- a/src/doc/it/faq/faq-contribute.rst +++ b/src/doc/it/faq/faq-contribute.rst @@ -21,7 +21,7 @@ Voglio contribuire a Sage. Da dove inizio? Dai un'occhiata alla `guida ufficiale per lo sviluppo `_ di Sage. Come minimo, la lettura del primo capitolo è richiesta per ogni -svilluppatore di Sage. Inoltre sii molto attento alle +sviluppatore di Sage. Inoltre sii molto attento alle `linee guida per trac `_. Puoi entrare nella lista email `sage-devel `_. @@ -29,7 +29,7 @@ Mentre inizi a conoscere la comunità prendi una copia del codice sorgente di Sa e familiarizza con `git `_, un software per il controllo versione. -Il migiol mode per diventare familiare con il processo di sviluppo di Sage +Il miglior modo per diventare familiare con il processo di sviluppo di Sage è quello di scegliere un ticket dal `server trac `_ ed esaminare i cambiamenti proposti in quel ticket. @@ -70,11 +70,11 @@ di Steven F. Lott è adatto a chiunque sia già a suo agio nel programmare. Se desideri, puoi iniziare a imparare Python usando Sage. Tuttavia, è utile sapere cosa è semplice Python e quando Sage sta usando la -sua "magia". Ci sono molte cose che funzionano in Phyton, ma non in Sage e +sua "magia". Ci sono molte cose che funzionano in Python, ma non in Sage e vice versa. Per di più anche quando la sintassi è identica, molti concetti di programmazione sono spiegati più dettagliatamente in risorse focalizzate su Python piuttosto che in risorse centrate su Sage; in quest'ultime, -la prioirità viene data alla matematica. +la priorità viene data alla matematica. Non sono un programmatore. C'è qualche altro modo in cui posso aiutare? """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" @@ -158,7 +158,7 @@ Consulta anche la Guida dello Sviluppo Sage, specialmente il capitolo `Convenzioni per scrivere codice sorgente in Sage `_. -Ho inviato al server trac una correzione molte settimane fa. Perchè la state ignorando? +Ho inviato al server trac una correzione molte settimane fa. Perché la state ignorando? """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Non stiamo cercando di ignorare la tua correzione. @@ -190,7 +190,7 @@ Se la tua correzione non ha la possibilità di essere aggiunta nell'albero dei sorgenti di Sage, non la ignoreremo ma semplicemente chiuderemo il ticket relativo con una spiegazione sul perché non possiamo includerla. -Come e quando posso ricordardare alla comunità di Sage una correzione a cui tengo? +Come e quando posso ricordare alla comunità di Sage una correzione a cui tengo? """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Ti suggeriamo di fare uno sforzo ulteriore sul come ricordare alla comunità di @@ -221,7 +221,7 @@ preparser di Sage) e la necessità di importare quello che ti serve. primalità e la fattorizzazione. - Dovresti anche notare che ``2 / 3`` non significa più ``Integer(2) / Integer(3)`` che restituisce ``2/3``, ma invece - ``int(2) / int(3)``, e pertanto restituisce ``0`` poichè la divisione è + ``int(2) / int(3)``, e pertanto restituisce ``0`` poiché la divisione è intera e trascura il resto. Se stai lavorando con i tipi ``Integer`` ma in realtà hai bisogno di eseguire una divisione intera puoi usare ``Integer(2) // Integer(3)``. diff --git a/src/doc/it/faq/faq-general.rst b/src/doc/it/faq/faq-general.rst index 39ae0070bf9..85ea1c1ad38 100644 --- a/src/doc/it/faq/faq-general.rst +++ b/src/doc/it/faq/faq-general.rst @@ -13,13 +13,13 @@ La missione fissata per Sage è di essere un'alternativa open-source a Magma, Maple, Mathematica e Matlab. I predecessori di Sage, noti come HECKE e Manin, furono creati perché William Stein ebbe bisogno di scriverli come parte della sua ricerca sulla Teoria dei Numeri. Iniziato da William nel 2005 quando era -all'università di Harvard, Sage combina alcuni fra i miglori software open-source -per la matematica in un'unica intefaccia comune. +all'università di Harvard, Sage combina alcuni fra i migliori software open-source +per la matematica in un'unica interfaccia comune. Da allora Sage viene utilizzato non solo da ricercatori nel campo della Teoria dei Numeri, ma da ricercatori in tutte le scienze matematiche. Sage si avvale ed estende le funzionalità di molti dei pacchetti inglobati. -Anche dal principio, quando Sage veiniva usato principalmente per la Teoria dei +Anche dal principio, quando Sage veniva usato principalmente per la Teoria dei Numeri, includeva: `Givaro `_, `GMP `_, @@ -30,7 +30,7 @@ professori universitari, ricercatori di tutto il mondo usano Sage perché voglio un pacchetto open-source comprensivo per la matematica che offra calcolo sia simbolico che numerico. Perlopiù le persone sono contente di quanto offre Sage. -Com'é comune nell'ambito del software open-source (FOSS), spesso ci sono persone +Come é comune nell'ambito del software open-source (FOSS), spesso ci sono persone che individuano casi in cui Sage non dispone delle funzionalità richiesta da loro. Quindi si immergono nel codice sorgente di Sage per estenderlo per il loro scopo, o ancora per esporre delle funzionalità dei pacchetti inglobati in Sage in modo @@ -73,7 +73,7 @@ all'opera gratuita di una grande squadra internazionale di studenti, insegnanti, professori universitari, ricercatori, ingegneri informatici e persone che lavorano in vari ambiti della matematica, delle scienze, dell'ingegneria, dello sviluppo software e a tutti i livelli della scuola. Lo sviluppo di Sage ha potuto -usufruire di fondi asegnati da numerose istituzioni e ha potuto includere sia +usufruire di fondi assegnati da numerose istituzioni e ha potuto includere sia componenti preesistenti che in corso di sviluppo da parte di numerosi autori. Una lista di coloro che hanno dato un contributo diretto è reperibile al link @@ -144,7 +144,7 @@ ed in particolare nella seguente citazione:: I computer non sono una minaccia per i matematici più di quanto i robot da cucina lo siano per i cuochi. Poiché la matematica diviene sempre più complessa - mentre il ritmo delle nostre vite accellera, dobbiamo delegare il più possibile + mentre il ritmo delle nostre vite accelera, dobbiamo delegare il più possibile alle macchine. Ed intendo sia il lavoro in campo numerico che in quello simbolico. Alcune persone possono andare avanti senza lavastoviglie, ma penso che le dimostrazioni vengano fuori molto più pulite quando il lavoro di @@ -153,7 +153,7 @@ ed in particolare nella seguente citazione:: Questo porta con sè parecchie questioni. Non sono un esperto ma penso che abbiamo bisogno di uno standard a livello di calcolo simbolico per rendere le manipolazioni al computer più facili da documentare e verificare. Con tutto il - rispetto per il libero mercato, forse in questo non dobbiam essere dipendenti + rispetto per il libero mercato, forse in questo non dobbiamo essere dipendenti da un software commerciale. Un progetto open-source potrebbe, forse, trovare risposte migliori a problemi ovvi come la disponibilità, i bug, la compatibilità all'indietro, l'indipendenza dalla piattaforma, le librerie diff --git a/src/doc/it/faq/faq-usage.rst b/src/doc/it/faq/faq-usage.rst index 13a2e0b7e5a..a13048eb71d 100644 --- a/src/doc/it/faq/faq-usage.rst +++ b/src/doc/it/faq/faq-usage.rst @@ -31,7 +31,7 @@ vai al link http://www.sagemath.org/download-source.html per scaricare l'archivio TAR di qualunque rilascio di Sage. Le sessioni di lavoro Notebook di Sage sono eseguite all'interno di -un browser web. Puoi lancianer il Notebook di sage attraverso il +un browser web. Puoi lanciare il Notebook di sage attraverso il seguente comando purché ``sage`` sia nella variabile ``PATH`` .. CODE-BLOCK:: shell-session @@ -45,7 +45,7 @@ Quali sono i prerequisiti di Sage? La maggior parte delle dipendenze sono incluse all'interno di Sage. Nella maggior parte dei casi puoi scaricare il binario precompilato ed usarlo senza dover installare alcun pacchetto dipendente. Se usi -Windows avrai bisogno di intallare +Windows avrai bisogno di installare `VirtualBox `_, che puoi scaricare dal link http://www.virtualbox.org/wiki/Downloads. Dopo aver installato VirtualBox devi scaricare una distribuzione di @@ -68,7 +68,7 @@ questi prerequisiti come segue:: sudo apt-get install build-essential m4 Se hai un sistema multiprocessore puoi scegliere una -copilazione parallela di Sage. Il comando :: +compilazione parallela di Sage. Il comando :: export MAKE='make -j8' @@ -87,7 +87,7 @@ Tcl/Tk. Su Ubuntu lancia, da riga di comando:: sudo apt-get install tk8.5-dev -o qualcosa di simile. Poi reinstalla l'iterprete Python di Sage con:: +o qualcosa di simile. Poi reinstalla l'interprete Python di Sage con:: sage -f python @@ -128,7 +128,7 @@ Puoi poi lanciare tale script Sage in questo modo:: sage /path/to/my/script.sage -Questo si occuperà di caricare le variabili d'ambiente necesssarie +Questo si occuperà di caricare le variabili d'ambiente necessarie ed eseguire gli import di default al posto tuo. @@ -189,7 +189,7 @@ o qualunque fallimento nei doctest. Le funzionalità di base di Sage dovrebbero risultare facili da imparare quanto le basi di Python. Molti tutorial sono disponibili in rete per aiutarti ad imparare Sage. Per trarre il massimo da Sage -ti consigliamo di impararare qualche elemento del linguaggio Python. +ti consigliamo di imparare qualche elemento del linguaggio Python. Segue una lista, incompleta, di risorse su Python. Altre risorse possono essere trovate cercando sul web. @@ -270,7 +270,7 @@ successiva nell'elenco. Questa funzionalità ti permette di recuperare dalla "history" tante righe consecutive quante vuoi. Ma Sage non ha una funzionalità simile: la riga di comando `IPython `_ utilizza la libreria "readline" -(via pyreadline), che evidentemente non supporta questa funzionalit. +(via pyreadline), che evidentemente non supporta questa funzionalità. Magma ha una sua propria libreria personalizzata simile alla "readline" che invece supporta questa funzionalità. (Dal momento che moltissime persone hanno richiesto questa @@ -292,7 +292,7 @@ anello base, come puoi vedere facendo:: sage: preparse("stats.uniform(0,15).ppf([0.5,0.7])") "stats.uniform(Integer(0),Integer(15)).ppf([RealNumber('0.5'),RealNumber('0.7')])" -Sfortunamente il supporto che NumPy fornisce a questi tipi avanzati di +Sfortunatamente il supporto che NumPy fornisce a questi tipi avanzati di Sage, quali ``Integer`` o ``RealNumber`` (numeri reali di precisione arbitraria), non è del 100%. Per risolvere ridefinisci ``Integer`` e/o ``RealNumber`` per cambiare @@ -475,7 +475,7 @@ La visualizzazione 3D in tempo reale per Sage dalla versione 6.4 in avanti usa il pacchetto `Jmol/JSmol `_. Dalla linea di comando viene utilizzata l'applicazione Java Jmol, mentre per la visualizzazione dal browser viene usato puro javascript -oppura una Java applet. In genere nei browser è usato javascript puro +oppure una Java applet. In genere nei browser è usato javascript puro per evitare problemi con quei browser che non supportano i plugin per le applet Java (ad esempio Chrome). In ogni worksheet su browser c'è una casella da spuntare prima di generare una vista tridimensionale @@ -548,7 +548,7 @@ Per saperne di più digita quanto segue al prompt di Sage :: sage.rings.finite_field_givaro.FiniteField_givaro. -Poi premi TAB, ed usa ``??`` per avere più informationi su ogni +Poi premi TAB, ed usa ``??`` per avere più informazioni su ogni funzione. Ad esempio:: sage.rings.finite_field_givaro.FiniteField_givaro.one?? @@ -698,10 +698,10 @@ accessibili tramite la linea di comando IPython con il comando ``??``:: Source: ... -Tuttabia gli oggetti che sono construiti in Python o IPython sono +Tuttavia gli oggetti che sono costruiti in Python o IPython sono compilati e non verranno visualizzati. Ci sono molte funzioni in Sage -construite come funzioni simboliche, i.e. possono essere usate come +costruite come funzioni simboliche, i.e. possono essere usate come parte di espressioni simboliche senza dover essere calcolate. Il loro codice sorgente potrebbe non essere accessibile dalla linea di -comando, sopratutto per le funzioni elementaru, poiché sono scritte +comando, sopratutto per le funzioni elementari, poiché sono scritte in C++ (per ragioni di efficienza). diff --git a/src/doc/it/tutorial/introduction.rst b/src/doc/it/tutorial/introduction.rst index 7e388e04dfc..856aa26d484 100644 --- a/src/doc/it/tutorial/introduction.rst +++ b/src/doc/it/tutorial/introduction.rst @@ -66,7 +66,7 @@ Qui vengono fatti solamente due commenti. #. Il file di download di Sage arrive con le "batterie incluse". In altre parole, nonostante Sage usi Python, IPython, PARI, GAP, Singular, Maxima, NTL, GMP e così via, non è necessario installarli - separatemente siccome sono incluse con la distribuzione di Sage. + separatamente siccome sono incluse con la distribuzione di Sage. Comunque, per usare certe feature di \sage, ad es. Macaulay o KASH, bisogna installare il pacchetto opzionale Sage che interessa o almeno avere i programmi in questioni gia installati sul proprio computer. @@ -76,7 +76,7 @@ Qui vengono fatti solamente due commenti. #. Le versioni binarie precompilate di Sage (che si trovano sul sito web di Sage) possono essere più facili e più veloci da installare invece che la - versione da codice sorgente. Basta solo spachettare il file e eseguire "sage". + versione da codice sorgente. Basta solo spacchettare il file e eseguire "sage". Modi di usare Sage ================== @@ -100,7 +100,7 @@ Obiettivi di lungo periodo per Sage =================================== - **Utile**: il pubblico per Sage il quale sage è stato pensato sono gli - studentu di matematica (dalla scuola superiore all'università), gli insegnanti + studenti di matematica (dalla scuola superiore all'università), gli insegnanti e i ricercatori in matematica. Lo scopo è di fornire software che possa essere usato per esplorare e sperimentare le costruzioni matematiche in algebra, geometria, teoria dei numeri, calcolo, calcolo numerico, ecc. Sage aiuta a @@ -111,11 +111,11 @@ Obiettivi di lungo periodo per Sage operazioni. - **Libero e open source:** il codice sorgente deve essere liberamente disponibile - e leggibile, così che gli utenti posssano capire cosa stia facendo veramente il + e leggibile, così che gli utenti possano capire cosa stia facendo veramente il sistema e possano estenderlo più facilmente. Così come i matematici acquisiscono - una comprensione più profonda di un teorema leggendo attentamete o almeno scorrendo + una comprensione più profonda di un teorema leggendo attentamente o almeno scorrendo velocemente la dimostrazione, le persone che fanno calcoli dovrebbero essere capaci - di capire come funzionano i calcoli leggengo il codice sorgente documentato. Se + di capire come funzionano i calcoli leggendo il codice sorgente documentato. Se si usa Sage per fare calcoli in un articolo che si pubblica, si può essere rassicurati dal fatto che i lettori avranno sempre libero accesso a Sage e a tutto il suo codice sorgente ed è persino concesso di archiviare la versione di Sage che si è utilizzata. diff --git a/src/doc/it/tutorial/tour_algebra.rst b/src/doc/it/tutorial/tour_algebra.rst index cde427d3090..4c301d7b1b2 100644 --- a/src/doc/it/tutorial/tour_algebra.rst +++ b/src/doc/it/tutorial/tour_algebra.rst @@ -71,7 +71,7 @@ l'argomento è il numero di bit di precisione.) Differenziazione, Integrazione, etc. ------------------------------------ -Sage è in grado di differenziae ed integrare molte funzioni. Per +Sage è in grado di differenziare ed integrare molte funzioni. Per esempio, per differenziare :math:`\sin(u)` rispetto a :math:`u`, si procede come nelle righe seguenti: @@ -379,7 +379,7 @@ e "Funzioni speciali", rispettivamente) del manuale di Sage. 0.167089499251049 A questo punto, Sage ha soltanto incorporato queste funzioni per l'uso numerico. -Per l'uso simbolico, si usi direttamente l'intefaccia di Maxima, come +Per l'uso simbolico, si usi direttamente l'interfaccia di Maxima, come nell'esempio seguente:: sage: maxima.eval("f:bessel_y(v, w)") diff --git a/src/sage/algebras/clifford_algebra_element.pxd b/src/sage/algebras/clifford_algebra_element.pxd index 14d5a7a625c..be08e06f922 100644 --- a/src/sage/algebras/clifford_algebra_element.pxd +++ b/src/sage/algebras/clifford_algebra_element.pxd @@ -5,8 +5,8 @@ from sage.modules.with_basis.indexed_element cimport IndexedFreeModuleElement from sage.data_structures.bitset cimport FrozenBitset cdef class CliffordAlgebraElement(IndexedFreeModuleElement): - cdef CliffordAlgebraElement _mul_self_term(self, FrozenBitset supp, coeff) - cdef CliffordAlgebraElement _mul_term_self(self, FrozenBitset supp, coeff) + cdef CliffordAlgebraElement _mul_self_term(self, FrozenBitset supp, coeff) noexcept + cdef CliffordAlgebraElement _mul_term_self(self, FrozenBitset supp, coeff) noexcept cdef class ExteriorAlgebraElement(CliffordAlgebraElement): pass diff --git a/src/sage/algebras/clifford_algebra_element.pyx b/src/sage/algebras/clifford_algebra_element.pyx index 046ee44c8e9..0a1a4adb681 100644 --- a/src/sage/algebras/clifford_algebra_element.pyx +++ b/src/sage/algebras/clifford_algebra_element.pyx @@ -64,7 +64,7 @@ cdef class CliffordAlgebraElement(IndexedFreeModuleElement): """ return repr_from_monomials(self.list(), self._parent._latex_term, True) - cdef _mul_(self, other): + cdef _mul_(self, other) noexcept: """ Return ``self`` multiplied by ``other``. @@ -175,7 +175,7 @@ cdef class CliffordAlgebraElement(IndexedFreeModuleElement): return self.__class__(self.parent(), d) - cdef CliffordAlgebraElement _mul_self_term(self, FrozenBitset supp, coeff): + cdef CliffordAlgebraElement _mul_self_term(self, FrozenBitset supp, coeff) noexcept: r""" Multiply ``self * term`` with the ``term`` having support ``supp`` and coefficient ``coeff``. @@ -223,7 +223,7 @@ cdef class CliffordAlgebraElement(IndexedFreeModuleElement): return type(self)(self._parent, {supp: coeff}) * self - cdef CliffordAlgebraElement _mul_term_self(self, FrozenBitset supp, coeff): + cdef CliffordAlgebraElement _mul_term_self(self, FrozenBitset supp, coeff) noexcept: r""" Multiply ``term * self`` with the ``term`` having support ``supp`` and coefficient ``coeff``. @@ -399,7 +399,7 @@ cdef class ExteriorAlgebraElement(CliffordAlgebraElement): """ An element of an exterior algebra. """ - cdef _mul_(self, other): + cdef _mul_(self, other) noexcept: """ Return ``self`` multiplied by ``other``. @@ -519,7 +519,7 @@ cdef class ExteriorAlgebraElement(CliffordAlgebraElement): return self.__class__(P, d) - cdef CliffordAlgebraElement _mul_self_term(self, FrozenBitset supp, coeff): + cdef CliffordAlgebraElement _mul_self_term(self, FrozenBitset supp, coeff) noexcept: r""" Multiply ``self * term`` with the ``term`` having support ``supp`` and coefficient ``coeff``. @@ -609,7 +609,7 @@ cdef class ExteriorAlgebraElement(CliffordAlgebraElement): del d[k] return type(self)(self._parent, d) - cdef CliffordAlgebraElement _mul_term_self(self, FrozenBitset supp, coeff): + cdef CliffordAlgebraElement _mul_term_self(self, FrozenBitset supp, coeff) noexcept: r""" Multiply ``term * self`` with the ``term`` having support ``supp`` and coefficient ``coeff``. @@ -938,7 +938,7 @@ cdef class CohomologyRAAGElement(CliffordAlgebraElement): :class:`~sage.groups.raag.CohomologyRAAG` """ - cdef _mul_(self, other): + cdef _mul_(self, other) noexcept: """ Return ``self`` multiplied by ``other``. diff --git a/src/sage/algebras/exterior_algebra_groebner.pxd b/src/sage/algebras/exterior_algebra_groebner.pxd index 28cea102be7..bf5ee24ea22 100644 --- a/src/sage/algebras/exterior_algebra_groebner.pxd +++ b/src/sage/algebras/exterior_algebra_groebner.pxd @@ -7,8 +7,8 @@ from sage.algebras.clifford_algebra_element cimport CliffordAlgebraElement from sage.structure.parent cimport Parent from sage.structure.element cimport MonoidElement -cdef long degree(FrozenBitset X) -cdef CliffordAlgebraElement build_monomial(Parent E, FrozenBitset supp) +cdef long degree(FrozenBitset X) noexcept +cdef CliffordAlgebraElement build_monomial(Parent E, FrozenBitset supp) noexcept cdef class GBElement: cdef CliffordAlgebraElement elt @@ -24,25 +24,25 @@ cdef class GroebnerStrategy: cdef Integer rank cdef public tuple groebner_basis - cdef inline GBElement build_elt(self, CliffordAlgebraElement f) - cdef inline GBElement prod_GB_term(self, GBElement f, FrozenBitset t) - cdef inline GBElement prod_term_GB(self, FrozenBitset t, GBElement f) - cdef inline bint build_S_poly(self, GBElement f, GBElement g) + cdef inline GBElement build_elt(self, CliffordAlgebraElement f) noexcept + cdef inline GBElement prod_GB_term(self, GBElement f, FrozenBitset t) noexcept + cdef inline GBElement prod_term_GB(self, FrozenBitset t, GBElement f) noexcept + cdef inline bint build_S_poly(self, GBElement f, GBElement g) noexcept - cdef inline FrozenBitset leading_support(self, CliffordAlgebraElement f) - cdef inline partial_S_poly_left(self, GBElement f, GBElement g) - cdef inline partial_S_poly_right(self, GBElement f, GBElement g) - cdef set preprocessing(self, list P, list G) - cdef list reduction(self, list P, list G) + cdef inline FrozenBitset leading_support(self, CliffordAlgebraElement f) noexcept + cdef inline partial_S_poly_left(self, GBElement f, GBElement g) noexcept + cdef inline partial_S_poly_right(self, GBElement f, GBElement g) noexcept + cdef set preprocessing(self, list P, list G) noexcept + cdef list reduction(self, list P, list G) noexcept - cpdef CliffordAlgebraElement reduce(self, CliffordAlgebraElement f) + cpdef CliffordAlgebraElement reduce(self, CliffordAlgebraElement f) noexcept cdef bint reduce_single(self, CliffordAlgebraElement f, CliffordAlgebraElement g) except -1 cdef int reduced_gb(self, list G) except -1 # These are the methods that determine the ordering of the monomials. # These must be implemented in subclasses. Declare them as "inline" there. - cdef Integer bitset_to_int(self, FrozenBitset X) - cdef FrozenBitset int_to_bitset(self, Integer n) + cdef Integer bitset_to_int(self, FrozenBitset X) noexcept + cdef FrozenBitset int_to_bitset(self, Integer n) noexcept cdef class GroebnerStrategyNegLex(GroebnerStrategy): pass diff --git a/src/sage/algebras/exterior_algebra_groebner.pyx b/src/sage/algebras/exterior_algebra_groebner.pyx index ba46a5f38b4..376eb454082 100644 --- a/src/sage/algebras/exterior_algebra_groebner.pyx +++ b/src/sage/algebras/exterior_algebra_groebner.pyx @@ -29,14 +29,14 @@ from sage.structure.richcmp cimport richcmp, rich_to_bool from sage.data_structures.blas_dict cimport iaxpy from copy import copy -cdef inline long degree(FrozenBitset X): +cdef inline long degree(FrozenBitset X) noexcept: """ Compute the degree of ``X``. """ return bitset_len(X._bitset) -cdef inline CliffordAlgebraElement build_monomial(Parent E, FrozenBitset supp): +cdef inline CliffordAlgebraElement build_monomial(Parent E, FrozenBitset supp) noexcept: """ Helper function for the fastest way to build a monomial. """ @@ -129,14 +129,14 @@ cdef class GroebnerStrategy: else: self.side = 2 - cdef inline FrozenBitset leading_support(self, CliffordAlgebraElement f): + cdef inline FrozenBitset leading_support(self, CliffordAlgebraElement f) noexcept: """ Return the leading support of the exterior algebra element ``f``. """ cdef dict mc = f._monomial_coefficients return self.int_to_bitset(max(self.bitset_to_int(k) for k in mc)) - cdef inline partial_S_poly_left(self, GBElement f, GBElement g): + cdef inline partial_S_poly_left(self, GBElement f, GBElement g) noexcept: r""" Compute one half of the `S`-polynomial for ``f`` and ``g``. @@ -153,7 +153,7 @@ cdef class GroebnerStrategy: ret.elt._monomial_coefficients[k] *= inv return ret - cdef inline partial_S_poly_right(self, GBElement f, GBElement g): + cdef inline partial_S_poly_right(self, GBElement f, GBElement g) noexcept: r""" Compute one half of the `S`-polynomial for ``f`` and ``g``. @@ -170,7 +170,7 @@ cdef class GroebnerStrategy: ret.elt._monomial_coefficients[k] *= inv return ret - cdef inline GBElement build_elt(self, CliffordAlgebraElement f): + cdef inline GBElement build_elt(self, CliffordAlgebraElement f) noexcept: """ Convert ``f`` into a ``GBElement``. """ @@ -180,7 +180,7 @@ cdef class GroebnerStrategy: cdef Integer r = max(self.bitset_to_int(k) for k in mc) return GBElement(f, self.int_to_bitset(r), r) - cdef inline GBElement prod_GB_term(self, GBElement f, FrozenBitset t): + cdef inline GBElement prod_GB_term(self, GBElement f, FrozenBitset t) noexcept: """ Return the GBElement corresponding to ``f * t``. @@ -192,7 +192,7 @@ cdef class GroebnerStrategy: cdef FrozenBitset ls = f.ls._union(t) return GBElement( ret, ls, self.bitset_to_int(ls)) - cdef inline GBElement prod_term_GB(self, FrozenBitset t, GBElement f): + cdef inline GBElement prod_term_GB(self, FrozenBitset t, GBElement f) noexcept: """ Return the GBElement corresponding to ``t * f``. @@ -204,7 +204,7 @@ cdef class GroebnerStrategy: cdef FrozenBitset ls = f.ls._union(t) return GBElement( ret, ls, self.bitset_to_int(ls)) - cdef inline bint build_S_poly(self, GBElement f, GBElement g): + cdef inline bint build_S_poly(self, GBElement f, GBElement g) noexcept: r""" Check to see if we should build the `S`-polynomial. @@ -219,7 +219,7 @@ cdef class GroebnerStrategy: return ( f.ls.intersection(g.ls)).isempty() - cdef inline set preprocessing(self, list P, list G): + cdef inline set preprocessing(self, list P, list G) noexcept: """ Perform the preprocessing step. """ @@ -265,7 +265,7 @@ cdef class GroebnerStrategy: break return L - cdef inline list reduction(self, list P, list G): + cdef inline list reduction(self, list P, list G) noexcept: """ Perform the reduction of ``P`` mod ``G`` in ``E``. """ @@ -450,7 +450,7 @@ cdef class GroebnerStrategy: cdef list G = [self.build_elt(f) for f in self.groebner_basis] self.reduced_gb(G) - cpdef CliffordAlgebraElement reduce(self, CliffordAlgebraElement f): + cpdef CliffordAlgebraElement reduce(self, CliffordAlgebraElement f) noexcept: """ Reduce ``f`` modulo the ideal with Gröbner basis ``G``. @@ -515,10 +515,10 @@ cdef class GroebnerStrategy: iaxpy(-coeff, gp._monomial_coefficients, f._monomial_coefficients) return was_reduced - cdef Integer bitset_to_int(self, FrozenBitset X): + cdef Integer bitset_to_int(self, FrozenBitset X) noexcept: raise NotImplementedError - cdef FrozenBitset int_to_bitset(self, Integer n): + cdef FrozenBitset int_to_bitset(self, Integer n) noexcept: raise NotImplementedError def sorted_monomials(self, as_dict=False): @@ -597,7 +597,7 @@ cdef class GroebnerStrategyNegLex(GroebnerStrategy): """ Gröbner basis strategy implementing neglex ordering. """ - cdef inline Integer bitset_to_int(self, FrozenBitset X): + cdef inline Integer bitset_to_int(self, FrozenBitset X) noexcept: """ Convert ``X`` to an :class:`Integer`. """ @@ -608,7 +608,7 @@ cdef class GroebnerStrategyNegLex(GroebnerStrategy): elt = bitset_next(X._bitset, elt + 1) return ret - cdef inline FrozenBitset int_to_bitset(self, Integer n): + cdef inline FrozenBitset int_to_bitset(self, Integer n) noexcept: """ Convert a nonnegative integer ``n`` to a :class:`FrozenBitset`. """ @@ -628,7 +628,7 @@ cdef class GroebnerStrategyDegRevLex(GroebnerStrategy): """ Gröbner basis strategy implementing degree revlex ordering. """ - cdef inline Integer bitset_to_int(self, FrozenBitset X): + cdef inline Integer bitset_to_int(self, FrozenBitset X) noexcept: """ Convert ``X`` to an :class:`Integer`. """ @@ -647,7 +647,7 @@ cdef class GroebnerStrategyDegRevLex(GroebnerStrategy): elt = bitset_next(X._bitset, elt + 1) return Integer(sum(n.binomial(i) for i in range(deg+1)) - t - 1) - cdef inline FrozenBitset int_to_bitset(self, Integer n): + cdef inline FrozenBitset int_to_bitset(self, Integer n) noexcept: """ Convert a nonnegative integer ``n`` to a :class:`FrozenBitset`. """ @@ -669,7 +669,7 @@ cdef class GroebnerStrategyDegLex(GroebnerStrategy): """ Gröbner basis strategy implementing degree lex ordering. """ - cdef inline Integer bitset_to_int(self, FrozenBitset X): + cdef inline Integer bitset_to_int(self, FrozenBitset X) noexcept: """ Convert ``X`` to an :class:`Integer`. """ @@ -688,7 +688,7 @@ cdef class GroebnerStrategyDegLex(GroebnerStrategy): elt = bitset_next(X._bitset, elt + 1) return Integer(sum(n.binomial(i) for i in range(deg+1)) - t - 1) - cdef inline FrozenBitset int_to_bitset(self, Integer n): + cdef inline FrozenBitset int_to_bitset(self, Integer n) noexcept: """ Convert a nonnegative integer ``n`` to a :class:`FrozenBitset`. """ diff --git a/src/sage/algebras/finite_dimensional_algebras/finite_dimensional_algebra_element.pxd b/src/sage/algebras/finite_dimensional_algebras/finite_dimensional_algebra_element.pxd index c13b8dbab07..dd5f85be9fb 100644 --- a/src/sage/algebras/finite_dimensional_algebras/finite_dimensional_algebra_element.pxd +++ b/src/sage/algebras/finite_dimensional_algebras/finite_dimensional_algebra_element.pxd @@ -6,4 +6,4 @@ cdef class FiniteDimensionalAlgebraElement(AlgebraElement): cdef Matrix __matrix cdef FiniteDimensionalAlgebraElement __inverse -cpdef FiniteDimensionalAlgebraElement unpickle_FiniteDimensionalAlgebraElement(A, vec, mat) +cpdef FiniteDimensionalAlgebraElement unpickle_FiniteDimensionalAlgebraElement(A, vec, mat) noexcept diff --git a/src/sage/algebras/finite_dimensional_algebras/finite_dimensional_algebra_element.pyx b/src/sage/algebras/finite_dimensional_algebras/finite_dimensional_algebra_element.pyx index 1fc0977ce10..e4901439e19 100644 --- a/src/sage/algebras/finite_dimensional_algebras/finite_dimensional_algebra_element.pyx +++ b/src/sage/algebras/finite_dimensional_algebras/finite_dimensional_algebra_element.pyx @@ -20,7 +20,7 @@ from sage.rings.integer import Integer from cpython.object cimport PyObject_RichCompare as richcmp -cpdef FiniteDimensionalAlgebraElement unpickle_FiniteDimensionalAlgebraElement(A, vec, mat): +cpdef FiniteDimensionalAlgebraElement unpickle_FiniteDimensionalAlgebraElement(A, vec, mat) noexcept: """ Helper for unpickling of finite dimensional algebra elements. @@ -341,7 +341,7 @@ cdef class FiniteDimensionalAlgebraElement(AlgebraElement): return self._vector.ncols() # (Rich) comparison - cpdef _richcmp_(self, right, int op): + cpdef _richcmp_(self, right, int op) noexcept: """ EXAMPLES:: @@ -373,7 +373,7 @@ cdef class FiniteDimensionalAlgebraElement(AlgebraElement): """ return richcmp(self._vector, right._vector, op) - cpdef _add_(self, other): + cpdef _add_(self, other) noexcept: """ EXAMPLES:: @@ -383,7 +383,7 @@ cdef class FiniteDimensionalAlgebraElement(AlgebraElement): """ return self._parent.element_class(self._parent, self._vector + other._vector) - cpdef _sub_(self, other): + cpdef _sub_(self, other) noexcept: """ EXAMPLES:: @@ -393,7 +393,7 @@ cdef class FiniteDimensionalAlgebraElement(AlgebraElement): """ return self._parent.element_class(self._parent, self._vector - other._vector) - cpdef _mul_(self, other): + cpdef _mul_(self, other) noexcept: """ EXAMPLES:: @@ -403,7 +403,7 @@ cdef class FiniteDimensionalAlgebraElement(AlgebraElement): """ return self._parent.element_class(self._parent, self._vector * (other)._matrix) - cpdef _lmul_(self, Element other): + cpdef _lmul_(self, Element other) noexcept: """ TESTS:: @@ -417,7 +417,7 @@ cdef class FiniteDimensionalAlgebraElement(AlgebraElement): .format(self.parent(), other.parent())) return self._parent.element_class(self._parent, self._vector * other) - cpdef _rmul_(self, Element other): + cpdef _rmul_(self, Element other) noexcept: """ TESTS:: diff --git a/src/sage/algebras/free_algebra_quotient.py b/src/sage/algebras/free_algebra_quotient.py index 81c7f5ad91e..b19884335c4 100644 --- a/src/sage/algebras/free_algebra_quotient.py +++ b/src/sage/algebras/free_algebra_quotient.py @@ -65,7 +65,7 @@ from sage.structure.unique_representation import UniqueRepresentation -class FreeAlgebraQuotient(UniqueRepresentation, Algebra, object): +class FreeAlgebraQuotient(UniqueRepresentation, Algebra): @staticmethod def __classcall__(cls, A, mons, mats, names): """ diff --git a/src/sage/algebras/fusion_rings/fast_parallel_fmats_methods.pxd b/src/sage/algebras/fusion_rings/fast_parallel_fmats_methods.pxd index e0908ab5884..19e98aa137d 100644 --- a/src/sage/algebras/fusion_rings/fast_parallel_fmats_methods.pxd +++ b/src/sage/algebras/fusion_rings/fast_parallel_fmats_methods.pxd @@ -1,4 +1,4 @@ -cdef _fmat(fvars, Nk_ij, one, a, b, c, d, x, y) -cpdef _backward_subs(factory, bint flatten=*) -cpdef executor(tuple params) -cpdef _solve_for_linear_terms(factory, list eqns=*) +cdef _fmat(fvars, Nk_ij, one, a, b, c, d, x, y) noexcept +cpdef _backward_subs(factory, bint flatten=*) noexcept +cpdef executor(tuple params) noexcept +cpdef _solve_for_linear_terms(factory, list eqns=*) noexcept diff --git a/src/sage/algebras/fusion_rings/fast_parallel_fmats_methods.pyx b/src/sage/algebras/fusion_rings/fast_parallel_fmats_methods.pyx index a9b7eb50fab..b79370c7f2c 100644 --- a/src/sage/algebras/fusion_rings/fast_parallel_fmats_methods.pyx +++ b/src/sage/algebras/fusion_rings/fast_parallel_fmats_methods.pyx @@ -32,7 +32,7 @@ from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing # Fast class methods # ########################## -cpdef _solve_for_linear_terms(factory, list eqns=None): +cpdef _solve_for_linear_terms(factory, list eqns=None) noexcept: r""" Solve for a linear term occurring in a two-term equation, and for variables appearing in univariate single-term equations. @@ -107,7 +107,7 @@ cpdef _solve_for_linear_terms(factory, list eqns=None): # assert _unflatten_coeffs(factory._field, factory.test_fvars[s]) == fvars[s], "OG value {}, Shared: {}".format(factory.test_fvars[s], fvars[s]) return linear_terms_exist -cpdef _backward_subs(factory, bint flatten=True): +cpdef _backward_subs(factory, bint flatten=True) noexcept: r""" Perform backward substitution on ``self.ideal_basis``, traversing variables in reverse lexicographical order. @@ -171,7 +171,7 @@ cpdef _backward_subs(factory, bint flatten=True): fvars[sextuple] = res -cdef _fmat(fvars, _Nk_ij, id_anyon, a, b, c, d, x, y): +cdef _fmat(fvars, _Nk_ij, id_anyon, a, b, c, d, x, y) noexcept: """ Cython version of fmat class method. Using cdef for fastest dispatch """ @@ -214,7 +214,7 @@ cdef _fmat(fvars, _Nk_ij, id_anyon, a, b, c, d, x, y): # Mappers # ############### -cdef req_cy(tuple basis, r_matrix, dict fvars, Nk_ij, id_anyon, tuple sextuple): +cdef req_cy(tuple basis, r_matrix, dict fvars, Nk_ij, id_anyon, tuple sextuple) noexcept: """ Given an FMatrix factory and a sextuple, return a hexagon equation as a polynomial object. @@ -232,7 +232,7 @@ cdef req_cy(tuple basis, r_matrix, dict fvars, Nk_ij, id_anyon, tuple sextuple): @cython.wraparound(False) @cython.nonecheck(False) @cython.cdivision(True) -cdef get_reduced_hexagons(factory, tuple mp_params): +cdef get_reduced_hexagons(factory, tuple mp_params) noexcept: """ Set up and reduce the hexagon equations corresponding to this worker. """ @@ -282,7 +282,7 @@ cdef get_reduced_hexagons(factory, tuple mp_params): return collect_eqns(worker_results) -cdef MPolynomial_libsingular feq_cy(tuple basis, fvars, Nk_ij, id_anyon, zero, tuple nonuple, bint prune=False): +cdef MPolynomial_libsingular feq_cy(tuple basis, fvars, Nk_ij, id_anyon, zero, tuple nonuple, bint prune=False) noexcept: r""" Given an FMatrix factory and a nonuple, return a pentagon equation as a polynomial object. @@ -301,7 +301,7 @@ cdef MPolynomial_libsingular feq_cy(tuple basis, fvars, Nk_ij, id_anyon, zero, t @cython.wraparound(False) @cython.nonecheck(False) @cython.cdivision(True) -cdef get_reduced_pentagons(factory, tuple mp_params): +cdef get_reduced_pentagons(factory, tuple mp_params) noexcept: r""" Set up and reduce the pentagon equations corresponding to this worker. """ @@ -349,7 +349,7 @@ cdef get_reduced_pentagons(factory, tuple mp_params): worker_results.append(red) return collect_eqns(worker_results) -cdef list update_reduce(factory, list eqns): +cdef list update_reduce(factory, list eqns) noexcept: r""" Substitute known values, known squares, and reduce. """ @@ -381,7 +381,7 @@ cdef list update_reduce(factory, list eqns): res.append(red) return collect_eqns(res) -cdef list compute_gb(factory, tuple args): +cdef list compute_gb(factory, tuple args) noexcept: r""" Compute the reduced Groebner basis for given equations iterable. """ @@ -425,7 +425,7 @@ cdef list compute_gb(factory, tuple args): # Reducers # ################ -cdef inline list collect_eqns(list eqns): +cdef inline list collect_eqns(list eqns) noexcept: r""" Helper function for returning processed results back to parent process. @@ -450,7 +450,7 @@ cdef dict mappers = { "pent_verify": pent_verify } -cpdef executor(tuple params): +cpdef executor(tuple params) noexcept: r""" Execute a function defined in this module (``sage.algebras.fusion_rings.fast_parallel_fmats_methods``) in a worker @@ -497,7 +497,7 @@ cpdef executor(tuple params): # Verification # #################### -cdef feq_verif(factory, worker_results, fvars, Nk_ij, id_anyon, tuple nonuple, float tol=5e-8): +cdef feq_verif(factory, worker_results, fvars, Nk_ij, id_anyon, tuple nonuple, float tol=5e-8) noexcept: r""" Check the pentagon equation corresponding to the given nonuple. """ @@ -516,7 +516,7 @@ cdef feq_verif(factory, worker_results, fvars, Nk_ij, id_anyon, tuple nonuple, f @cython.wraparound(False) @cython.nonecheck(False) @cython.cdivision(True) -cdef pent_verify(factory, tuple mp_params): +cdef pent_verify(factory, tuple mp_params) noexcept: r""" Generate all the pentagon equations assigned to this process, and reduce them. diff --git a/src/sage/algebras/fusion_rings/fast_parallel_fusion_ring_braid_repn.pxd b/src/sage/algebras/fusion_rings/fast_parallel_fusion_ring_braid_repn.pxd index a992f0339a4..9fde1f0c5e8 100644 --- a/src/sage/algebras/fusion_rings/fast_parallel_fusion_ring_braid_repn.pxd +++ b/src/sage/algebras/fusion_rings/fast_parallel_fusion_ring_braid_repn.pxd @@ -1,2 +1,2 @@ -cpdef _unflatten_entries(factory, list entries) -cpdef executor(tuple params) +cpdef _unflatten_entries(factory, list entries) noexcept +cpdef executor(tuple params) noexcept diff --git a/src/sage/algebras/fusion_rings/fast_parallel_fusion_ring_braid_repn.pyx b/src/sage/algebras/fusion_rings/fast_parallel_fusion_ring_braid_repn.pyx index 8fc054f50cd..9ba832c5124 100644 --- a/src/sage/algebras/fusion_rings/fast_parallel_fusion_ring_braid_repn.pyx +++ b/src/sage/algebras/fusion_rings/fast_parallel_fusion_ring_braid_repn.pyx @@ -18,7 +18,7 @@ from sage.rings.qqbar import QQbar # Mappers # ############### -cdef mid_sig_ij(fusion_ring, row, col, a, b): +cdef mid_sig_ij(fusion_ring, row, col, a, b) noexcept: r""" Compute the (xi, yi), (xj, yj) entry of generator braiding the middle two strands in the tree b -> xi # yi -> (a # a) # (a # a), which results in @@ -48,7 +48,7 @@ cdef mid_sig_ij(fusion_ring, row, col, a, b): entry += f1 * f2 * r * f3 * f4 return entry -cdef odd_one_out_ij(fusion_ring, xi, xj, a, b): +cdef odd_one_out_ij(fusion_ring, xi, xj, a, b) noexcept: r""" Compute the `xi`, `xj` entry of the braid generator on the two right-most strands, corresponding to the tree b -> (xi # a) -> (a # a) # a, which @@ -76,7 +76,7 @@ cdef odd_one_out_ij(fusion_ring, xi, xj, a, b): cdef odd_one_out_ij_cache = dict() cdef mid_sig_ij_cache = dict() -cdef cached_mid_sig_ij(fusion_ring, row, col, a, b): +cdef cached_mid_sig_ij(fusion_ring, row, col, a, b) noexcept: r""" Cached version of :meth:`mid_sig_ij`. """ @@ -86,7 +86,7 @@ cdef cached_mid_sig_ij(fusion_ring, row, col, a, b): mid_sig_ij_cache[row, col, a, b] = entry return entry -cdef cached_odd_one_out_ij(fusion_ring, xi, xj, a, b): +cdef cached_odd_one_out_ij(fusion_ring, xi, xj, a, b) noexcept: r""" Cached version of :meth:`odd_one_out_ij`. """ @@ -99,7 +99,7 @@ cdef cached_odd_one_out_ij(fusion_ring, xi, xj, a, b): @cython.nonecheck(False) @cython.cdivision(True) -cdef sig_2k(fusion_ring, tuple args): +cdef sig_2k(fusion_ring, tuple args) noexcept: r""" Compute entries of the `2k`-th braid generator """ @@ -179,7 +179,7 @@ cdef sig_2k(fusion_ring, tuple args): @cython.nonecheck(False) @cython.cdivision(True) -cdef odd_one_out(fusion_ring, tuple args): +cdef odd_one_out(fusion_ring, tuple args) noexcept: r""" Compute entries of the rightmost braid generator, in case we have an odd number of strands. @@ -263,7 +263,7 @@ cdef dict mappers = { "odd_one_out": odd_one_out } -cpdef executor(tuple params): +cpdef executor(tuple params) noexcept: r""" Execute a function registered in this module's ``mappers`` in a worker process, and supply the ``FusionRing`` parameter by @@ -305,7 +305,7 @@ cpdef executor(tuple params): # Pickling circumvention helpers # ###################################### -cpdef _unflatten_entries(fusion_ring, list entries): +cpdef _unflatten_entries(fusion_ring, list entries) noexcept: r""" Restore cyclotomic coefficient object from its tuple of rational coefficients representation. diff --git a/src/sage/algebras/fusion_rings/poly_tup_engine.pxd b/src/sage/algebras/fusion_rings/poly_tup_engine.pxd index a4ddf9b92ae..ac2c5041de9 100644 --- a/src/sage/algebras/fusion_rings/poly_tup_engine.pxd +++ b/src/sage/algebras/fusion_rings/poly_tup_engine.pxd @@ -3,21 +3,21 @@ from sage.rings.number_field.number_field_element cimport NumberFieldElement_abs from sage.rings.polynomial.multi_polynomial_libsingular cimport MPolynomial_libsingular, MPolynomialRing_libsingular from sage.rings.polynomial.polydict cimport ETuple -cpdef tuple poly_to_tup(MPolynomial_libsingular poly) -cpdef MPolynomial_libsingular _tup_to_poly(tuple eq_tup, MPolynomialRing_libsingular parent) -cpdef tuple resize(tuple eq_tup, dict idx_map, int nvars) -cpdef list get_variables_degrees(list eqns, int nvars) -cpdef list variables(tuple eq_tup) -cpdef constant_coeff(tuple eq_tup, field) -cpdef tuple apply_coeff_map(tuple eq_tup, coeff_map) +cpdef tuple poly_to_tup(MPolynomial_libsingular poly) noexcept +cpdef MPolynomial_libsingular _tup_to_poly(tuple eq_tup, MPolynomialRing_libsingular parent) noexcept +cpdef tuple resize(tuple eq_tup, dict idx_map, int nvars) noexcept +cpdef list get_variables_degrees(list eqns, int nvars) noexcept +cpdef list variables(tuple eq_tup) noexcept +cpdef constant_coeff(tuple eq_tup, field) noexcept +cpdef tuple apply_coeff_map(tuple eq_tup, coeff_map) noexcept # cpdef bint tup_fixes_sq(tuple eq_tup) -cdef bint tup_fixes_sq(tuple eq_tup) -cdef dict subs_squares(dict eq_dict, KSHandler known_sq) -cpdef dict compute_known_powers(max_degs, dict val_dict, one) -cdef dict subs(tuple poly_tup, dict known_powers, one) -cpdef tup_to_univ_poly(tuple eq_tup, univ_poly_ring) -cpdef tuple poly_tup_sortkey(tuple eq_tup) -cdef tuple reduce_poly_dict(dict eq_dict, ETuple nonz, KSHandler known_sq, NumberFieldElement_absolute one) -cdef tuple _flatten_coeffs(tuple eq_tup) -cpdef tuple _unflatten_coeffs(field, tuple eq_tup) -cdef int has_appropriate_linear_term(tuple eq_tup) +cdef bint tup_fixes_sq(tuple eq_tup) noexcept +cdef dict subs_squares(dict eq_dict, KSHandler known_sq) noexcept +cpdef dict compute_known_powers(max_degs, dict val_dict, one) noexcept +cdef dict subs(tuple poly_tup, dict known_powers, one) noexcept +cpdef tup_to_univ_poly(tuple eq_tup, univ_poly_ring) noexcept +cpdef tuple poly_tup_sortkey(tuple eq_tup) noexcept +cdef tuple reduce_poly_dict(dict eq_dict, ETuple nonz, KSHandler known_sq, NumberFieldElement_absolute one) noexcept +cdef tuple _flatten_coeffs(tuple eq_tup) noexcept +cpdef tuple _unflatten_coeffs(field, tuple eq_tup) noexcept +cdef int has_appropriate_linear_term(tuple eq_tup) noexcept diff --git a/src/sage/algebras/fusion_rings/poly_tup_engine.pyx b/src/sage/algebras/fusion_rings/poly_tup_engine.pyx index 67176402134..5c3f54df9a6 100644 --- a/src/sage/algebras/fusion_rings/poly_tup_engine.pyx +++ b/src/sage/algebras/fusion_rings/poly_tup_engine.pyx @@ -12,7 +12,7 @@ Arithmetic Engine for Polynomials as Tuples # API # ########### -cpdef inline tuple poly_to_tup(MPolynomial_libsingular poly): +cpdef inline tuple poly_to_tup(MPolynomial_libsingular poly) noexcept: r""" Convert a polynomial object into the internal representation as tuple of ``(ETuple exp, NumberFieldElement coeff)`` pairs. @@ -28,7 +28,7 @@ cpdef inline tuple poly_to_tup(MPolynomial_libsingular poly): """ return tuple(poly.dict().items()) -cpdef inline MPolynomial_libsingular _tup_to_poly(tuple eq_tup, MPolynomialRing_libsingular parent): +cpdef inline MPolynomial_libsingular _tup_to_poly(tuple eq_tup, MPolynomialRing_libsingular parent) noexcept: r""" Return a polynomial object from its tuple of pairs representation. @@ -74,7 +74,7 @@ cpdef inline MPolynomial_libsingular _tup_to_poly(tuple eq_tup, MPolynomialRing_ """ return parent._element_constructor_(dict(eq_tup), check=False) -cdef inline tuple _flatten_coeffs(tuple eq_tup): +cdef inline tuple _flatten_coeffs(tuple eq_tup) noexcept: r""" Flatten cyclotomic coefficients to a representation as a tuple of rational coefficients. @@ -88,7 +88,7 @@ cdef inline tuple _flatten_coeffs(tuple eq_tup): flat.append((exp, tuple(cyc_coeff._coefficients()))) return tuple(flat) -cpdef tuple _unflatten_coeffs(field, tuple eq_tup): +cpdef tuple _unflatten_coeffs(field, tuple eq_tup) noexcept: r""" Restore cyclotomic coefficient object from its tuple of rational coefficients representation. @@ -118,7 +118,7 @@ cpdef tuple _unflatten_coeffs(field, tuple eq_tup): # Useful private predicates # ################################# -cdef inline int has_appropriate_linear_term(tuple eq_tup): +cdef inline int has_appropriate_linear_term(tuple eq_tup) noexcept: r""" Determine whether the given tuple of pairs (of length 2) contains an *appropriate* linear term. @@ -149,7 +149,7 @@ cdef inline int has_appropriate_linear_term(tuple eq_tup): # "Change rings" # ###################### -cpdef inline tup_to_univ_poly(tuple eq_tup, univ_poly_ring): +cpdef inline tup_to_univ_poly(tuple eq_tup, univ_poly_ring) noexcept: r""" Given a tuple of pairs representing a univariate polynomial and a univariate polynomial ring, return a univariate polynomial object. @@ -177,7 +177,7 @@ cpdef inline tup_to_univ_poly(tuple eq_tup, univ_poly_ring): cdef NumberFieldElement_absolute c return univ_poly_ring({exp._data[1] if exp._nonzero else 0: c for exp, c in eq_tup}) -cpdef inline tuple resize(tuple eq_tup, dict idx_map, int nvars): +cpdef inline tuple resize(tuple eq_tup, dict idx_map, int nvars) noexcept: r""" Return a tuple representing a polynomial in a ring with ``len(sorted_vars)`` generators. @@ -218,7 +218,7 @@ cpdef inline tuple resize(tuple eq_tup, dict idx_map, int nvars): # Convenience methods # ########################### -cdef inline ETuple degrees(tuple poly_tup): +cdef inline ETuple degrees(tuple poly_tup) noexcept: r""" Return the maximal degree of each variable in the polynomial. """ @@ -232,7 +232,7 @@ cdef inline ETuple degrees(tuple poly_tup): max_degs = max_degs.emax( ( poly_tup[i])[0]) return max_degs -cpdef list get_variables_degrees(list eqns, int nvars): +cpdef list get_variables_degrees(list eqns, int nvars) noexcept: r""" Find maximum degrees for each variable in equations. @@ -257,7 +257,7 @@ cpdef list get_variables_degrees(list eqns, int nvars): dense[max_deg._data[2*i]] = max_deg._data[2*i+1] return dense -cpdef list variables(tuple eq_tup): +cpdef list variables(tuple eq_tup) noexcept: """ Return indices of all variables appearing in eq_tup @@ -277,7 +277,7 @@ cpdef list variables(tuple eq_tup): """ return degrees(eq_tup).nonzero_positions() -cpdef constant_coeff(tuple eq_tup, field): +cpdef constant_coeff(tuple eq_tup, field) noexcept: r""" Return the constant coefficient of the polynomial represented by given tuple. @@ -300,7 +300,7 @@ cpdef constant_coeff(tuple eq_tup, field): return coeff return field.zero() -cpdef tuple apply_coeff_map(tuple eq_tup, coeff_map): +cpdef tuple apply_coeff_map(tuple eq_tup, coeff_map) noexcept: """ Apply ``coeff_map`` to coefficients. @@ -320,7 +320,7 @@ cpdef tuple apply_coeff_map(tuple eq_tup, coeff_map): return tuple(new_tup) # cpdef inline bint tup_fixes_sq(tuple eq_tup): -cdef inline bint tup_fixes_sq(tuple eq_tup): +cdef inline bint tup_fixes_sq(tuple eq_tup) noexcept: r""" Determine if given equation fixes the square of a variable. @@ -342,7 +342,7 @@ cdef inline bint tup_fixes_sq(tuple eq_tup): # Simplification # ###################### -cdef dict subs_squares(dict eq_dict, KSHandler known_sq): +cdef dict subs_squares(dict eq_dict, KSHandler known_sq) noexcept: r""" Substitute for known squares into a given polynomial. @@ -379,7 +379,7 @@ cdef dict subs_squares(dict eq_dict, KSHandler known_sq): subbed[exp] = coeff return subbed -cdef dict remove_gcf(dict eq_dict, ETuple nonz): +cdef dict remove_gcf(dict eq_dict, ETuple nonz) noexcept: r""" Return a dictionary of ``(ETuple, coeff)`` pairs describing the polynomial ``eq / GCF(eq)``. @@ -399,7 +399,7 @@ cdef dict remove_gcf(dict eq_dict, ETuple nonz): ret[exp.esub(common_powers)] = c return ret -cdef tuple to_monic(dict eq_dict, one): +cdef tuple to_monic(dict eq_dict, one) noexcept: """ Return tuple of pairs ``(ETuple, coeff)`` describing the monic polynomial associated to ``eq_dict``. @@ -422,7 +422,7 @@ cdef tuple to_monic(dict eq_dict, one): ret.append((ord_monoms[n-2-i], inv_lc * eq_dict[ord_monoms[n-2-i]])) return tuple(ret) -cdef tuple reduce_poly_dict(dict eq_dict, ETuple nonz, KSHandler known_sq, NumberFieldElement_absolute one): +cdef tuple reduce_poly_dict(dict eq_dict, ETuple nonz, KSHandler known_sq, NumberFieldElement_absolute one) noexcept: """ Return a tuple describing a monic polynomial with no known nonzero gcf and no known squares. @@ -437,7 +437,7 @@ cdef tuple reduce_poly_dict(dict eq_dict, ETuple nonz, KSHandler known_sq, Numbe # Substitution # #################### -cpdef dict compute_known_powers(max_degs, dict val_dict, one): +cpdef dict compute_known_powers(max_degs, dict val_dict, one) noexcept: """ Pre-compute powers of known values for efficiency when preparing to substitute into a list of polynomials. @@ -482,7 +482,7 @@ cpdef dict compute_known_powers(max_degs, dict val_dict, one): known_powers[var_idx][power+1] = tup_mul(known_powers[var_idx][power], val_dict[var_idx]) return known_powers -cdef dict subs(tuple poly_tup, dict known_powers, one): +cdef dict subs(tuple poly_tup, dict known_powers, one) noexcept: """ Substitute given variables into a polynomial tuple. """ @@ -505,7 +505,7 @@ cdef dict subs(tuple poly_tup, dict known_powers, one): subbed[shifted_exp] = coeff * c return subbed -cdef tuple tup_mul(tuple p1, tuple p2): +cdef tuple tup_mul(tuple p1, tuple p2) noexcept: r""" Multiplication of two polynomial tuples using schoolbook multiplication. """ @@ -524,7 +524,7 @@ cdef tuple tup_mul(tuple p1, tuple p2): # Sorting # ############### -cdef tuple monom_sortkey(ETuple exp): +cdef tuple monom_sortkey(ETuple exp) noexcept: r""" Produce a sortkey for a monomial exponent with respect to degree reversed lexicographic ordering. @@ -535,7 +535,7 @@ cdef tuple monom_sortkey(ETuple exp): cdef ETuple rev = exp.reversed().emul(-1) return (deg, rev) -cpdef tuple poly_tup_sortkey(tuple eq_tup): +cpdef tuple poly_tup_sortkey(tuple eq_tup) noexcept: r""" Return the sortkey of a polynomial represented as a tuple of ``(ETuple, coeff)`` pairs with respect to the degree diff --git a/src/sage/algebras/fusion_rings/shm_managers.pxd b/src/sage/algebras/fusion_rings/shm_managers.pxd index 8f4967d6d0a..f1e2ed74714 100644 --- a/src/sage/algebras/fusion_rings/shm_managers.pxd +++ b/src/sage/algebras/fusion_rings/shm_managers.pxd @@ -8,10 +8,10 @@ cdef class KSHandler: cdef NumberField field cdef public object shm - cdef bint contains(self, int idx) - cdef NumberFieldElement_absolute get(self, int idx) - cdef setitem(self, int idx, rhs) - cpdef update(self, list eqns) + cdef bint contains(self, int idx) noexcept + cdef NumberFieldElement_absolute get(self, int idx) noexcept + cdef setitem(self, int idx, rhs) noexcept + cpdef update(self, list eqns) noexcept cdef class FvarsHandler: cdef dict sext_to_idx, obj_cache diff --git a/src/sage/algebras/fusion_rings/shm_managers.pyx b/src/sage/algebras/fusion_rings/shm_managers.pyx index bbb364e91dd..dcfa274b5ea 100644 --- a/src/sage/algebras/fusion_rings/shm_managers.pyx +++ b/src/sage/algebras/fusion_rings/shm_managers.pyx @@ -144,7 +144,7 @@ cdef class KSHandler: @cython.nonecheck(False) @cython.wraparound(False) @cython.boundscheck(False) - cdef NumberFieldElement_absolute get(self, int idx): + cdef NumberFieldElement_absolute get(self, int idx) noexcept: r""" Retrieve the known square corresponding to the given index, if it exists. @@ -175,7 +175,7 @@ cdef class KSHandler: self.obj_cache[idx] = cyc_coeff return cyc_coeff - cpdef update(self, list eqns): + cpdef update(self, list eqns) noexcept: r""" Update ```self``'s ``shared_memory``-backed dictionary of known squares. Keys are variable indices and corresponding values @@ -242,7 +242,7 @@ cdef class KSHandler: @cython.nonecheck(False) @cython.wraparound(False) @cython.infer_types(False) - cdef setitem(self, int idx, rhs): + cdef setitem(self, int idx, rhs) noexcept: """ Create an entry corresponding to the given index. @@ -269,7 +269,7 @@ cdef class KSHandler: nums[i] = num denoms[i] = denom - cdef bint contains(self, int idx): + cdef bint contains(self, int idx) noexcept: r""" Determine whether ``self`` contains entry corresponding to given ``idx``. diff --git a/src/sage/algebras/letterplace/free_algebra_element_letterplace.pxd b/src/sage/algebras/letterplace/free_algebra_element_letterplace.pxd index d22fe4e9a40..ddd77e94be7 100644 --- a/src/sage/algebras/letterplace/free_algebra_element_letterplace.pxd +++ b/src/sage/algebras/letterplace/free_algebra_element_letterplace.pxd @@ -13,5 +13,5 @@ from sage.algebras.letterplace.free_algebra_letterplace cimport FreeAlgebra_lett cdef class FreeAlgebraElement_letterplace(AlgebraElement): cdef MPolynomial_libsingular _poly - cpdef _add_(self, other) - cpdef _mul_(self, other) + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept diff --git a/src/sage/algebras/letterplace/free_algebra_element_letterplace.pyx b/src/sage/algebras/letterplace/free_algebra_element_letterplace.pyx index 9029a8b07a5..8e48f0530d9 100644 --- a/src/sage/algebras/letterplace/free_algebra_element_letterplace.pyx +++ b/src/sage/algebras/letterplace/free_algebra_element_letterplace.pyx @@ -441,7 +441,7 @@ cdef class FreeAlgebraElement_letterplace(AlgebraElement): return True return False - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ Implement comparisons, using the Cython richcmp convention. @@ -458,7 +458,7 @@ cdef class FreeAlgebraElement_letterplace(AlgebraElement): ################################ # Arithmetic - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ TESTS:: @@ -474,7 +474,7 @@ cdef class FreeAlgebraElement_letterplace(AlgebraElement): return FreeAlgebraElement_letterplace(self._parent, -self._poly, check=False) - cpdef _add_(self, other): + cpdef _add_(self, other) noexcept: """ Addition, under the side condition that either one summand is zero, or both summands have the same degree. @@ -508,7 +508,7 @@ cdef class FreeAlgebraElement_letterplace(AlgebraElement): self._poly + right._poly, check=False) - cpdef _sub_(self, other): + cpdef _sub_(self, other) noexcept: """ Difference, under the side condition that either one summand is zero or both have the same weighted degree. @@ -548,7 +548,7 @@ cdef class FreeAlgebraElement_letterplace(AlgebraElement): self._poly - right._poly, check=False) - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: """ Multiplication from the right with an element of the base ring. @@ -563,7 +563,7 @@ cdef class FreeAlgebraElement_letterplace(AlgebraElement): self._poly._lmul_(right), check=False) - cpdef _rmul_(self, Element left): + cpdef _rmul_(self, Element left) noexcept: """ Multiplication from the left with an element of the base ring. @@ -578,7 +578,7 @@ cdef class FreeAlgebraElement_letterplace(AlgebraElement): self._poly._rmul_(left), check=False) - cpdef _mul_(self, other): + cpdef _mul_(self, other) noexcept: """ Product of two free algebra elements in letterplace implementation. diff --git a/src/sage/algebras/letterplace/free_algebra_letterplace.pxd b/src/sage/algebras/letterplace/free_algebra_letterplace.pxd index 47a7275aba0..a726262546b 100644 --- a/src/sage/algebras/letterplace/free_algebra_letterplace.pxd +++ b/src/sage/algebras/letterplace/free_algebra_letterplace.pxd @@ -29,6 +29,6 @@ cdef class FreeAlgebra_letterplace(Algebra): cdef int _ngens cdef int _nb_slackvars cdef object __monoid - cdef str exponents_to_string(self, E) - cdef str exponents_to_latex(self, E) + cdef str exponents_to_string(self, E) noexcept + cdef str exponents_to_latex(self, E) noexcept cdef tuple _degrees diff --git a/src/sage/algebras/letterplace/free_algebra_letterplace.pyx b/src/sage/algebras/letterplace/free_algebra_letterplace.pyx index 53f0dfdea6d..ddf3e5c2f09 100644 --- a/src/sage/algebras/letterplace/free_algebra_letterplace.pyx +++ b/src/sage/algebras/letterplace/free_algebra_letterplace.pyx @@ -137,7 +137,7 @@ freeAlgebra = singular_function("freeAlgebra") ##################### # Auxiliary functions -cdef MPolynomialRing_libsingular make_letterplace_ring(base_ring, blocks): +cdef MPolynomialRing_libsingular make_letterplace_ring(base_ring, blocks) noexcept: """ Create a polynomial ring in block order. @@ -563,7 +563,7 @@ cdef class FreeAlgebra_letterplace(Algebra): return self.__monoid # Auxiliar methods - cdef str exponents_to_string(self, E): + cdef str exponents_to_string(self, E) noexcept: """ This auxiliary method is used for the string representation of elements of this free algebra. @@ -605,7 +605,7 @@ cdef class FreeAlgebra_letterplace(Algebra): return '*'.join(out) # Auxiliar methods - cdef str exponents_to_latex(self, E): + cdef str exponents_to_latex(self, E) noexcept: r""" This auxiliary method is used for the representation of elements of this free algebra as a latex string. @@ -689,7 +689,7 @@ cdef class FreeAlgebra_letterplace(Algebra): ########################### # Coercion - cpdef _coerce_map_from_(self, S): + cpdef _coerce_map_from_(self, S) noexcept: """ A ring ``R`` coerces into self, if diff --git a/src/sage/algebras/lie_algebras/lie_algebra_element.pxd b/src/sage/algebras/lie_algebras/lie_algebra_element.pxd index fdae38396b9..9005eae72fd 100644 --- a/src/sage/algebras/lie_algebras/lie_algebra_element.pxd +++ b/src/sage/algebras/lie_algebras/lie_algebra_element.pxd @@ -4,24 +4,24 @@ from sage.structure.sage_object cimport SageObject from sage.modules.with_basis.indexed_element cimport IndexedFreeModuleElement cdef class LieAlgebraElement(IndexedFreeModuleElement): - cpdef lift(self) + cpdef lift(self) noexcept cdef class LieAlgebraElementWrapper(ElementWrapper): - cpdef _add_(self, right) - cpdef _sub_(self, right) + cpdef _add_(self, right) noexcept + cpdef _sub_(self, right) noexcept cdef class LieAlgebraMatrixWrapper(LieAlgebraElementWrapper): pass cdef class LieSubalgebraElementWrapper(LieAlgebraElementWrapper): cdef dict _monomial_coefficients - cpdef dict monomial_coefficients(self, bint copy=*) + cpdef dict monomial_coefficients(self, bint copy=*) noexcept cdef class StructureCoefficientsElement(LieAlgebraMatrixWrapper): - cpdef bracket(self, right) - cpdef _bracket_(self, right) - cpdef to_vector(self, bint sparse=*) - cpdef dict monomial_coefficients(self, bint copy=*) + cpdef bracket(self, right) noexcept + cpdef _bracket_(self, right) noexcept + cpdef to_vector(self, bint sparse=*) noexcept + cpdef dict monomial_coefficients(self, bint copy=*) noexcept # cpdef lift(self) cdef class UntwistedAffineLieAlgebraElement(Element): @@ -30,23 +30,23 @@ cdef class UntwistedAffineLieAlgebraElement(Element): cdef _d_coeff cdef long _hash - cpdef _add_(self, other) - cpdef _sub_(self, other) - cpdef _neg_(self) + cpdef _add_(self, other) noexcept + cpdef _sub_(self, other) noexcept + cpdef _neg_(self) noexcept - cpdef dict t_dict(self) - cpdef c_coefficient(self) - cpdef d_coefficient(self) + cpdef dict t_dict(self) noexcept + cpdef c_coefficient(self) noexcept + cpdef d_coefficient(self) noexcept - cpdef bracket(self, y) - cpdef _bracket_(self, y) - cpdef canonical_derivation(self) - cpdef monomial_coefficients(self, bint copy=*) + cpdef bracket(self, y) noexcept + cpdef _bracket_(self, y) noexcept + cpdef canonical_derivation(self) noexcept + cpdef monomial_coefficients(self, bint copy=*) noexcept cdef class LieObject(SageObject): cdef tuple _word cdef public tuple _index_word - cpdef tuple to_word(self) + cpdef tuple to_word(self) noexcept cdef class LieGenerator(LieObject): cdef public str _name @@ -56,7 +56,7 @@ cdef class LieBracket(LieObject): cdef public LieObject _right cdef long _hash - cpdef lift(self, dict UEA_gens_dict) + cpdef lift(self, dict UEA_gens_dict) noexcept cdef class GradedLieBracket(LieBracket): cdef public _grade diff --git a/src/sage/algebras/lie_algebras/lie_algebra_element.pyx b/src/sage/algebras/lie_algebras/lie_algebra_element.pyx index ec8dafeec66..ed9680a0af5 100644 --- a/src/sage/algebras/lie_algebras/lie_algebra_element.pyx +++ b/src/sage/algebras/lie_algebras/lie_algebra_element.pyx @@ -124,7 +124,7 @@ cdef class LieAlgebraElement(IndexedFreeModuleElement): return codomain.sum(base_map(c) * t._im_gens_(codomain, im_gens, names) for t, c in self._monomial_coefficients.items()) - cpdef lift(self): + cpdef lift(self) noexcept: """ Lift ``self`` to the universal enveloping algebra. @@ -275,7 +275,7 @@ cdef class LieAlgebraElementWrapper(ElementWrapper): """ return bool(self.value) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Add ``self`` and ``rhs``. @@ -288,7 +288,7 @@ cdef class LieAlgebraElementWrapper(ElementWrapper): """ return type(self)(self._parent, self.value + right.value) - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Subtract ``self`` and ``rhs``. @@ -376,7 +376,7 @@ cdef class LieAlgebraElementWrapper(ElementWrapper): """ return self * (~x) - cpdef _acted_upon_(self, scalar, bint self_on_left): + cpdef _acted_upon_(self, scalar, bint self_on_left) noexcept: """ Return the action of a scalar on ``self``. @@ -572,7 +572,7 @@ cdef class LieSubalgebraElementWrapper(LieAlgebraElementWrapper): """ return self._parent.module()(self.value.to_vector(sparse=sparse)) - cpdef dict monomial_coefficients(self, bint copy=True): + cpdef dict monomial_coefficients(self, bint copy=True) noexcept: r""" Return a dictionary whose keys are indices of basis elements in the support of ``self`` and whose values are the @@ -605,7 +605,7 @@ cdef class LieSubalgebraElementWrapper(LieAlgebraElementWrapper): return dict(self._monomial_coefficients) return self._monomial_coefficients - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Add ``self`` and ``rhs``. @@ -631,7 +631,7 @@ cdef class LieSubalgebraElementWrapper(LieAlgebraElementWrapper): ret._monomial_coefficients = mc return ret - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Subtract ``self`` and ``rhs``. @@ -657,7 +657,7 @@ cdef class LieSubalgebraElementWrapper(LieAlgebraElementWrapper): ret._monomial_coefficients = mc return ret - cpdef _acted_upon_(self, scalar, bint self_on_left): + cpdef _acted_upon_(self, scalar, bint self_on_left) noexcept: """ Return the action of a scalar on ``self``. @@ -757,7 +757,7 @@ cdef class StructureCoefficientsElement(LieAlgebraMatrixWrapper): scalar_mult='·', strip_one=True)) - cpdef bracket(self, right): + cpdef bracket(self, right) noexcept: """ Return the Lie bracket ``[self, right]``. @@ -777,7 +777,7 @@ cdef class StructureCoefficientsElement(LieAlgebraMatrixWrapper): # We need this method because the LieAlgebra.bracket method (from the # category) calls this, where we are guaranteed to have the same parent. - cpdef _bracket_(self, right): + cpdef _bracket_(self, right) noexcept: """ Return the Lie bracket ``[self, right]``. @@ -832,7 +832,7 @@ cdef class StructureCoefficientsElement(LieAlgebraMatrixWrapper): if v != zero: yield (I[i], v) - cpdef to_vector(self, bint sparse=False): + cpdef to_vector(self, bint sparse=False) noexcept: """ Return ``self`` as a vector. @@ -865,7 +865,7 @@ cdef class StructureCoefficientsElement(LieAlgebraMatrixWrapper): gens = UEA.gens() return UEA.sum(c * gens[i] for i, c in self.value.items()) - cpdef dict monomial_coefficients(self, bint copy=True): + cpdef dict monomial_coefficients(self, bint copy=True) noexcept: """ Return the monomial coefficients of ``self`` as a dictionary. @@ -1072,7 +1072,7 @@ cdef class UntwistedAffineLieAlgebraElement(Element): lambda t: "t" + unicode_superscript(t), unicode_art('⋅'), unicode_art('⊗')) - cpdef dict t_dict(self): + cpdef dict t_dict(self) noexcept: r""" Return the ``dict``, whose keys are powers of `t` and values are elements of the classical Lie algebra, of ``self``. @@ -1088,7 +1088,7 @@ cdef class UntwistedAffineLieAlgebraElement(Element): """ return self._t_dict.copy() - cpdef c_coefficient(self): + cpdef c_coefficient(self) noexcept: r""" Return the coefficient of `c` of ``self``. @@ -1101,7 +1101,7 @@ cdef class UntwistedAffineLieAlgebraElement(Element): """ return self._c_coeff - cpdef d_coefficient(self): + cpdef d_coefficient(self) noexcept: r""" Return the coefficient of `d` of ``self``. @@ -1114,7 +1114,7 @@ cdef class UntwistedAffineLieAlgebraElement(Element): """ return self._d_coeff - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ Return the rich comparison of ``self`` with ``other``. @@ -1177,7 +1177,7 @@ cdef class UntwistedAffineLieAlgebraElement(Element): """ return bool(self._t_dict) or bool(self._c_coeff) or bool(self._d_coeff) - cpdef _add_(self, other): + cpdef _add_(self, other) noexcept: """ Add ``self`` and ``other``. @@ -1193,7 +1193,7 @@ cdef class UntwistedAffineLieAlgebraElement(Element): self._c_coeff + rt._c_coeff, self._d_coeff + rt._d_coeff) - cpdef _sub_(self, other): + cpdef _sub_(self, other) noexcept: """ Subtract ``self`` and ``other``. @@ -1217,7 +1217,7 @@ cdef class UntwistedAffineLieAlgebraElement(Element): self._c_coeff - rt._c_coeff, self._d_coeff - rt._d_coeff) - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ Negate ``self``. @@ -1232,7 +1232,7 @@ cdef class UntwistedAffineLieAlgebraElement(Element): return type(self)(self._parent, negate(self._t_dict), -self._c_coeff, -self._d_coeff) - cpdef _acted_upon_(self, x, bint self_on_left): + cpdef _acted_upon_(self, x, bint self_on_left) noexcept: """ Return ``self`` acted upon by ``x``. @@ -1250,7 +1250,7 @@ cdef class UntwistedAffineLieAlgebraElement(Element): x * self._c_coeff, x * self._d_coeff) - cpdef monomial_coefficients(self, bint copy=True): + cpdef monomial_coefficients(self, bint copy=True) noexcept: """ Return the monomial coefficients of ``self``. @@ -1280,7 +1280,7 @@ cdef class UntwistedAffineLieAlgebraElement(Element): d['d'] = self._d_coeff return d - cpdef bracket(self, right): + cpdef bracket(self, right) noexcept: """ Return the Lie bracket ``[self, right]``. @@ -1303,7 +1303,7 @@ cdef class UntwistedAffineLieAlgebraElement(Element): self, right = coercion_model.canonical_coercion(self, right) return self._bracket_(right) - cpdef _bracket_(self, y): + cpdef _bracket_(self, y) noexcept: """ Return the Lie bracket ``[self, y]``. @@ -1371,7 +1371,7 @@ cdef class UntwistedAffineLieAlgebraElement(Element): return type(self)(self._parent, d, c, self._parent.base_ring().zero()) - cpdef canonical_derivation(self): + cpdef canonical_derivation(self) noexcept: r""" Return the canonical derivation `d` applied to ``self``. @@ -1511,7 +1511,7 @@ cdef class LieObject(SageObject): """ Abstract base class for :class:`LieGenerator` and :class:`LieBracket`. """ - cpdef tuple to_word(self): + cpdef tuple to_word(self) noexcept: """ Return the word ("flattening") of ``self``. @@ -1645,7 +1645,7 @@ cdef class LieGenerator(LieObject): """ return im_gens[names.index(self._name)] - cpdef tuple to_word(self): + cpdef tuple to_word(self) noexcept: """ Return the word ("flattening") of ``self``. @@ -1831,7 +1831,7 @@ cdef class LieBracket(LieObject): return codomain.bracket(self._left._im_gens_(codomain, im_gens, names), self._right._im_gens_(codomain, im_gens, names)) - cpdef lift(self, dict UEA_gens_dict): + cpdef lift(self, dict UEA_gens_dict) noexcept: """ Lift ``self`` to the universal enveloping algebra. @@ -1860,7 +1860,7 @@ cdef class LieBracket(LieObject): return l*r - r*l - cpdef tuple to_word(self): + cpdef tuple to_word(self) noexcept: """ Return the word ("flattening") of ``self``. diff --git a/src/sage/algebras/octonion_algebra.pxd b/src/sage/algebras/octonion_algebra.pxd index 78500729bdc..459e8ea3070 100644 --- a/src/sage/algebras/octonion_algebra.pxd +++ b/src/sage/algebras/octonion_algebra.pxd @@ -8,12 +8,12 @@ from sage.modules.free_module_element cimport FreeModuleElement cdef class Octonion_generic(AlgebraElement): cdef FreeModuleElement vec - cpdef Octonion_generic conjugate(self) - cpdef quadratic_form(self) - cpdef norm(self) - cpdef abs(self) - cpdef real_part(self) - cpdef Octonion_generic imag_part(self) + cpdef Octonion_generic conjugate(self) noexcept + cpdef quadratic_form(self) noexcept + cpdef norm(self) noexcept + cpdef abs(self) noexcept + cpdef real_part(self) noexcept + cpdef Octonion_generic imag_part(self) noexcept cdef class Octonion(Octonion_generic): pass diff --git a/src/sage/algebras/octonion_algebra.pyx b/src/sage/algebras/octonion_algebra.pyx index 18101c48f66..aef4f54aa9d 100644 --- a/src/sage/algebras/octonion_algebra.pyx +++ b/src/sage/algebras/octonion_algebra.pyx @@ -116,7 +116,7 @@ cdef class Octonion_generic(AlgebraElement): """ return (self.__class__, (self._parent, self.vec)) - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: r""" Compare ``self`` to ``other`` with type ``op``. @@ -147,7 +147,7 @@ cdef class Octonion_generic(AlgebraElement): """ return hash(self.vec) - cpdef _add_(self, other): + cpdef _add_(self, other) noexcept: r""" Return ``self`` plus ``other``. @@ -161,7 +161,7 @@ cdef class Octonion_generic(AlgebraElement): """ return self.__class__(self._parent, self.vec + ( other).vec) - cpdef _sub_(self, other): + cpdef _sub_(self, other) noexcept: r""" Return ``self`` minus ``other``. @@ -191,7 +191,7 @@ cdef class Octonion_generic(AlgebraElement): """ return self.__class__(self._parent, -self.vec) - cpdef _lmul_(self, Element other): + cpdef _lmul_(self, Element other) noexcept: r""" Return ``self * other`` for a scalar ``other``. @@ -205,7 +205,7 @@ cdef class Octonion_generic(AlgebraElement): """ return self.__class__(self._parent, self.vec * other) - cpdef _rmul_(self, Element other): + cpdef _rmul_(self, Element other) noexcept: r""" Return ``self * other`` for a scalar ``other``. @@ -219,7 +219,7 @@ cdef class Octonion_generic(AlgebraElement): """ return self.__class__(self._parent, other * self.vec) - cpdef _mul_(self, other): + cpdef _mul_(self, other) noexcept: r""" Return ``self`` multiplied by ``other``. @@ -267,7 +267,7 @@ cdef class Octonion_generic(AlgebraElement): ret[k] += cl * cr * coeff return self.__class__(P, P._module(ret)) - cpdef _div_(self, other): + cpdef _div_(self, other) noexcept: """ Return ``self`` divided by ``other``. @@ -356,7 +356,7 @@ cdef class Octonion_generic(AlgebraElement): raise ZeroDivisionError return self.quadratic_form().inverse_of_unit() * self.conjugate() - cpdef Octonion_generic conjugate(self): + cpdef Octonion_generic conjugate(self) noexcept: r""" Return the conjugate of ``self``. @@ -372,7 +372,7 @@ cdef class Octonion_generic(AlgebraElement): v.set_unsafe(0, -v.get_unsafe(0)) return self.__class__(self._parent, v) - cpdef quadratic_form(self): + cpdef quadratic_form(self) noexcept: r""" Return the quadratic form of ``self``. @@ -395,7 +395,7 @@ cdef class Octonion_generic(AlgebraElement): ret += -( table[i])[i][1] * self.vec.get_unsafe(i) ** 2 return ret - cpdef norm(self): + cpdef norm(self) noexcept: r""" Return the norm of ``self``. @@ -423,7 +423,7 @@ cdef class Octonion_generic(AlgebraElement): """ return sqrt(self.quadratic_form()) - cpdef abs(self): + cpdef abs(self) noexcept: r""" Return the absolute value of ``self``. @@ -446,7 +446,7 @@ cdef class Octonion_generic(AlgebraElement): """ return self.norm() - cpdef real_part(self): + cpdef real_part(self) noexcept: r""" Return the real part of ``self``. @@ -466,7 +466,7 @@ cdef class Octonion_generic(AlgebraElement): """ return self.vec.get_unsafe(0) - cpdef Octonion_generic imag_part(self): + cpdef Octonion_generic imag_part(self) noexcept: r""" Return the imginary part of ``self``. @@ -542,7 +542,7 @@ cdef class Octonion(Octonion_generic): This is an element of the octonion algebra with parameters `a = b = c = -1`, which is a classical octonion number. """ - cpdef quadratic_form(self): + cpdef quadratic_form(self) noexcept: r""" Return the quadratic form of ``self``. @@ -561,7 +561,7 @@ cdef class Octonion(Octonion_generic): """ return self.vec * self.vec - cpdef norm(self): + cpdef norm(self) noexcept: r""" Return the norm of ``self``. diff --git a/src/sage/algebras/quatalg/quaternion_algebra_element.pxd b/src/sage/algebras/quatalg/quaternion_algebra_element.pxd index 243cae8e222..5a4f811443a 100644 --- a/src/sage/algebras/quatalg/quaternion_algebra_element.pxd +++ b/src/sage/algebras/quatalg/quaternion_algebra_element.pxd @@ -7,11 +7,11 @@ from sage.structure.element cimport AlgebraElement, RingElement, ModuleElement, from sage.categories.morphism cimport Morphism cdef class QuaternionAlgebraElement_abstract(AlgebraElement): - cpdef bint is_constant(self) - cdef _do_print(self, x, y, z, w) - cpdef conjugate(self) - cpdef reduced_norm(self) - cpdef reduced_trace(self) + cpdef bint is_constant(self) noexcept + cdef _do_print(self, x, y, z, w) noexcept + cpdef conjugate(self) noexcept + cpdef reduced_norm(self) noexcept + cpdef reduced_trace(self) noexcept cdef class QuaternionAlgebraElement_generic(QuaternionAlgebraElement_abstract): cdef object x, y, z, w @@ -21,8 +21,8 @@ cdef class QuaternionAlgebraElement_generic(QuaternionAlgebraElement_abstract): cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstract): cdef fmpz_poly_t x, y, z, w, a, b, modulus cdef mpz_t d - cdef inline canonicalize(self) + cdef inline canonicalize(self) noexcept cdef class QuaternionAlgebraElement_rational_field(QuaternionAlgebraElement_abstract): cdef mpz_t x, y, z, w, a, b, d - cdef inline canonicalize(self) + cdef inline canonicalize(self) noexcept diff --git a/src/sage/algebras/quatalg/quaternion_algebra_element.pyx b/src/sage/algebras/quatalg/quaternion_algebra_element.pyx index 723c284989e..a1dd86a224c 100644 --- a/src/sage/algebras/quatalg/quaternion_algebra_element.pyx +++ b/src/sage/algebras/quatalg/quaternion_algebra_element.pyx @@ -53,7 +53,7 @@ from sage.libs.flint.ntl_interface cimport * cdef mpz_t T1, T2, t3, t4, t5, t6, t7, t8, s1, s2, U1, U2 cdef fmpz_poly_t fT1, fT2, ft3, ft4, ft5, ft6, ft7, ft8, fs1, fs2, fU1, fU2 -cdef _clear_globals(): +cdef _clear_globals() noexcept: """ Clear all global variables allocated for optimization of quaternion algebra arithmetic. @@ -90,7 +90,7 @@ cdef _clear_globals(): fmpz_poly_clear(fU1) fmpz_poly_clear(fU2) -cdef _init_globals(): +cdef _init_globals() noexcept: """ Initialize all global variables allocated for optimization of quaternion algebra arithmetic, and register a hook to eventually @@ -137,7 +137,7 @@ cdef _init_globals(): # Initialize module-scope global C variables. _init_globals() -cdef to_quaternion(R, x): +cdef to_quaternion(R, x) noexcept: """ Internal function used implicitly by quaternion algebra creation. @@ -161,7 +161,7 @@ cdef to_quaternion(R, x): else: return R(x), R(0), R(0), R(0) -cdef inline print_coeff(y, i, bint atomic): +cdef inline print_coeff(y, i, bint atomic) noexcept: """ Internal function used implicitly by all quaternion algebra printing. @@ -219,7 +219,7 @@ cdef class QuaternionAlgebraElement_abstract(AlgebraElement): h = ((h+34125L)*51125L) ^ hash(x) return h - cpdef bint is_constant(self): + cpdef bint is_constant(self) noexcept: """ Return True if this quaternion is constant, i.e., has no i, j, or k term. @@ -335,7 +335,7 @@ cdef class QuaternionAlgebraElement_abstract(AlgebraElement): """ return self[0] or self[1] or self[2] or self[3] - cdef _do_print(self, x, y, z, w): + cdef _do_print(self, x, y, z, w) noexcept: """ Used internally by the print function. @@ -384,7 +384,7 @@ cdef class QuaternionAlgebraElement_abstract(AlgebraElement): """ return self._do_print(self[0], self[1], self[2], self[3]) - cpdef _richcmp_(self, right, int op): + cpdef _richcmp_(self, right, int op) noexcept: """ Comparing elements. @@ -412,7 +412,7 @@ cdef class QuaternionAlgebraElement_abstract(AlgebraElement): return res return rich_to_bool(op, 0) - cpdef conjugate(self): + cpdef conjugate(self) noexcept: """ Return the conjugate of the quaternion: if `\\theta = x + yi + zj + wk`, return `x - yi - zj - wk`; that is, return theta.reduced_trace() - theta. @@ -436,7 +436,7 @@ cdef class QuaternionAlgebraElement_abstract(AlgebraElement): """ return self.__class__(self._parent, (self[0], -self[1], -self[2], -self[3]), check=False) - cpdef reduced_trace(self): + cpdef reduced_trace(self) noexcept: """ Return the reduced trace of self: if `\\theta = x + yi + zj + wk`, then `\\theta` has reduced trace `2x`. @@ -451,7 +451,7 @@ cdef class QuaternionAlgebraElement_abstract(AlgebraElement): """ return 2*self[0] - cpdef reduced_norm(self): + cpdef reduced_norm(self) noexcept: """ Return the reduced norm of self: if `\\theta = x + yi + zj + wk`, then `\\theta` has reduced norm `x^2 - ay^2 - bz^2 + @@ -508,7 +508,7 @@ cdef class QuaternionAlgebraElement_abstract(AlgebraElement): """ return ~self.reduced_norm() * self.conjugate() - cpdef _rmul_(self, Element left): + cpdef _rmul_(self, Element left) noexcept: """ Return left*self, where left is in the base ring. @@ -523,7 +523,7 @@ cdef class QuaternionAlgebraElement_abstract(AlgebraElement): """ return self.__class__(self._parent, (left*self[0], left*self[1], left*self[2], left*self[3]), check=False) - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: """ Return self*right, where right is in the base ring. @@ -538,7 +538,7 @@ cdef class QuaternionAlgebraElement_abstract(AlgebraElement): """ return self.__class__(self._parent, (self[0]*right, self[1]*right, self[2]*right, self[3]*right), check=False) - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Return quotient of self by right. @@ -769,7 +769,7 @@ cdef class QuaternionAlgebraElement_generic(QuaternionAlgebraElement_abstract): return (unpickle_QuaternionAlgebraElement_generic_v0, (self._parent, (self.x, self.y, self.z, self.w))) - cpdef _add_(self, _right): + cpdef _add_(self, _right) noexcept: """ Return the sum of self and _right. @@ -785,7 +785,7 @@ cdef class QuaternionAlgebraElement_generic(QuaternionAlgebraElement_abstract): # TODO -- make this, etc. use __new__ return QuaternionAlgebraElement_generic(self._parent, (self.x + right.x, self.y + right.y, self.z + right.z, self.w + right.w), check=False) - cpdef _sub_(self, _right): + cpdef _sub_(self, _right) noexcept: """ Return the difference of self and _right. @@ -800,7 +800,7 @@ cdef class QuaternionAlgebraElement_generic(QuaternionAlgebraElement_abstract): cdef QuaternionAlgebraElement_generic right = _right return QuaternionAlgebraElement_generic(self._parent, (self.x - right.x, self.y - right.y, self.z - right.z, self.w - right.w), check=False) - cpdef _mul_(self, _right): + cpdef _mul_(self, _right) noexcept: """ Return the product of self and _right. @@ -928,7 +928,7 @@ cdef class QuaternionAlgebraElement_rational_field(QuaternionAlgebraElement_abst return x raise TypeError - cpdef bint is_constant(self): + cpdef bint is_constant(self) noexcept: """ Return True if this quaternion is constant, i.e., has no i, j, or k term. @@ -964,7 +964,7 @@ cdef class QuaternionAlgebraElement_rational_field(QuaternionAlgebraElement_abst """ return bool(mpz_sgn(self.x) or mpz_sgn(self.y) or mpz_sgn(self.z) or mpz_sgn(self.w)) - cpdef _richcmp_(self, _right, int op): + cpdef _richcmp_(self, _right, int op) noexcept: """ Compare two quaternions. @@ -1125,7 +1125,7 @@ cdef class QuaternionAlgebraElement_rational_field(QuaternionAlgebraElement_abst return (unpickle_QuaternionAlgebraElement_rational_field_v0, (self._parent, (self[0], self[1], self[2], self[3]))) - cpdef _add_(self, _right): + cpdef _add_(self, _right) noexcept: """ EXAMPLES:: @@ -1181,7 +1181,7 @@ cdef class QuaternionAlgebraElement_rational_field(QuaternionAlgebraElement_abst mpz_set(result.b, self.b) return result - cpdef _sub_(self, _right): + cpdef _sub_(self, _right) noexcept: """ EXAMPLES:: @@ -1222,7 +1222,7 @@ cdef class QuaternionAlgebraElement_rational_field(QuaternionAlgebraElement_abst mpz_set(result.b, self.b) return result - cpdef _mul_(self, _right): + cpdef _mul_(self, _right) noexcept: """ EXAMPLES:: @@ -1335,7 +1335,7 @@ cdef class QuaternionAlgebraElement_rational_field(QuaternionAlgebraElement_abst return result - cpdef reduced_norm(self): + cpdef reduced_norm(self) noexcept: """ Return the reduced norm of ``self``. @@ -1376,7 +1376,7 @@ cdef class QuaternionAlgebraElement_rational_field(QuaternionAlgebraElement_abst return result - cpdef conjugate(self): + cpdef conjugate(self) noexcept: """ Return the conjugate of this quaternion. @@ -1407,7 +1407,7 @@ cdef class QuaternionAlgebraElement_rational_field(QuaternionAlgebraElement_abst return result - cpdef reduced_trace(self): + cpdef reduced_trace(self) noexcept: """ Return the reduced trace of ``self``. @@ -1431,7 +1431,7 @@ cdef class QuaternionAlgebraElement_rational_field(QuaternionAlgebraElement_abst mpq_canonicalize(result.value) return result - cdef inline canonicalize(self): + cdef inline canonicalize(self) noexcept: """ Put the representation of this quaternion element into smallest form. For `a = (1/d)(x + yi + zj + wk)` we @@ -1785,7 +1785,7 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra return (unpickle_QuaternionAlgebraElement_number_field_v0, (self._parent, (self[0], self[1], self[2], self[3]))) - cpdef _add_(self, _right): + cpdef _add_(self, _right) noexcept: """ Add self and _right: @@ -1857,7 +1857,7 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra return result - cpdef _sub_(self, _right): + cpdef _sub_(self, _right) noexcept: """ Subtract _right from self. @@ -1906,7 +1906,7 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra return result - cpdef _mul_(self, _right): + cpdef _mul_(self, _right) noexcept: """ Multiply self and _right. @@ -2052,7 +2052,7 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra return result - cdef inline canonicalize(self): + cdef inline canonicalize(self) noexcept: """ Put the representation of this quaternion element into smallest form. For a = `(1/d)(x + yi + zj + wk)` we diff --git a/src/sage/arith/functions.pxd b/src/sage/arith/functions.pxd index 9ddfc38b38b..58ad13a30b7 100644 --- a/src/sage/arith/functions.pxd +++ b/src/sage/arith/functions.pxd @@ -1,3 +1,3 @@ -cpdef LCM_list(v) +cpdef LCM_list(v) noexcept -cdef LCM_generic(itr, ret) +cdef LCM_generic(itr, ret) noexcept diff --git a/src/sage/arith/functions.pyx b/src/sage/arith/functions.pyx index db49367b7f4..040a11ff0d6 100644 --- a/src/sage/arith/functions.pyx +++ b/src/sage/arith/functions.pyx @@ -124,7 +124,7 @@ def lcm(a, b=None): raise TypeError(f"unable to find lcm of {a!r} and {b!r}") -cpdef LCM_list(v): +cpdef LCM_list(v) noexcept: """ Return the LCM of an iterable ``v``. @@ -206,7 +206,7 @@ cpdef LCM_list(v): return z -cdef LCM_generic(itr, ret): +cdef LCM_generic(itr, ret) noexcept: """ Return the least common multiple of the element ``ret`` and the elements in the iterable ``itr``. diff --git a/src/sage/arith/long.pxd b/src/sage/arith/long.pxd index 3ea70cef571..ce6a70bc215 100644 --- a/src/sage/arith/long.pxd +++ b/src/sage/arith/long.pxd @@ -217,12 +217,12 @@ cdef inline bint integer_check_long(x, long* value, int* err) except -1: return 0 -cdef inline long dig(const digit* D, int n): +cdef inline long dig(const digit* D, int n) noexcept: # Convenient helper function for integer_check_long_py() return (D[n]) << (n * PyLong_SHIFT) -cdef inline bint integer_check_long_py(x, long* value, int* err): +cdef inline bint integer_check_long_py(x, long* value, int* err) noexcept: """ Return whether ``x`` is a python object of type ``int``. @@ -381,7 +381,7 @@ cdef inline bint integer_check_long_py(x, long* value, int* err): return 1 -cdef inline bint is_small_python_int(obj): +cdef inline bint is_small_python_int(obj) noexcept: """ Test whether Python object is a small Python integer. diff --git a/src/sage/arith/misc.py b/src/sage/arith/misc.py index d18e83309e5..aa0174580a1 100644 --- a/src/sage/arith/misc.py +++ b/src/sage/arith/misc.py @@ -2688,6 +2688,11 @@ def factor(n, proof=None, int_=False, algorithm='pari', verbose=0, **kwds): Traceback (most recent call last): ... TypeError: unable to factor 'xyz' + + Test that :issue:`35219` is fixed:: + + sage: len(factor(2^2203-1,proof=false)) + 1 """ try: m = n.factor diff --git a/src/sage/arith/multi_modular.pxd b/src/sage/arith/multi_modular.pxd index ca43eb3e23f..62534fce43c 100644 --- a/src/sage/arith/multi_modular.pxd +++ b/src/sage/arith/multi_modular.pxd @@ -13,11 +13,11 @@ cdef class MultiModularBasis_base(): cdef unsigned long _num_primes cdef mod_int _new_random_prime(self, set known_primes) except 1 - cdef mod_int last_prime(self) - cdef _realloc_to_new_count(self, new_count) + cdef mod_int last_prime(self) noexcept + cdef _realloc_to_new_count(self, new_count) noexcept cdef int _extend_moduli_to_height_c(self, mpz_t height) except -1 - cdef void _refresh_products(self, int start) - cdef void _refresh_prod(self) + cdef void _refresh_products(self, int start) noexcept + cdef void _refresh_prod(self) noexcept cdef void _refresh_precomputations(self, int start) except * cdef int min_moduli_count(self, mpz_t height) except -1 diff --git a/src/sage/arith/multi_modular.pyx b/src/sage/arith/multi_modular.pyx index a656742bd50..44a6059c6f1 100644 --- a/src/sage/arith/multi_modular.pyx +++ b/src/sage/arith/multi_modular.pyx @@ -101,7 +101,7 @@ cdef class MultiModularBasis_base(): mpz_init(self.product) mpz_init(self.half_product) - cdef _realloc_to_new_count(self, new_count): + cdef _realloc_to_new_count(self, new_count) noexcept: self.moduli = check_reallocarray(self.moduli, new_count, sizeof(mod_int)) self.partial_products = check_reallocarray(self.partial_products, new_count, sizeof(mpz_t)) self.C = check_reallocarray(self.C, new_count, sizeof(mod_int)) @@ -445,7 +445,7 @@ cdef class MultiModularBasis_base(): """ self._extend_moduli_to_count(self.n + count) - cdef void _refresh_products(self, int start): + cdef void _refresh_products(self, int start) noexcept: r""" Compute and store `\prod_j=1^{i-1} m_j` for i > start. """ @@ -460,7 +460,7 @@ cdef class MultiModularBasis_base(): mpz_clear(z) self._refresh_prod() - cdef void _refresh_prod(self): + cdef void _refresh_prod(self) noexcept: # record the product and half product for balancing the lifts. mpz_set(self.product, self.partial_products[self.n-1]) mpz_fdiv_q_ui(self.half_product, self.product, 2) @@ -492,7 +492,7 @@ cdef class MultiModularBasis_base(): return count - cdef mod_int last_prime(self): + cdef mod_int last_prime(self) noexcept: return self.moduli[self.n-1] cdef int mpz_reduce_tail(self, mpz_t z, mod_int* b, int offset, int len) except -1: diff --git a/src/sage/arith/power.pxd b/src/sage/arith/power.pxd index 7651245d2eb..33f043e9551 100644 --- a/src/sage/arith/power.pxd +++ b/src/sage/arith/power.pxd @@ -7,12 +7,12 @@ ctypedef fused ulong_or_object: object -cpdef generic_power(a, n) -cdef generic_power_long(a, long n) -cdef generic_power_pos(a, ulong_or_object n) # n > 0 +cpdef generic_power(a, n) noexcept +cdef generic_power_long(a, long n) noexcept +cdef generic_power_pos(a, ulong_or_object n) noexcept # n > 0 -cdef inline invert(a): +cdef inline invert(a) noexcept: """ Return ``a^(-1)``. """ @@ -21,7 +21,7 @@ cdef inline invert(a): return PyNumber_TrueDivide(type(a)(1), a) -cdef inline one(a): +cdef inline one(a) noexcept: """ Return ``a^0``. """ diff --git a/src/sage/arith/power.pyx b/src/sage/arith/power.pyx index acd5f885e85..65090f23c23 100644 --- a/src/sage/arith/power.pyx +++ b/src/sage/arith/power.pyx @@ -20,7 +20,7 @@ from cysignals.signals cimport sig_check from .long cimport integer_check_long -cpdef generic_power(a, n): +cpdef generic_power(a, n) noexcept: """ Return `a^n`. @@ -88,7 +88,7 @@ cpdef generic_power(a, n): return generic_power_pos(a, n) -cdef generic_power_long(a, long n): +cdef generic_power_long(a, long n) noexcept: """ As ``generic_power`` but where ``n`` is a C long. """ @@ -102,7 +102,7 @@ cdef generic_power_long(a, long n): return generic_power_pos(a, u) -cdef generic_power_pos(a, ulong_or_object n): +cdef generic_power_pos(a, ulong_or_object n) noexcept: """ Return `a^n` where `n > 0`. """ diff --git a/src/sage/calculus/integration.pyx b/src/sage/calculus/integration.pyx index 19b2dc2e4c8..621241436ae 100644 --- a/src/sage/calculus/integration.pyx +++ b/src/sage/calculus/integration.pyx @@ -43,10 +43,10 @@ cdef class PyFunctionWrapper: cdef list lx cdef class compiled_integrand: - cdef int c_f(self, double t): # void *params): + cdef int c_f(self, double t) noexcept: # void *params): return 0 -cdef double c_f(double t, void *params): +cdef double c_f(double t, void *params) noexcept: cdef double value cdef PyFunctionWrapper wrapper wrapper = params @@ -401,7 +401,7 @@ def numerical_integral(func, a, b=None, return result, abs_err -cdef double c_monte_carlo_f(double *t, size_t dim, void *params): +cdef double c_monte_carlo_f(double *t, size_t dim, void *params) noexcept: cdef double value cdef PyFunctionWrapper wrapper wrapper = params @@ -421,7 +421,7 @@ cdef double c_monte_carlo_f(double *t, size_t dim, void *params): return value -cdef double c_monte_carlo_ff(double *x, size_t dim, void *params): +cdef double c_monte_carlo_ff(double *x, size_t dim, void *params) noexcept: cdef double result ( params).call_c(x, &result) return result diff --git a/src/sage/calculus/interpolation.pxd b/src/sage/calculus/interpolation.pxd index 9d60459a03b..2d729228149 100644 --- a/src/sage/calculus/interpolation.pxd +++ b/src/sage/calculus/interpolation.pxd @@ -8,5 +8,5 @@ cdef class Spline: cdef int started cdef object v - cdef start_interp(self) - cdef stop_interp(self) + cdef start_interp(self) noexcept + cdef stop_interp(self) noexcept diff --git a/src/sage/calculus/interpolation.pyx b/src/sage/calculus/interpolation.pyx index 83bc83d1797..59f9fcc8e7a 100644 --- a/src/sage/calculus/interpolation.pyx +++ b/src/sage/calculus/interpolation.pyx @@ -243,7 +243,7 @@ cdef class Spline: """ return str(self.v) - cdef start_interp(self): + cdef start_interp(self) noexcept: if self.started: sig_free(self.x) sig_free(self.y) @@ -271,7 +271,7 @@ cdef class Spline: gsl_spline_init (self.spline, self.x, self.y, n) self.started = 1 - cdef stop_interp(self): + cdef stop_interp(self) noexcept: if not self.started: return sig_free(self.x) diff --git a/src/sage/calculus/ode.pxd b/src/sage/calculus/ode.pxd index e517fe0c401..2de37b91764 100644 --- a/src/sage/calculus/ode.pxd +++ b/src/sage/calculus/ode.pxd @@ -1,4 +1,4 @@ cdef class ode_system: - cdef int c_j(self,double , double *, double *,double *) + cdef int c_j(self,double , double *, double *,double *) noexcept - cdef int c_f(self,double t, double* , double* ) + cdef int c_f(self,double t, double* , double* ) noexcept diff --git a/src/sage/calculus/ode.pyx b/src/sage/calculus/ode.pyx index f1004b9b438..32ccfab5dfc 100644 --- a/src/sage/calculus/ode.pyx +++ b/src/sage/calculus/ode.pyx @@ -33,31 +33,31 @@ cdef class PyFunctionWrapper: cdef object the_parameters cdef int y_n - cdef set_yn(self,x): + cdef set_yn(self,x) noexcept: self.y_n = x cdef class ode_system: - cdef int c_j(self,double t, double *y, double *dfdy,double *dfdt): #void *params): + cdef int c_j(self,double t, double *y, double *dfdy,double *dfdt) noexcept: #void *params): return 0 - cdef int c_f(self,double t, double* y, double* dydt): #void *params): + cdef int c_f(self,double t, double* y, double* dydt) noexcept: #void *params): return 0 -cdef int c_jac_compiled(double t, double *y, double *dfdy,double *dfdt, void * params): +cdef int c_jac_compiled(double t, double *y, double *dfdy,double *dfdt, void * params) noexcept: cdef int status cdef ode_system wrapper wrapper = params status = wrapper.c_j(t,y,dfdy,dfdt) #Could add parameters return status -cdef int c_f_compiled(double t, double *y, double *dydt, void *params): +cdef int c_f_compiled(double t, double *y, double *dydt, void *params) noexcept: cdef int status cdef ode_system wrapper wrapper = params status = wrapper.c_f(t,y,dydt) #Could add parameters return status -cdef int c_jac(double t,double *y,double *dfdy,double *dfdt,void *params): +cdef int c_jac(double t,double *y,double *dfdy,double *dfdt,void *params) noexcept: cdef int i cdef int j cdef int y_n @@ -84,7 +84,7 @@ cdef int c_jac(double t,double *y,double *dfdy,double *dfdt,void *params): except Exception: return -1 -cdef int c_f(double t,double* y, double* dydt,void *params): +cdef int c_f(double t,double* y, double* dydt,void *params) noexcept: cdef int i cdef int y_n cdef int param_n diff --git a/src/sage/calculus/riemann.pyx b/src/sage/calculus/riemann.pyx index a4f9545bffb..0b80a29da70 100644 --- a/src/sage/calculus/riemann.pyx +++ b/src/sage/calculus/riemann.pyx @@ -291,7 +291,7 @@ cdef class Riemann_Map: """ return "A Riemann or Ahlfors mapping of a figure to the unit circle." - cdef _generate_theta_array(self): + cdef _generate_theta_array(self) noexcept: """ Generates the essential data for the Riemann map, primarily the Szegő kernel and boundary correspondence. @@ -515,7 +515,7 @@ cdef class Riemann_Map: return np.column_stack( [self.tk2, self.theta_array[boundary]]).tolist() - cdef _generate_interior_mapper(self): + cdef _generate_interior_mapper(self) noexcept: """ Generates the data necessary to use the :meth:`riemann_map` function. As much setup as possible is done here to minimize the computation @@ -568,7 +568,7 @@ cdef class Riemann_Map: cdef np.ndarray[double complex, ndim=1] pq = self.cps[:,list(range(N))+[0]].flatten() self.pre_q_vector = pq - cpdef riemann_map(self, COMPLEX_T pt): + cpdef riemann_map(self, COMPLEX_T pt) noexcept: """ Return the Riemann mapping of a point. @@ -619,7 +619,7 @@ cdef class Riemann_Map: self.pre_q_vector - pt1) return -np.dot(self.p_vector, q_vector) - cdef _generate_inverse_mapper(self): + cdef _generate_inverse_mapper(self) noexcept: """ Generates the data necessary to use the :meth:`inverse_riemann_map` function. As much setup as possible is @@ -656,7 +656,7 @@ cdef class Riemann_Map: for i in range(N): self.cosalpha[k, i] = cos(-theta_array[k, i]) - cpdef inverse_riemann_map(self, COMPLEX_T pt): + cpdef inverse_riemann_map(self, COMPLEX_T pt) noexcept: """ Return the inverse Riemann mapping of a point. @@ -764,7 +764,7 @@ cdef class Riemann_Map: pointsize=thickness) return sum(plots) - cpdef compute_on_grid(self, plot_range, int x_points): + cpdef compute_on_grid(self, plot_range, int x_points) noexcept: """ Compute the Riemann map on a grid of points. @@ -1060,7 +1060,7 @@ cdef class Riemann_Map: (ymin, ymax),options)) return g -cdef comp_pt(clist, loop=True): +cdef comp_pt(clist, loop=True) noexcept: """ Utility function to convert the list of complex numbers ``xderivs = get_derivatives(z_values, xstep, ystep)[0]`` to the plottable @@ -1090,7 +1090,7 @@ cdef comp_pt(clist, loop=True): return list2 cpdef get_derivatives(np.ndarray[COMPLEX_T, ndim=2] z_values, FLOAT_T xstep, - FLOAT_T ystep): + FLOAT_T ystep) noexcept: """ Computes the r*e^(I*theta) form of derivatives from the grid of points. The derivatives are computed using quick-and-dirty taylor expansion and @@ -1146,7 +1146,7 @@ cpdef get_derivatives(np.ndarray[COMPLEX_T, ndim=2] z_values, FLOAT_T xstep, cpdef complex_to_spiderweb(np.ndarray[COMPLEX_T, ndim = 2] z_values, np.ndarray[FLOAT_T, ndim = 2] dr, np.ndarray[FLOAT_T, ndim = 2] dtheta, - spokes, circles, rgbcolor, thickness, withcolor, min_mag): + spokes, circles, rgbcolor, thickness, withcolor, min_mag) noexcept: """ Converts a grid of complex numbers into a matrix containing rgb data for the Riemann spiderweb plot. @@ -1263,7 +1263,7 @@ cpdef complex_to_spiderweb(np.ndarray[COMPLEX_T, ndim = 2] z_values, return rgb -cpdef complex_to_rgb(np.ndarray[COMPLEX_T, ndim = 2] z_values): +cpdef complex_to_rgb(np.ndarray[COMPLEX_T, ndim = 2] z_values) noexcept: r""" Convert from a (Numpy) array of complex numbers to its corresponding matrix of RGB values. For internal use of :meth:`~Riemann_Map.plot_colored` @@ -1368,7 +1368,7 @@ cpdef complex_to_rgb(np.ndarray[COMPLEX_T, ndim = 2] z_values): sig_off() return rgb -cpdef analytic_boundary(FLOAT_T t, int n, FLOAT_T epsilon): +cpdef analytic_boundary(FLOAT_T t, int n, FLOAT_T epsilon) noexcept: """ Provides an exact (for n = infinity) Riemann boundary correspondence for the ellipse with axes 1 + epsilon and 1 - epsilon. The @@ -1417,7 +1417,7 @@ cpdef analytic_boundary(FLOAT_T t, int n, FLOAT_T epsilon): return result -cpdef cauchy_kernel(t, args): +cpdef cauchy_kernel(t, args) noexcept: """ Intermediate function for the integration in :meth:`~Riemann_Map.analytic_interior`. @@ -1463,7 +1463,7 @@ cpdef cauchy_kernel(t, args): return None -cpdef analytic_interior(COMPLEX_T z, int n, FLOAT_T epsilon): +cpdef analytic_interior(COMPLEX_T z, int n, FLOAT_T epsilon) noexcept: """ Provides a nearly exact computation of the Riemann Map of an interior point of the ellipse with axes 1 + epsilon and 1 - epsilon. It is diff --git a/src/sage/calculus/transforms/dft.py b/src/sage/calculus/transforms/dft.py index b413bc0ea81..1b165fa6503 100644 --- a/src/sage/calculus/transforms/dft.py +++ b/src/sage/calculus/transforms/dft.py @@ -277,7 +277,7 @@ def plot(self): S = self.list() return line([[RR(I[i]), RR(S[i])] for i in range(len(I) - 1)]) - def dft(self, chi=lambda x: x): + def dft(self, chi=None): r""" A discrete Fourier transform "over `\QQ`" using exact `N`-th roots of unity. @@ -340,6 +340,8 @@ def dft(self, chi=lambda x: x): implemented Group (permutation, matrix), call .characters() and test if the index list is the set of conjugacy classes. """ + if chi is None: + chi = lambda x: x J = self.index_object() # index set of length N N = len(J) S = self.list() diff --git a/src/sage/categories/action.pxd b/src/sage/categories/action.pxd index 5883adebc97..a22a37cc22a 100644 --- a/src/sage/categories/action.pxd +++ b/src/sage/categories/action.pxd @@ -8,10 +8,10 @@ cdef class Action(Functor): cdef readonly op cdef readonly bint _is_left cdef US - cdef underlying_set(self) + cdef underlying_set(self) noexcept - cdef _act_convert(self, g, x) - cpdef _act_(self, g, x) + cdef _act_convert(self, g, x) noexcept + cpdef _act_(self, g, x) noexcept cdef class InverseAction(Action): diff --git a/src/sage/categories/action.pyx b/src/sage/categories/action.pyx index 0d564e46c4d..b164e9213ce 100644 --- a/src/sage/categories/action.pyx +++ b/src/sage/categories/action.pyx @@ -66,7 +66,7 @@ from sage.categories import homset from weakref import ref -cdef inline category(x): +cdef inline category(x) noexcept: try: return x.category() except AttributeError: @@ -178,7 +178,7 @@ cdef class Action(Functor): else: raise TypeError("actions should be called with 1 or 2 arguments") - cdef _act_convert(self, g, x): + cdef _act_convert(self, g, x) noexcept: """ Let ``g`` act on ``x`` under this action, converting ``g`` and ``x`` to the correct parents first. @@ -190,7 +190,7 @@ cdef class Action(Functor): x = U(x) return self._act_(g, x) - cpdef _act_(self, g, x): + cpdef _act_(self, g, x) noexcept: """ Let ``g`` act on ``x`` under this action. @@ -251,7 +251,7 @@ cdef class Action(Functor): def actor(self): return self.G - cdef underlying_set(self): + cdef underlying_set(self) noexcept: """ The set on which the actor acts (it is not necessarily the codomain of the action). @@ -410,7 +410,7 @@ cdef class InverseAction(Action): """ return (type(self), (self._action,)) - cpdef _act_(self, g, x): + cpdef _act_(self, g, x) noexcept: if self.S_precomposition is not None: x = self.S_precomposition(x) return self._action._act_(~g, x) @@ -498,7 +498,7 @@ cdef class PrecomposedAction(Action): """ return (type(self), (self._action, self.G_precomposition, self.S_precomposition)) - cpdef _act_(self, g, x): + cpdef _act_(self, g, x) noexcept: if self.G_precomposition is not None: g = self.G_precomposition._call_(g) if self.S_precomposition is not None: @@ -569,7 +569,7 @@ cdef class ActionEndomorphism(Morphism): self._action = action self._g = g - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for pickling and copying. @@ -591,7 +591,7 @@ cdef class ActionEndomorphism(Morphism): slots['_g'] = self._g return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for pickling and copying. @@ -612,7 +612,7 @@ cdef class ActionEndomorphism(Morphism): self._g = _slots['_g'] Morphism._update_slots(self, _slots) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: return self._action._act_(self._g, x) def _repr_(self): diff --git a/src/sage/categories/bimodules.py b/src/sage/categories/bimodules.py index eccadf20a02..eec2f674aa7 100644 --- a/src/sage/categories/bimodules.py +++ b/src/sage/categories/bimodules.py @@ -37,22 +37,24 @@ class Bimodules(CategoryWithParameters): def __init__(self, left_base, right_base, name=None): """ + The ``name`` parameter is ignored. + EXAMPLES:: sage: C = Bimodules(QQ, ZZ) sage: TestSuite(C).run() """ - if not ( left_base in Rings() or - (isinstance(left_base, Category) - and left_base.is_subcategory(Rings())) ): + if not (left_base in Rings() or + (isinstance(left_base, Category) + and left_base.is_subcategory(Rings()))): raise ValueError("the left base must be a ring or a subcategory of Rings()") - if not ( right_base in Rings() or - (isinstance(right_base, Category) - and right_base.is_subcategory(Rings())) ): + if not (right_base in Rings() or + (isinstance(right_base, Category) + and right_base.is_subcategory(Rings()))): raise ValueError("the right base must be a ring or a subcategory of Rings()") self._left_base_ring = left_base self._right_base_ring = right_base - Category.__init__(self, name) + Category.__init__(self) def _make_named_class_key(self, name): r""" diff --git a/src/sage/categories/category.py b/src/sage/categories/category.py index 29bce8ee415..fcf25b75fd4 100644 --- a/src/sage/categories/category.py +++ b/src/sage/categories/category.py @@ -118,6 +118,7 @@ _join_cache = WeakValueDictionary() + class Category(UniqueRepresentation, SageObject): r""" The base class for modeling mathematical categories, like for example: @@ -448,7 +449,7 @@ class of ``C`` is a dynamic subclass ``Cs_with_category`` of cls = cls.__base__ return super().__classcall__(cls, *args, **options) - def __init__(self, s=None): + def __init__(self): """ Initialize this category. @@ -468,12 +469,10 @@ def __init__(self, s=None): .. NOTE:: - Specifying the name of this category by passing a string - is deprecated. If the default name (built from the name of - the class) is not adequate, please use + If the default name of the category (built from the name of + the class) is not adequate, please implement :meth:`_repr_object_names` to customize it. """ - assert s is None self.__class__ = dynamic_class("{}_with_category".format(self.__class__.__name__), (self.__class__, self.subcategory_class, ), cache=False, reduction=None, @@ -491,49 +490,38 @@ def _label(self): """ t = str(self.__class__.__base__) - t = t[t.rfind('.')+1:] + t = t[t.rfind('.') + 1:] return t[:t.rfind("'")] - # TODO: move this code into the method _repr_object_names once passing a string is not accepted anymore - @lazy_attribute - def __repr_object_names(self): + def _repr_object_names(self): """ - Determine the name of the objects of this category - from its type, if it has not been explicitly given - at initialisation. + Return the name of the objects of this category. EXAMPLES:: - sage: Rings()._Category__repr_object_names - 'rings' - sage: PrincipalIdealDomains()._Category__repr_object_names - 'principal ideal domains' + sage: FiniteGroups()._repr_object_names() + 'finite groups' + sage: AlgebrasWithBasis(QQ)._repr_object_names() + 'algebras with basis over Rational Field' + + TESTS:: sage: Rings() Category of rings + sage: Rings()._repr_object_names() + 'rings' + sage: PrincipalIdealDomains()._repr_object_names() + 'principal ideal domains' """ i = -1 s = self._label - while i < len(s)-1: + while i < len(s) - 1: for i in range(len(s)): if s[i].isupper(): - s = s[:i] + " " + s[i].lower() + s[i+1:] + s = s[:i] + " " + s[i].lower() + s[i + 1:] break return s.lstrip() - def _repr_object_names(self): - """ - Return the name of the objects of this category. - - EXAMPLES:: - - sage: FiniteGroups()._repr_object_names() - 'finite groups' - sage: AlgebrasWithBasis(QQ)._repr_object_names() - 'algebras with basis over Rational Field' - """ - return self.__repr_object_names - def _short_name(self): """ Return a CamelCase name for this category. @@ -1256,7 +1244,7 @@ def structure(self): recursively from the result of :meth:`additional_structure` on the super categories of ``self``. """ - result = { D for C in self.super_categories() for D in C.structure() } + result = {D for C in self.super_categories() for D in C.structure()} if self.additional_structure() is not None: result.add(self) return frozenset(result) @@ -1319,8 +1307,7 @@ def is_full_subcategory(self, other): False """ return self.is_subcategory(other) and \ - len(self.structure()) == \ - len(other.structure()) + len(self.structure()) == len(other.structure()) @cached_method def full_super_categories(self): @@ -1446,27 +1433,26 @@ def _test_category(self, **options): Traceback (most recent call last): ... AssertionError: Category of my objects is not a subcategory of Objects() - """ - from sage.categories.objects import Objects + from sage.categories.objects import Objects from sage.categories.sets_cat import Sets tester = self._tester(**options) tester.assertTrue(isinstance(self.super_categories(), list), - "%s.super_categories() should return a list" % self) + "%s.super_categories() should return a list" % self) tester.assertTrue(self.is_subcategory(Objects()), - "%s is not a subcategory of Objects()" % self) + "%s is not a subcategory of Objects()" % self) tester.assertTrue(isinstance(self.parent_class, type)) tester.assertTrue(all(not isinstance(cat, JoinCategory) for cat in self._super_categories)) if not isinstance(self, JoinCategory): - tester.assertTrue(all(self._cmp_key > cat._cmp_key for cat in self._super_categories)) - tester.assertTrue(self.is_subcategory( Category.join(self.super_categories()) )) # Not an obviously passing test with axioms + tester.assertTrue(all(self._cmp_key > cat._cmp_key for cat in self._super_categories)) + tester.assertTrue(self.is_subcategory(Category.join(self.super_categories()))) # Not an obviously passing test with axioms for category in self._all_super_categories_proper: if self.is_full_subcategory(category): tester.assertTrue(any(cat.is_subcategory(category) - for cat in self.full_super_categories()), - "Every full super category should be a super category" - "of some immediate full super category") + for cat in self.full_super_categories()), + "Every full super category should be a super category" + "of some immediate full super category") if self.is_subcategory(Sets()): tester.assertTrue(isinstance(self.parent_class, type)) @@ -1588,7 +1574,7 @@ def _make_named_class(self, name, method_provider, cache=False, picklable=True): doccls = cls else: # Otherwise, check XXXMethods - assert inspect.isclass(method_provider_cls),\ + assert inspect.isclass(method_provider_cls), \ "%s.%s should be a class" % (cls.__name__, method_provider) mro = inspect.getmro(method_provider_cls) if len(mro) > 2 or (len(mro) == 2 and mro[1] is not object): @@ -1941,7 +1927,7 @@ def _meet_(self, other): appropriate convention for AB. """ - if self is other: # useful? fast pathway + if self is other: # useful? fast pathway return self elif self.is_subcategory(other): return other @@ -2050,14 +2036,13 @@ def _with_axiom_as_tuple(self, axiom): return (axiom_attribute(self),) warn(("Expecting {}.{} to be a subclass of CategoryWithAxiom to" " implement a category with axiom; got {}; ignoring").format( - self.__class__.__base__.__name__, axiom, axiom_attribute)) + self.__class__.__base__.__name__, axiom, axiom_attribute)) # self does not implement this axiom - result = (self, ) + \ - tuple(cat - for category in self._super_categories - for cat in category._with_axiom_as_tuple(axiom)) - hook = getattr(self, axiom+"_extra_super_categories", None) + result = (self, ) + tuple(cat + for category in self._super_categories + for cat in category._with_axiom_as_tuple(axiom)) + hook = getattr(self, axiom + "_extra_super_categories", None) if hook is not None: assert inspect.ismethod(hook) result += tuple(hook()) @@ -2593,6 +2578,7 @@ def is_Category(x): """ return isinstance(x, Category) + @cached_function def category_sample(): r""" @@ -2606,7 +2592,8 @@ def category_sample(): sage: from sage.categories.category import category_sample sage: sorted(category_sample(), key=str) # needs sage.groups - [Category of G-sets for Symmetric group of order 8! as a permutation group, + [Category of Coxeter groups, + Category of G-sets for Symmetric group of order 8! as a permutation group, Category of Hecke modules over Rational Field, Category of Lie algebras over Rational Field, Category of additive magmas, ..., @@ -2900,6 +2887,7 @@ def _subcategory_hook_(self, C): return False return Unknown + ############################################################# # Join of several categories ############################################################# @@ -2948,11 +2936,11 @@ def __init__(self, super_categories, **kwds): INPUT: - - super_categories -- Categories to join. This category will + - ``super_categories`` -- Categories to join. This category will consist of objects and morphisms that lie in all of these categories. - - name -- An optional name for this category. + - ``name`` -- ignored TESTS:: @@ -2960,17 +2948,13 @@ def __init__(self, super_categories, **kwds): sage: C = JoinCategory((Groups(), CommutativeAdditiveMonoids())); C Join of Category of groups and Category of commutative additive monoids sage: TestSuite(C).run() - """ assert len(super_categories) >= 2 assert all(not isinstance(category, JoinCategory) for category in super_categories) # Use __super_categories to not overwrite the lazy attribute Category._super_categories # Maybe this would not be needed if the flattening/sorting is does consistently? self.__super_categories = list(super_categories) - if 'name' in kwds: - Category.__init__(self, kwds['name']) - else: - Category.__init__(self) + Category.__init__(self) def _make_named_class_key(self, name): r""" diff --git a/src/sage/categories/category_cy_helper.pxd b/src/sage/categories/category_cy_helper.pxd index f50ce4e8226..c7bf3759712 100644 --- a/src/sage/categories/category_cy_helper.pxd +++ b/src/sage/categories/category_cy_helper.pxd @@ -1,7 +1,7 @@ -cpdef tuple _sort_uniq(categories) +cpdef tuple _sort_uniq(categories) noexcept cdef class AxiomContainer(dict): pass -cpdef tuple canonicalize_axioms(AxiomContainer all_axioms, axioms) +cpdef tuple canonicalize_axioms(AxiomContainer all_axioms, axioms) noexcept from sage.misc.classcall_metaclass cimport ClasscallMetaclass -cpdef tuple _flatten_categories(categories, ClasscallMetaclass JoinCategory) -cpdef tuple join_as_tuple(tuple categories, tuple axioms, tuple ignore_axioms) +cpdef tuple _flatten_categories(categories, ClasscallMetaclass JoinCategory) noexcept +cpdef tuple join_as_tuple(tuple categories, tuple axioms, tuple ignore_axioms) noexcept diff --git a/src/sage/categories/category_cy_helper.pyx b/src/sage/categories/category_cy_helper.pyx index 1d0c5a2ad41..6ed38f4d00e 100644 --- a/src/sage/categories/category_cy_helper.pyx +++ b/src/sage/categories/category_cy_helper.pyx @@ -21,7 +21,7 @@ AUTHOR: ####################################### # Sorting -cpdef inline tuple category_sort_key(object category): +cpdef inline tuple category_sort_key(object category) noexcept: """ Return ``category._cmp_key``. @@ -38,7 +38,7 @@ cpdef inline tuple category_sort_key(object category): """ return category._cmp_key -cpdef tuple _sort_uniq(categories): +cpdef tuple _sort_uniq(categories) noexcept: """ Return the categories after sorting them and removing redundant categories. @@ -72,7 +72,7 @@ cpdef tuple _sort_uniq(categories): result.append(category) return tuple(result) -cpdef tuple _flatten_categories(categories, ClasscallMetaclass JoinCategory): +cpdef tuple _flatten_categories(categories, ClasscallMetaclass JoinCategory) noexcept: """ Return the tuple of categories in ``categories``, while flattening join categories. @@ -108,7 +108,7 @@ cpdef tuple _flatten_categories(categories, ClasscallMetaclass JoinCategory): ############################################# # Join -cdef bint is_supercategory_of_done(new_cat, dict done): +cdef bint is_supercategory_of_done(new_cat, dict done) noexcept: # This is a helper function. It replaces the closure # any(cat.is_subcategory(new_cat) for cat in done) for cat in done: @@ -116,7 +116,7 @@ cdef bint is_supercategory_of_done(new_cat, dict done): return True return False -cpdef tuple join_as_tuple(tuple categories, tuple axioms, tuple ignore_axioms): +cpdef tuple join_as_tuple(tuple categories, tuple axioms, tuple ignore_axioms) noexcept: """ Helper for :meth:`~sage.categories.category.Category.join`. @@ -267,7 +267,7 @@ cdef class AxiomContainer(dict): return self -cpdef inline get_axiom_index(AxiomContainer all_axioms, str axiom): +cpdef inline get_axiom_index(AxiomContainer all_axioms, str axiom) noexcept: """ Helper function: Return the rank of an axiom. @@ -286,7 +286,7 @@ cpdef inline get_axiom_index(AxiomContainer all_axioms, str axiom): return (all_axioms)[axiom] -cpdef tuple canonicalize_axioms(AxiomContainer all_axioms, axioms): +cpdef tuple canonicalize_axioms(AxiomContainer all_axioms, axioms) noexcept: r""" Canonicalize a set of axioms. diff --git a/src/sage/categories/category_types.py b/src/sage/categories/category_types.py index c9e2fe79130..4ead4f23530 100644 --- a/src/sage/categories/category_types.py +++ b/src/sage/categories/category_types.py @@ -171,6 +171,8 @@ def __init__(self, base, name=None): r""" Initialize ``self``. + The ``name`` parameter is ignored. + EXAMPLES:: sage: S = Spec(ZZ) @@ -183,7 +185,7 @@ def __init__(self, base, name=None): sage: TestSuite(C).run() """ self.__base = base - Category.__init__(self, name) + Category.__init__(self) def _test_category_over_bases(self, **options): """ @@ -529,13 +531,15 @@ def __init__(self, ambient, name=None): """ Initialize ``self``. + The parameter ``name`` is ignored. + EXAMPLES:: sage: C = Ideals(IntegerRing()) sage: TestSuite(C).run() """ self.__ambient = ambient - Category.__init__(self, name) + Category.__init__(self) def ambient(self): """ diff --git a/src/sage/categories/category_with_axiom.py b/src/sage/categories/category_with_axiom.py index 4775d4e5bf1..bb9dbbe2347 100644 --- a/src/sage/categories/category_with_axiom.py +++ b/src/sage/categories/category_with_axiom.py @@ -269,7 +269,7 @@ class from the base category class:: covers the following examples:: sage: FiniteCoxeterGroups() - Category of finite coxeter groups + Category of finite Coxeter groups sage: FiniteCoxeterGroups() is CoxeterGroups().Finite() True sage: FiniteCoxeterGroups._base_category_class_and_axiom_origin diff --git a/src/sage/categories/complex_reflection_or_generalized_coxeter_groups.py b/src/sage/categories/complex_reflection_or_generalized_coxeter_groups.py index 89667bfc237..d3908a8db03 100644 --- a/src/sage/categories/complex_reflection_or_generalized_coxeter_groups.py +++ b/src/sage/categories/complex_reflection_or_generalized_coxeter_groups.py @@ -130,7 +130,7 @@ def Irreducible(self): sage: ComplexReflectionGroups().Irreducible() Category of irreducible complex reflection groups sage: CoxeterGroups().Irreducible() - Category of irreducible coxeter groups + Category of irreducible Coxeter groups TESTS:: diff --git a/src/sage/categories/coxeter_groups.py b/src/sage/categories/coxeter_groups.py index b5e5da9ea1a..71285521a5e 100644 --- a/src/sage/categories/coxeter_groups.py +++ b/src/sage/categories/coxeter_groups.py @@ -41,7 +41,7 @@ class CoxeterGroups(Category_singleton): EXAMPLES:: sage: C = CoxeterGroups(); C - Category of coxeter groups + Category of Coxeter groups sage: C.super_categories() [Category of generalized coxeter groups] @@ -128,6 +128,17 @@ def additional_structure(self): Finite = LazyImport('sage.categories.finite_coxeter_groups', 'FiniteCoxeterGroups') Algebras = LazyImport('sage.categories.coxeter_group_algebras', 'CoxeterGroupAlgebras') + def _repr_object_names(self): + """ + Return the name of the objects of this category. + + EXAMPLES:: + + sage: CoxeterGroups().Finite() + Category of finite Coxeter groups + """ + return "Coxeter groups" + class ParentMethods: @abstract_method def coxeter_matrix(self): diff --git a/src/sage/categories/enumerated_sets.py b/src/sage/categories/enumerated_sets.py index b0ea05d0563..8ae3270491c 100644 --- a/src/sage/categories/enumerated_sets.py +++ b/src/sage/categories/enumerated_sets.py @@ -313,8 +313,7 @@ def iterator_range(self, start=None, stop=None, step=None): if stop is None: if start is None: if step is None: - for x in self: - yield x + yield from self return start = 0 elif start < 0: @@ -793,8 +792,7 @@ def _iterator_from_list(self): sage: [next(it), next(it), next(it)] [1, 2, 3] """ - for x in self.tuple(): - yield x + yield from self.tuple() def _iterator_from_next(self): """ diff --git a/src/sage/categories/examples/semigroups_cython.pyx b/src/sage/categories/examples/semigroups_cython.pyx index b456c2868f8..2b7b76c00e3 100644 --- a/src/sage/categories/examples/semigroups_cython.pyx +++ b/src/sage/categories/examples/semigroups_cython.pyx @@ -85,7 +85,7 @@ cdef class LeftZeroSemigroupElement(Element): """ return LeftZeroSemigroupElement, (self._parent, self._value) - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ EXAMPLES:: @@ -100,7 +100,7 @@ cdef class LeftZeroSemigroupElement(Element): right = (other)._value return PyObject_RichCompare(left, right, op) - cpdef _mul_(self, other): + cpdef _mul_(self, other) noexcept: """ EXAMPLES:: diff --git a/src/sage/categories/finite_complex_reflection_groups.py b/src/sage/categories/finite_complex_reflection_groups.py index 3ee374b739c..80ff28a90f2 100644 --- a/src/sage/categories/finite_complex_reflection_groups.py +++ b/src/sage/categories/finite_complex_reflection_groups.py @@ -135,7 +135,7 @@ def WellGenerated(self): desired output (well generated does not appear):: sage: CoxeterGroups().Finite() - Category of finite coxeter groups + Category of finite Coxeter groups """ return self._with_axiom('WellGenerated') diff --git a/src/sage/categories/finite_coxeter_groups.py b/src/sage/categories/finite_coxeter_groups.py index 3459135c9c0..4d422a7541f 100644 --- a/src/sage/categories/finite_coxeter_groups.py +++ b/src/sage/categories/finite_coxeter_groups.py @@ -25,10 +25,10 @@ class FiniteCoxeterGroups(CategoryWithAxiom): EXAMPLES:: sage: CoxeterGroups.Finite() - Category of finite coxeter groups + Category of finite Coxeter groups sage: FiniteCoxeterGroups().super_categories() [Category of finite generalized coxeter groups, - Category of coxeter groups] + Category of Coxeter groups] sage: G = CoxeterGroups().Finite().example() sage: G.cayley_graph(side = "right").plot() @@ -55,7 +55,7 @@ def extra_super_categories(self): sage: CoxeterGroups().Finite().super_categories() [Category of finite generalized coxeter groups, - Category of coxeter groups] + Category of Coxeter groups] """ from sage.categories.complex_reflection_groups import ComplexReflectionGroups return [ComplexReflectionGroups().Finite().WellGenerated()] @@ -214,7 +214,7 @@ def bruhat_poset(self, facade=False): handle large / infinite Coxeter groups. """ from sage.combinat.posets.posets import Poset - covers = tuple([u, v] for v in self for u in v.bruhat_lower_covers() ) + covers = tuple([u, v] for v in self for u in v.bruhat_lower_covers()) return Poset((self, covers), cover_relations=True, facade=facade) def shard_poset(self, side='right'): @@ -590,7 +590,7 @@ def m_cambrian_lattice(self, c, m=1, on_roots=False): inv_woc = self.inversion_sequence(sorting_word) S = self.simple_reflections() T = self.reflections_from_w0() - Twords = {t : t.reduced_word() for t in T} + Twords = {t: t.reduced_word() for t in T} elements = set() covers = [] @@ -799,11 +799,12 @@ def coxeter_poset(self): sage: P.rank() 3 - sage: W = CoxeterGroup(['H', 3], implementation="permutation") # optional - gap3 - sage: P = W.coxeter_poset() # optional - gap3 - sage: P # optional - gap3 + sage: # optional - gap3 + sage: W = CoxeterGroup(['H', 3], implementation="permutation") + sage: P = W.coxeter_poset() + sage: P Finite meet-semilattice containing 363 elements - sage: P.rank() # optional - gap3 + sage: P.rank() 3 """ I = self.index_set() @@ -871,11 +872,12 @@ def coxeter_complex(self): sage: C.homology() {0: 0, 1: 0, 2: Z} - sage: W = CoxeterGroup(['H', 3], implementation="permutation") # optional - gap3 - sage: C = W.coxeter_complex() # optional - gap3 - sage: C # optional - gap3 + sage: # optional - gap3 + sage: W = CoxeterGroup(['H', 3], implementation="permutation") + sage: C = W.coxeter_complex() + sage: C Simplicial complex with 62 vertices and 120 facets - sage: C.homology() # optional - gap3 + sage: C.homology() {0: 0, 1: 0, 2: Z} """ I = self.index_set() @@ -898,7 +900,7 @@ def coxeter_complex(self): verts = set() for F in facets.values(): verts.update(F) - labels = {x: i for i,x in enumerate(verts)} + labels = {x: i for i, x in enumerate(verts)} result = [[labels[v] for v in F] for F in facets.values()] from sage.topology.simplicial_complex import SimplicialComplex return SimplicialComplex(result) @@ -938,12 +940,13 @@ def bruhat_upper_covers(self): are those covers of `ws_i` that have a descent at `i`. """ - i = self.first_descent(positive=True,side='right') + i = self.first_descent(positive=True, side='right') if i is not None: - wsi = self.apply_simple_reflection(i,side='right') - return [u.apply_simple_reflection(i,side='right') for u in wsi.bruhat_upper_covers() if u.has_descent(i,side='right')] + [wsi] - else: - return [] + wsi = self.apply_simple_reflection(i, side='right') + return [u.apply_simple_reflection(i, side='right') + for u in wsi.bruhat_upper_covers() + if u.has_descent(i, side='right')] + [wsi] + return [] def coxeter_knuth_neighbor(self, w): r""" @@ -984,7 +987,7 @@ def coxeter_knuth_neighbor(self, w): if not C[0] == 'A': raise NotImplementedError("this has only been implemented in finite type A so far") d = [] - for i in range(2,len(w)): + for i in range(2, len(w)): v = [j for j in w] if w[i-2] == w[i]: if w[i] == w[i-1] - 1: @@ -1046,7 +1049,7 @@ def coxeter_knuth_graph(self): R = [tuple(v) for v in self.reduced_words()] G = Graph() G.add_vertices(R) - G.add_edges([v,vp] for v in R for vp in self.coxeter_knuth_neighbor(v)) + G.add_edges([v, vp] for v in R for vp in self.coxeter_knuth_neighbor(v)) return G def is_coxeter_element(self): diff --git a/src/sage/categories/finite_enumerated_sets.py b/src/sage/categories/finite_enumerated_sets.py index 8a3c0e42ca5..4ca87850b7a 100644 --- a/src/sage/categories/finite_enumerated_sets.py +++ b/src/sage/categories/finite_enumerated_sets.py @@ -446,8 +446,7 @@ def iterator_range(self, start=None, stop=None, step=None): for j in range(stop): yield next(it) return - for x in self: - yield x + yield from self return if L is None: L = self.tuple() diff --git a/src/sage/categories/finite_weyl_groups.py b/src/sage/categories/finite_weyl_groups.py index 4420827c833..4210e2f9feb 100644 --- a/src/sage/categories/finite_weyl_groups.py +++ b/src/sage/categories/finite_weyl_groups.py @@ -20,7 +20,7 @@ class FiniteWeylGroups(CategoryWithAxiom): sage: C Category of finite weyl groups sage: C.super_categories() - [Category of finite coxeter groups, Category of weyl groups] + [Category of finite Coxeter groups, Category of weyl groups] sage: C.example() The symmetric group on {0, ..., 3} diff --git a/src/sage/categories/map.pxd b/src/sage/categories/map.pxd index 0467b872353..98c74d862e4 100644 --- a/src/sage/categories/map.pxd +++ b/src/sage/categories/map.pxd @@ -8,12 +8,12 @@ cdef class Map(Element): # a rough measure of the cost of using this morphism in the coercion system. # 10 by default, 100 if a DefaultCoercionMorphism, 10000 if inexact. - cdef _update_slots(self, dict) - cdef dict _extra_slots(self) + cdef _update_slots(self, dict) noexcept + cdef dict _extra_slots(self) noexcept # these methods require x is an element of domain, and returns an element with parent codomain - cpdef Element _call_(self, x) - cpdef Element _call_with_args(self, x, args=*, kwds=*) + cpdef Element _call_(self, x) noexcept + cpdef Element _call_with_args(self, x, args=*, kwds=*) noexcept cdef public domain # will be either a weakref or a constant map cdef public codomain # will be a constant map @@ -23,7 +23,7 @@ cdef class Map(Element): cdef public _repr_type_str cdef public bint _is_coercion - cpdef _pow_int(self, n) + cpdef _pow_int(self, n) noexcept cdef class Section(Map): diff --git a/src/sage/categories/map.pyx b/src/sage/categories/map.pyx index 71c3ef3f1d2..fadd066d7f4 100644 --- a/src/sage/categories/map.pyx +++ b/src/sage/categories/map.pyx @@ -389,7 +389,7 @@ cdef class Map(Element): self.domain = ConstantFunction(D) self._parent = homset.Hom(D, C, self._category_for) - cdef _update_slots(self, dict slots): + cdef _update_slots(self, dict slots) noexcept: """ Set various attributes of this map to implement unpickling. @@ -451,7 +451,7 @@ cdef class Map(Element): """ self._update_slots(_slots) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Return a dict with attributes to pickle and copy this map. """ @@ -816,7 +816,7 @@ cdef class Map(Element): return self._call_(x) return self._call_with_args(x, args, kwds) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Call method with a single argument, not implemented in the base class. @@ -831,7 +831,7 @@ cdef class Map(Element): """ raise NotImplementedError(type(self)) - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ Call method with multiple arguments, not implemented in the base class. @@ -1222,7 +1222,7 @@ cdef class Map(Element): """ raise NotImplementedError(type(self)) - cpdef _pow_int(self, n): + cpdef _pow_int(self, n) noexcept: """ TESTS:: @@ -1368,7 +1368,7 @@ cdef class Section(Map): Map.__init__(self, Hom(map.codomain(), map.domain(), SetsWithPartialMaps())) self._inverse = map # TODO: Use this attribute somewhere! - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for pickling and copying. @@ -1387,7 +1387,7 @@ cdef class Section(Map): slots['_inverse'] = self._inverse return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for pickling and copying. @@ -1576,7 +1576,7 @@ cdef class FormalCompositeMap(Map): """ return FormalCompositeMap(self.parent(), [f.__copy__() for f in self.__list]) - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Used in pickling and copying. @@ -1595,7 +1595,7 @@ cdef class FormalCompositeMap(Map): self.__list = _slots['__list'] Map._update_slots(self, _slots) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Used in pickling and copying. @@ -1708,7 +1708,7 @@ cdef class FormalCompositeMap(Map): """ return self.__list[i] - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Call with a single argument @@ -1726,7 +1726,7 @@ cdef class FormalCompositeMap(Map): x = f._call_(x) return x - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ Additional arguments are only passed to the last applied map. diff --git a/src/sage/categories/morphism.pxd b/src/sage/categories/morphism.pxd index 2222a9c679a..e5befc8207e 100644 --- a/src/sage/categories/morphism.pxd +++ b/src/sage/categories/morphism.pxd @@ -7,4 +7,4 @@ cdef class Morphism(Map): cdef class SetMorphism(Morphism): cdef object _function - cpdef bint _eq_c_impl(left, Element right) + cpdef bint _eq_c_impl(left, Element right) noexcept diff --git a/src/sage/categories/morphism.pyx b/src/sage/categories/morphism.pyx index 571f90a7330..32fcd565e34 100644 --- a/src/sage/categories/morphism.pyx +++ b/src/sage/categories/morphism.pyx @@ -344,7 +344,7 @@ cdef class Morphism(Map): definition = repr(self) return hash((domain, codomain, definition)) - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ Generic comparison function for morphisms. @@ -453,7 +453,7 @@ cdef class FormalCoercionMorphism(Morphism): def _repr_type(self): return "Coercion" - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: return self._codomain.coerce(x) cdef class CallMorphism(Morphism): @@ -461,7 +461,7 @@ cdef class CallMorphism(Morphism): def _repr_type(self): return "Call" - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: return self._codomain(x) cdef class IdentityMorphism(Morphism): @@ -475,10 +475,10 @@ cdef class IdentityMorphism(Morphism): def _repr_type(self): return "Identity" - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: return x - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: if not args and not kwds: return x cdef Parent C = self._codomain @@ -499,7 +499,7 @@ cdef class IdentityMorphism(Morphism): else: return left - cpdef _pow_int(self, n): + cpdef _pow_int(self, n) noexcept: return self def __invert__(self): @@ -586,7 +586,7 @@ cdef class SetMorphism(Morphism): Morphism.__init__(self, parent) self._function = function - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ INPUT: @@ -607,7 +607,7 @@ cdef class SetMorphism(Morphism): """ return self._function(x) - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ Extra arguments are passed to the defining function. @@ -629,7 +629,7 @@ cdef class SetMorphism(Morphism): except Exception: raise TypeError("Underlying map %s does not accept additional arguments" % type(self._function)) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ INPUT: @@ -651,7 +651,7 @@ cdef class SetMorphism(Morphism): slots['_function'] = self._function return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ INPUT: @@ -680,7 +680,7 @@ cdef class SetMorphism(Morphism): self._function = _slots['_function'] Map._update_slots(self, _slots) - cpdef bint _eq_c_impl(self, Element other): + cpdef bint _eq_c_impl(self, Element other) noexcept: """ Equality test diff --git a/src/sage/categories/posets.py b/src/sage/categories/posets.py index 5cad3c70f73..98d1be6049d 100644 --- a/src/sage/categories/posets.py +++ b/src/sage/categories/posets.py @@ -150,8 +150,7 @@ def __iter__(self): from sage.combinat.posets.posets import FinitePosets_n n = 0 while True: - for P in FinitePosets_n(n): - yield P + yield from FinitePosets_n(n) n += 1 Finite = LazyImport('sage.categories.finite_posets', 'FinitePosets') diff --git a/src/sage/categories/weyl_groups.py b/src/sage/categories/weyl_groups.py index 1322ecd8499..88879d2b478 100644 --- a/src/sage/categories/weyl_groups.py +++ b/src/sage/categories/weyl_groups.py @@ -26,7 +26,7 @@ class WeylGroups(Category_singleton): sage: WeylGroups() Category of weyl groups sage: WeylGroups().super_categories() - [Category of coxeter groups] + [Category of Coxeter groups] Here are some examples:: @@ -53,7 +53,7 @@ def super_categories(self): EXAMPLES:: sage: WeylGroups().super_categories() - [Category of coxeter groups] + [Category of Coxeter groups] """ return [CoxeterGroups()] diff --git a/src/sage/coding/ag_code_decoders.pyx b/src/sage/coding/ag_code_decoders.pyx index ccd6c8c6912..162c7210fc5 100644 --- a/src/sage/coding/ag_code_decoders.pyx +++ b/src/sage/coding/ag_code_decoders.pyx @@ -1318,7 +1318,7 @@ class DifferentialAGCodeUniqueDecoder(Decoder): return self._encode(self._decode(received_vector, **kwargs)) -cdef inline int pos_mod(int a, int b): +cdef inline int pos_mod(int a, int b) noexcept: """ Return ``a % b`` such that the result is positive. @@ -1384,7 +1384,7 @@ cdef class Decoder_K(): message_index = self.message_index return vector(sum([message[i]*code_basis[i] for i in range(len(message_index))])) - cdef inline int _degree(self, Polynomial f): + cdef inline int _degree(self, Polynomial f) noexcept: """ Return the degree of polynomial ``f`` @@ -1395,7 +1395,7 @@ cdef class Decoder_K(): else: return f.degree() - cdef void _exponents(self, int s, int *sk, int *si): + cdef void _exponents(self, int s, int *sk, int *si) noexcept: """ Compute the exponents of the monomial with weighted degree ``s``. @@ -1414,7 +1414,7 @@ cdef class Decoder_K(): @cython.wraparound(False) @cython.boundscheck(False) - cdef void _substitution(self, FreeModuleElement vec, w, int k, Py_ssize_t i): + cdef void _substitution(self, FreeModuleElement vec, w, int k, Py_ssize_t i) noexcept: r""" Substitute ``z`` with ``(z + w*phi_s)``. @@ -1740,7 +1740,7 @@ cdef class Decoder_K(): @cython.wraparound(False) @cython.boundscheck(False) - cdef inline int _next(self, int s): + cdef inline int _next(self, int s) noexcept: """ Return the next value after ``s`` in dRbar(dWbar). """ @@ -1757,7 +1757,7 @@ cdef class Decoder_K(): @cython.wraparound(False) @cython.boundscheck(False) - cdef inline void _get_eta_basis(self, list basis, list vecs, int s0, mon_func): + cdef inline void _get_eta_basis(self, list basis, list vecs, int s0, mon_func) noexcept: """ Compute a basis of J and h-functions via FGLM algorithm. diff --git a/src/sage/coding/binary_code.pxd b/src/sage/coding/binary_code.pxd index 4ae828dcd2b..38be220c731 100644 --- a/src/sage/coding/binary_code.pxd +++ b/src/sage/coding/binary_code.pxd @@ -1,4 +1,4 @@ -cdef int *hamming_weights() +cdef int *hamming_weights() noexcept ctypedef unsigned int codeword @@ -18,20 +18,20 @@ cdef class BinaryCode: cdef int radix cdef int nwords - cdef int is_one(self, int, int) - cdef int is_automorphism(self, int *, int *) - cpdef int put_in_std_form(self) - cdef void _apply_permutation_to_basis(self, object labeling) - cdef void _update_words_from_basis(self) + cdef int is_one(self, int, int) noexcept + cdef int is_automorphism(self, int *, int *) noexcept + cpdef int put_in_std_form(self) noexcept + cdef void _apply_permutation_to_basis(self, object labeling) noexcept + cdef void _update_words_from_basis(self) noexcept -cdef WordPermutation *create_word_perm(object) -cdef WordPermutation *create_array_word_perm(int *, int, int) -cdef WordPermutation *create_id_word_perm(int) -cdef WordPermutation *create_comp_word_perm(WordPermutation *, WordPermutation *) -cdef WordPermutation *create_inv_word_perm(WordPermutation *) -cdef int dealloc_word_perm(WordPermutation *) -cdef codeword permute_word_by_wp(WordPermutation *, codeword) -cdef codeword *expand_to_ortho_basis(BinaryCode, int) +cdef WordPermutation *create_word_perm(object) noexcept +cdef WordPermutation *create_array_word_perm(int *, int, int) noexcept +cdef WordPermutation *create_id_word_perm(int) noexcept +cdef WordPermutation *create_comp_word_perm(WordPermutation *, WordPermutation *) noexcept +cdef WordPermutation *create_inv_word_perm(WordPermutation *) noexcept +cdef int dealloc_word_perm(WordPermutation *) noexcept +cdef codeword permute_word_by_wp(WordPermutation *, codeword) noexcept +cdef codeword *expand_to_ortho_basis(BinaryCode, int) noexcept cdef class OrbitPartition: cdef int nwords @@ -45,11 +45,11 @@ cdef class OrbitPartition: cdef int *col_min_cell_rep cdef int *col_size - cdef int wd_find(self, int) - cdef void wd_union(self, int, int) - cdef int col_find(self, int) - cdef void col_union(self, int, int) - cdef int merge_perm(self, int *, int *) + cdef int wd_find(self, int) noexcept + cdef void wd_union(self, int, int) noexcept + cdef int col_find(self, int) noexcept + cdef void col_union(self, int, int) noexcept + cdef int merge_perm(self, int *, int *) noexcept cdef class PartitionStack: cdef int *wd_ents @@ -69,24 +69,24 @@ cdef class PartitionStack: cdef int *wd_counts # These are just for scratch space... cdef int *wd_output # - cdef int is_discrete(self, int) - cdef int num_cells(self, int) - cdef int sat_225(self, int) - cdef void new_min_cell_reps(self, int, unsigned int *, int) - cdef void fixed_vertices(self, int, unsigned int *, unsigned int *, int) - cdef int new_first_smallest_nontrivial(self, int, unsigned int *, int) - cdef void col_percolate(self, int, int) - cdef void wd_percolate(self, int, int) - cdef int split_vertex(self, int, int) - cdef int col_degree(self, BinaryCode, int, int, int) - cdef int wd_degree(self, BinaryCode, int, int, int, int *) - cdef int sort_cols(self, int, int) - cdef int sort_wds(self, int, int) - cdef int refine(self, int, int *, int, BinaryCode, int *) - cdef void clear(self, int) - cpdef int cmp(self, PartitionStack, BinaryCode) - cdef int find_basis(self, int *) - cdef void get_permutation(self, PartitionStack, int *, int *) + cdef int is_discrete(self, int) noexcept + cdef int num_cells(self, int) noexcept + cdef int sat_225(self, int) noexcept + cdef void new_min_cell_reps(self, int, unsigned int *, int) noexcept + cdef void fixed_vertices(self, int, unsigned int *, unsigned int *, int) noexcept + cdef int new_first_smallest_nontrivial(self, int, unsigned int *, int) noexcept + cdef void col_percolate(self, int, int) noexcept + cdef void wd_percolate(self, int, int) noexcept + cdef int split_vertex(self, int, int) noexcept + cdef int col_degree(self, BinaryCode, int, int, int) noexcept + cdef int wd_degree(self, BinaryCode, int, int, int, int *) noexcept + cdef int sort_cols(self, int, int) noexcept + cdef int sort_wds(self, int, int) noexcept + cdef int refine(self, int, int *, int, BinaryCode, int *) noexcept + cdef void clear(self, int) noexcept + cpdef int cmp(self, PartitionStack, BinaryCode) noexcept + cdef int find_basis(self, int *) noexcept + cdef void get_permutation(self, PartitionStack, int *, int *) noexcept cdef class BinaryCodeClassifier: cdef int *ham_wts @@ -113,6 +113,6 @@ cdef class BinaryCodeClassifier: cdef int Phi_size - cdef void record_automorphism(self, int *, int) - cdef void aut_gp_and_can_label(self, BinaryCode, int) + cdef void record_automorphism(self, int *, int) noexcept + cdef void aut_gp_and_can_label(self, BinaryCode, int) noexcept diff --git a/src/sage/coding/binary_code.pyx b/src/sage/coding/binary_code.pyx index fba66d7c690..6779708bfda 100644 --- a/src/sage/coding/binary_code.pyx +++ b/src/sage/coding/binary_code.pyx @@ -57,7 +57,7 @@ WORD_SIZE = sizeof(codeword) << 3 cdef enum: chunk_size = 8 -cdef inline int min(int a, int b): +cdef inline int min(int a, int b) noexcept: if a > b: return b else: @@ -67,7 +67,7 @@ cdef inline int min(int a, int b): ## functions come without an underscore, and the def'd equivalents, which are ## essentially only for doctesting and debugging, have underscores. -cdef int *hamming_weights(): +cdef int *hamming_weights() noexcept: cdef int *ham_wts cdef int i ham_wts = sig_malloc( 65536 * sizeof(int) ) @@ -279,7 +279,7 @@ def test_word_perms(t_limit=5.0): dealloc_word_perm(i) sig_free(arr) -cdef WordPermutation *create_word_perm(object list_perm): +cdef WordPermutation *create_word_perm(object list_perm) noexcept: r""" Create a word permutation from a Python list permutation L, i.e. such that `i \mapsto L[i]`. @@ -330,7 +330,7 @@ cdef WordPermutation *create_word_perm(object list_perm): image ^= images_i[1 << j] return word_perm -cdef WordPermutation *create_array_word_perm(int *array, int start, int degree): +cdef WordPermutation *create_array_word_perm(int *array, int start, int degree) noexcept: """ Create a word permutation of a given degree from a C array, starting at start. """ @@ -379,7 +379,7 @@ cdef WordPermutation *create_array_word_perm(int *array, int start, int degree): image ^= images_i[1 << j] return word_perm -cdef WordPermutation *create_id_word_perm(int degree): +cdef WordPermutation *create_id_word_perm(int degree) noexcept: """ Create the identity word permutation of degree degree. """ @@ -427,7 +427,7 @@ cdef WordPermutation *create_id_word_perm(int degree): image ^= images_i[1 << j] return word_perm -cdef WordPermutation *create_comp_word_perm(WordPermutation *g, WordPermutation *h): +cdef WordPermutation *create_comp_word_perm(WordPermutation *g, WordPermutation *h) noexcept: r""" Create the composition of word permutations `g \circ h`. """ @@ -478,7 +478,7 @@ cdef WordPermutation *create_comp_word_perm(WordPermutation *g, WordPermutation image ^= images_i[1 << j] return word_perm -cdef WordPermutation *create_inv_word_perm(WordPermutation *g): +cdef WordPermutation *create_inv_word_perm(WordPermutation *g) noexcept: r""" Create the inverse `g^{-1}` of the word permutation of `g`. """ @@ -496,7 +496,7 @@ cdef WordPermutation *create_inv_word_perm(WordPermutation *g): sig_free(array) return w -cdef int dealloc_word_perm(WordPermutation *wp): +cdef int dealloc_word_perm(WordPermutation *wp) noexcept: """ Free the memory used by a word permutation. """ @@ -506,7 +506,7 @@ cdef int dealloc_word_perm(WordPermutation *wp): sig_free(wp.images) sig_free(wp) -cdef codeword permute_word_by_wp(WordPermutation *wp, codeword word): +cdef codeword permute_word_by_wp(WordPermutation *wp, codeword word) noexcept: """ Return the codeword obtained by applying the permutation wp to word. """ @@ -574,7 +574,7 @@ def test_expand_to_ortho_basis(B=None): print(''.join(reversed(Integer(output[i]).binary().zfill(C.ncols)))) sig_free(output) -cdef codeword *expand_to_ortho_basis(BinaryCode B, int n): +cdef codeword *expand_to_ortho_basis(BinaryCode B, int n) noexcept: r""" INPUT: @@ -1073,7 +1073,7 @@ cdef class BinaryCode: """ return self.is_one(word, col) != 0 - cdef int is_one(self, int word, int column): + cdef int is_one(self, int word, int column) noexcept: return (self.words[word] & ( 1 << column)) >> column def _is_automorphism(self, col_gamma, word_gamma): @@ -1121,7 +1121,7 @@ cdef class BinaryCode: sig_free(_word_gamma) return result - cdef int is_automorphism(self, int *col_gamma, int *word_gamma): + cdef int is_automorphism(self, int *col_gamma, int *word_gamma) noexcept: cdef int i, j, self_nwords = self.nwords, self_ncols = self.ncols i = 1 while i < self_nwords: @@ -1180,7 +1180,7 @@ cdef class BinaryCode: self._apply_permutation_to_basis(labeling) self._update_words_from_basis() - cdef void _apply_permutation_to_basis(self, object labeling): + cdef void _apply_permutation_to_basis(self, object labeling) noexcept: cdef WordPermutation *wp cdef int i wp = create_word_perm(labeling) @@ -1188,7 +1188,7 @@ cdef class BinaryCode: self.basis[i] = permute_word_by_wp(wp, self.basis[i]) dealloc_word_perm(wp) - cdef void _update_words_from_basis(self): + cdef void _update_words_from_basis(self) noexcept: cdef codeword word cdef int j, parity, combination word = 0 @@ -1206,7 +1206,7 @@ cdef class BinaryCode: combination ^= (1 << j) word ^= self.basis[j] - cpdef int put_in_std_form(self): + cpdef int put_in_std_form(self) noexcept: """ Put the code in binary form, which is defined by an identity matrix on the left, augmented by a matrix of data. @@ -1386,7 +1386,7 @@ cdef class OrbitPartition: """ return self.wd_find(word) - cdef int wd_find(self, int word): + cdef int wd_find(self, int word) noexcept: if self.wd_parent[word] == word: return word else: @@ -1421,7 +1421,7 @@ cdef class OrbitPartition: """ self.wd_union(x, y) - cdef void wd_union(self, int x, int y): + cdef void wd_union(self, int x, int y) noexcept: cdef int x_root, y_root x_root = self.wd_find(x) y_root = self.wd_find(y) @@ -1460,7 +1460,7 @@ cdef class OrbitPartition: """ return self.col_find(col) - cdef int col_find(self, int col): + cdef int col_find(self, int col) noexcept: if self.col_parent[col] == col: return col else: @@ -1495,7 +1495,7 @@ cdef class OrbitPartition: """ self.col_union(x, y) - cdef void col_union(self, int x, int y): + cdef void col_union(self, int x, int y) noexcept: cdef int x_root, y_root x_root = self.col_find(x) y_root = self.col_find(y) @@ -1558,7 +1558,7 @@ cdef class OrbitPartition: sig_free(_wd_gamma) return result - cdef int merge_perm(self, int *col_gamma, int *wd_gamma): + cdef int merge_perm(self, int *col_gamma, int *wd_gamma) noexcept: cdef int i, gamma_i_root cdef int j, gamma_j_root, return_value = 0 cdef int *self_wd_parent = self.wd_parent @@ -1906,7 +1906,7 @@ cdef class PartitionStack: """ return self.is_discrete(k) - cdef int is_discrete(self, int k): + cdef int is_discrete(self, int k) noexcept: cdef int i, self_ncols = self.ncols, self_nwords = self.nwords cdef int *self_col_lvls = self.col_lvls cdef int *self_wd_lvls = self.wd_lvls @@ -1942,7 +1942,7 @@ cdef class PartitionStack: """ return self.num_cells(k) - cdef int num_cells(self, int k): + cdef int num_cells(self, int k) noexcept: cdef int i, j = 0 cdef int *self_wd_lvls = self.wd_lvls cdef int *self_col_lvls = self.col_lvls @@ -1982,7 +1982,7 @@ cdef class PartitionStack: """ return self.sat_225(k) - cdef int sat_225(self, int k): + cdef int sat_225(self, int k) noexcept: cdef int i, n = self.nwords + self.ncols, in_cell = 0 cdef int nontrivial_cells = 0, total_cells = self.num_cells(k) cdef int *self_wd_lvls = self.wd_lvls @@ -2049,7 +2049,7 @@ cdef class PartitionStack: # reps += (1 << i) # return reps # - cdef void new_min_cell_reps(self, int k, unsigned int *Omega, int start): + cdef void new_min_cell_reps(self, int k, unsigned int *Omega, int start) noexcept: cdef int i, j cdef int *self_col_lvls = self.col_lvls cdef int *self_wd_lvls = self.wd_lvls @@ -2109,7 +2109,7 @@ cdef class PartitionStack: # fixed += (1 << i) # return fixed & mcrs # - cdef void fixed_vertices(self, int k, unsigned int *Phi, unsigned int *Omega, int start): + cdef void fixed_vertices(self, int k, unsigned int *Phi, unsigned int *Omega, int start) noexcept: cdef int i, j, length, ell, fixed = 0 cdef int radix = self.radix, nwords = self.nwords, ncols = self.ncols cdef int *self_col_lvls = self.col_lvls @@ -2184,7 +2184,7 @@ cdef class PartitionStack: # cell = (~0 << location) ^ (~0 << j+1) # <------- self.radix -----> # return cell # [0]*(radix-j-1) + [1]*(j-location+1) + [0]*location # - cdef int new_first_smallest_nontrivial(self, int k, unsigned int *W, int start): + cdef int new_first_smallest_nontrivial(self, int k, unsigned int *W, int start) noexcept: cdef int ell cdef int i = 0, j = 0, location = 0, min = self.ncols, nwords = self.nwords cdef int min_is_col = 1, radix = self.radix @@ -2296,7 +2296,7 @@ cdef class PartitionStack: """ self.col_percolate(start, end) - cdef void col_percolate(self, int start, int end): + cdef void col_percolate(self, int start, int end) noexcept: cdef int i, temp cdef int *self_col_ents = self.col_ents for i from end >= i > start: @@ -2331,7 +2331,7 @@ cdef class PartitionStack: """ self.wd_percolate(start, end) - cdef void wd_percolate(self, int start, int end): + cdef void wd_percolate(self, int start, int end) noexcept: cdef int i, temp cdef int *self_wd_ents = self.wd_ents for i from end >= i > start: @@ -2430,7 +2430,7 @@ cdef class PartitionStack: """ return self.split_vertex(v, k) - cdef int split_vertex(self, int v, int k): + cdef int split_vertex(self, int v, int k) noexcept: cdef int i = 0, j, flag = self.flag cdef int *ents cdef int *lvls @@ -2496,7 +2496,7 @@ cdef class PartitionStack: """ return self.col_degree(C, col, wd_ptr, k) - cdef int col_degree(self, BinaryCode CG, int col, int wd_ptr, int k): + cdef int col_degree(self, BinaryCode CG, int col, int wd_ptr, int k) noexcept: cdef int i = 0 cdef int *self_wd_lvls = self.wd_lvls cdef int *self_wd_ents = self.wd_ents @@ -2540,7 +2540,7 @@ cdef class PartitionStack: sig_free(ham_wts) return result - cdef int wd_degree(self, BinaryCode CG, int wd, int col_ptr, int k, int *ham_wts): + cdef int wd_degree(self, BinaryCode CG, int wd, int col_ptr, int k, int *ham_wts) noexcept: cdef int *self_col_lvls = self.col_lvls cdef int *self_col_ents = self.col_ents @@ -2580,7 +2580,7 @@ cdef class PartitionStack: self.col_degs[i] = degrees[i] return self.sort_cols(start, k) - cdef int sort_cols(self, int start, int k): + cdef int sort_cols(self, int start, int k) noexcept: cdef int i, j, max, max_location, self_ncols = self.ncols cdef int self_nwords = self.nwords, ii cdef int *self_col_counts = self.col_counts @@ -2650,7 +2650,7 @@ cdef class PartitionStack: self.wd_degs[i] = degrees[i] return self.sort_wds(start, k) - cdef int sort_wds(self, int start, int k): + cdef int sort_wds(self, int start, int k) noexcept: cdef int i, j, max, max_location, self_nwords = self.nwords cdef int ii, self_ncols = self.ncols cdef int *self_wd_counts = self.wd_counts @@ -2755,7 +2755,7 @@ cdef class PartitionStack: sig_free(ham_wts) return result - cdef int refine(self, int k, int *alpha, int alpha_length, BinaryCode CG, int *ham_wts): + cdef int refine(self, int k, int *alpha, int alpha_length, BinaryCode CG, int *ham_wts) noexcept: cdef int q, r, s, t, flag = self.flag, self_ncols = self.ncols cdef int t_w, self_nwords = self.nwords, invariant = 0, i, j, m = 0 cdef int *self_wd_degs = self.wd_degs @@ -2858,7 +2858,7 @@ cdef class PartitionStack: """ self.clear(k) - cdef void clear(self, int k): + cdef void clear(self, int k) noexcept: cdef int i, j = 0, nwords = self.nwords, ncols = self.ncols cdef int *wd_lvls = self.wd_lvls cdef int *col_lvls = self.col_lvls @@ -2876,7 +2876,7 @@ cdef class PartitionStack: self.col_percolate(j, i) j = i + 1 - cpdef int cmp(self, PartitionStack other, BinaryCode CG): + cpdef int cmp(self, PartitionStack other, BinaryCode CG) noexcept: """ EXAMPLES:: @@ -2996,7 +2996,7 @@ cdef class PartitionStack: self.find_basis(ham_wts) sig_free(ham_wts) - cdef int find_basis(self, int *ham_wts): + cdef int find_basis(self, int *ham_wts) noexcept: cdef int i = 0, j, k, nwords = self.nwords, weight, basis_elts = 0, nrows = self.nrows cdef int *self_wd_ents = self.wd_ents if self.basis_locations is NULL: @@ -3072,7 +3072,7 @@ cdef class PartitionStack: sig_free(col_g) return word_l, col_l - cdef void get_permutation(self, PartitionStack other, int *word_gamma, int *col_gamma): + cdef void get_permutation(self, PartitionStack other, int *word_gamma, int *col_gamma) noexcept: cdef int i cdef int *self_wd_ents = self.wd_ents cdef int *other_wd_ents = other.wd_ents @@ -3159,7 +3159,7 @@ cdef class BinaryCodeClassifier: sig_free(self.labeling) sig_free(self.base) - cdef void record_automorphism(self, int *gamma, int ncols): + cdef void record_automorphism(self, int *gamma, int ncols) noexcept: cdef int i, j if self.aut_gp_index + ncols > self.aut_gens_size: self.aut_gens_size *= 2 @@ -3337,7 +3337,7 @@ cdef class BinaryCodeClassifier: aut_gp_size = self.aut_gp_size return py_aut_gp_gens, py_labeling, aut_gp_size, base - cdef void aut_gp_and_can_label(self, BinaryCode C, int verbosity): + cdef void aut_gp_and_can_label(self, BinaryCode C, int verbosity) noexcept: # declare variables: cdef int i, j, ii, jj, iii, jjj, iiii # local variables diff --git a/src/sage/coding/codecan/codecan.pxd b/src/sage/coding/codecan/codecan.pxd index dd72f6bb798..b76608d68e3 100644 --- a/src/sage/coding/codecan/codecan.pxd +++ b/src/sage/coding/codecan/codecan.pxd @@ -14,23 +14,23 @@ cdef class InnerGroup: cdef SemimonomialTransformation transporter cdef bint compute_transporter - cdef inline int get_rep(self, int pos) - cdef inline int join_rows(self, int rep1, int rep2) + cdef inline int get_rep(self, int pos) noexcept + cdef inline int join_rows(self, int rep1, int rep2) noexcept - cdef InnerGroup _new_c(self) - cdef void copy_from(self, InnerGroup other) - cdef bint has_semilinear_action(self) - cdef minimize_by_row_mult(self, FreeModuleElement v) + cdef InnerGroup _new_c(self) noexcept + cdef void copy_from(self, InnerGroup other) noexcept + cdef bint has_semilinear_action(self) noexcept + cdef minimize_by_row_mult(self, FreeModuleElement v) noexcept cdef minimize_matrix_col(self, object m, int pos, list fixed_minimized_cols, - bint *group_changed) - cdef void gaussian_elimination(self, object m, int pos, int pivot, list nz_pos) - cdef void minimize_by_frobenius(self, object v, int *applied_frob, int *stab_pow) + bint *group_changed) noexcept + cdef void gaussian_elimination(self, object m, int pos, int pivot, list nz_pos) noexcept + cdef void minimize_by_frobenius(self, object v, int *applied_frob, int *stab_pow) noexcept - cdef SemimonomialTransformation get_transporter(self) + cdef SemimonomialTransformation get_transporter(self) noexcept - cdef bint has_semilinear_action(self) - cpdef int get_frob_pow(self) - cpdef column_blocks(self, mat) + cdef bint has_semilinear_action(self) noexcept + cpdef int get_frob_pow(self) noexcept + cpdef column_blocks(self, mat) noexcept cdef class PartitionRefinementLinearCode(PartitionRefinement_generic): cdef int _k, _q @@ -53,10 +53,10 @@ cdef class PartitionRefinementLinearCode(PartitionRefinement_generic): cdef list _autom_group_generators # specialized refine methods, called in refine - cdef bint _inner_min_refine(self, bint *inner_stab_changed, bint *changed_partition) - cdef bint _point_refine(self, bint *inner_stab_changed, bint *changed_partition) - cdef bint _hyp_refine(self, bint *changed_partition) + cdef bint _inner_min_refine(self, bint *inner_stab_changed, bint *changed_partition) noexcept + cdef bint _point_refine(self, bint *inner_stab_changed, bint *changed_partition) noexcept + cdef bint _hyp_refine(self, bint *changed_partition) noexcept # some additional methods - cdef _compute_group_element(self, SemimonomialTransformation trans, str algorithm_type) - cdef _init_point_hyperplane_incidence(self) + cdef _compute_group_element(self, SemimonomialTransformation trans, str algorithm_type) noexcept + cdef _init_point_hyperplane_incidence(self) noexcept diff --git a/src/sage/coding/codecan/codecan.pyx b/src/sage/coding/codecan/codecan.pyx index b0709155b57..4276fffda68 100644 --- a/src/sage/coding/codecan/codecan.pyx +++ b/src/sage/coding/codecan/codecan.pyx @@ -190,20 +190,20 @@ cdef class InnerGroup: """ OP_dealloc(self.row_partition) - cdef int get_rep(self, int pos): + cdef int get_rep(self, int pos) noexcept: """ Get the index of the cell of ``self.row_partition`` containing ``pos``. """ return OP_find(self.row_partition, pos) - cdef bint has_semilinear_action(self): + cdef bint has_semilinear_action(self) noexcept: """ Returns ``True`` iff the field automorphism group component of ``self`` is non-trivial. """ return (self.frob_pow > 0) - cdef int join_rows(self, int rep1, int rep2): + cdef int join_rows(self, int rep1, int rep2) noexcept: """ Join the cells with unique representatives ``rep1`` and ``rep2`` of ``self.row_partition``. @@ -212,7 +212,7 @@ cdef class InnerGroup: OP_join(self.row_partition, rep1, rep2) return self.get_rep(rep1) - cdef void copy_from(self, InnerGroup other): + cdef void copy_from(self, InnerGroup other) noexcept: """ Copy the group ``other`` to ``self``. """ @@ -221,7 +221,7 @@ cdef class InnerGroup: self.permutational_only = other.permutational_only OP_copy_from_to(other.row_partition, self.row_partition) - cdef minimize_by_row_mult(self, FreeModuleElement w): + cdef minimize_by_row_mult(self, FreeModuleElement w) noexcept: r""" We suppose `v \in \GF{q}^k` and the entries `v_i = 0` for all ``i >= self.rank``. @@ -249,7 +249,7 @@ cdef class InnerGroup: return d, v cdef minimize_matrix_col(self, object m, int pos, list fixed_minimized_cols, - bint *group_changed): + bint *group_changed) noexcept: r""" Minimize the column at position ``pos`` of the matrix ``m`` by the action of ``self``. ``m`` should have no zero column. ``self`` is set to @@ -330,7 +330,7 @@ cdef class InnerGroup: self.rank += 1 return m - cdef void gaussian_elimination(self, object m, int pos, int pivot, list nz_pos): + cdef void gaussian_elimination(self, object m, int pos, int pivot, list nz_pos) noexcept: r""" Minimize the column at position ``pos`` of the matrix ``m`` by the action of ``self``. We know that there is some nonzero entry of this @@ -347,7 +347,7 @@ cdef class InnerGroup: if pivot != self.rank: m.swap_rows(self.rank, pivot) - cdef InnerGroup _new_c(self): + cdef InnerGroup _new_c(self) noexcept: r""" Make a new copy of ``self``. """ @@ -358,7 +358,7 @@ cdef class InnerGroup: res.permutational_only = self.permutational_only return res - cdef SemimonomialTransformation get_transporter(self): + cdef SemimonomialTransformation get_transporter(self) noexcept: r""" Return the group element we have applied. Should only be called if we passed an element in @@ -380,7 +380,7 @@ cdef class InnerGroup: "with rank = %s, frobenius power = %s and partition =%s" % (self.rank, self.frob_pow, OP_string(self.row_partition)) - cdef void minimize_by_frobenius(self, object v, int *applied_frob, int *stab_pow): + cdef void minimize_by_frobenius(self, object v, int *applied_frob, int *stab_pow) noexcept: r""" Minimize the vector ``v \in \GF{q}^k`` by the action of the field automorphism component of ``self``. @@ -417,7 +417,7 @@ cdef class InnerGroup: stab_pow[0] = 0 break # for - cpdef int get_frob_pow(self): + cpdef int get_frob_pow(self) noexcept: r""" Return the power of the Frobenius automorphism which generates the corresponding component of ``self``. @@ -431,7 +431,7 @@ cdef class InnerGroup: """ return self.frob_pow - cpdef column_blocks(self, mat): + cpdef column_blocks(self, mat) noexcept: r""" Let ``mat`` be a matrix which is stabilized by ``self`` having no zero columns. We know that for each column of ``mat`` there is a uniquely @@ -646,7 +646,7 @@ cdef class PartitionRefinementLinearCode(PartitionRefinement_generic): self._autom_group_generators.append(transp_inv * x * self._transporter) self._inner_group_stabilizer_order *= Integer(F.degree() / remaining_inner_group.get_frob_pow()) - cdef _compute_group_element(self, SemimonomialTransformation trans, str algorithm_type): + cdef _compute_group_element(self, SemimonomialTransformation trans, str algorithm_type) noexcept: """ Apply ``trans`` to ``self._root_matrix`` and minimize this matrix column by column under the inner minimization. The action is @@ -738,7 +738,7 @@ cdef class PartitionRefinementLinearCode(PartitionRefinement_generic): """ return self._inner_group_stabilizer_order - cdef _init_point_hyperplane_incidence(self): + cdef _init_point_hyperplane_incidence(self) noexcept: r""" Compute a set of codewords `W` of `C` (generated by self) which is compatible with the group action, i.e. if we start with some other code `(g,\pi)C` @@ -811,7 +811,7 @@ cdef class PartitionRefinementLinearCode(PartitionRefinement_generic): self._hyp_refine_vals = _BestValStore(self._hyp_part.degree) - cdef bint _minimization_allowed_on_col(self, int pos): + cdef bint _minimization_allowed_on_col(self, int pos) noexcept: r""" Decide if we are allowed to perform the inner minimization on position ``pos`` which is supposed to be a singleton. For linear codes over finite @@ -819,7 +819,7 @@ cdef class PartitionRefinementLinearCode(PartitionRefinement_generic): """ return True - cdef bint _inner_min_(self, int pos, bint *inner_group_changed): + cdef bint _inner_min_(self, int pos, bint *inner_group_changed) noexcept: r""" Minimize the node by the action of the inner group on the ``pos``-th position. Sets ``inner_group_changed`` to ``True`` if and only if the inner group @@ -850,7 +850,7 @@ cdef class PartitionRefinementLinearCode(PartitionRefinement_generic): return True cdef bint _refine(self, bint *part_changed, - bint inner_group_changed, bint first_step): + bint inner_group_changed, bint first_step) noexcept: """ Refine the partition ``self.part``. Set ``part_changed`` to ``True`` if and only if ``self.part`` was refined. @@ -900,7 +900,7 @@ cdef class PartitionRefinementLinearCode(PartitionRefinement_generic): return True - cdef bint _inner_min_refine(self, bint *inner_stab_changed, bint *changed_partition): + cdef bint _inner_min_refine(self, bint *inner_stab_changed, bint *changed_partition) noexcept: """ Refine the partition ``self.part`` by computing the orbit (respectively the hash of a canonical form) of each column vector under the inner group. @@ -953,7 +953,7 @@ cdef class PartitionRefinementLinearCode(PartitionRefinement_generic): return self._one_refinement(best_vals, 0, self._n, inner_stab_changed, changed_partition, "supp_refine") - cdef bint _point_refine(self, bint *inner_stab_changed, bint *changed_partition): + cdef bint _point_refine(self, bint *inner_stab_changed, bint *changed_partition) noexcept: """ Refine the partition ``self.part`` by counting (colored) neighbours in the point-hyperplane graph. @@ -999,7 +999,7 @@ cdef class PartitionRefinementLinearCode(PartitionRefinement_generic): self._part.depth -= 1 return ret_val - cdef bint _hyp_refine(self, bint *changed_partition): + cdef bint _hyp_refine(self, bint *changed_partition) noexcept: """ Refine the partition of the hyperplanes by counting (colored) neighbours in the point-hyperplane graph. @@ -1045,7 +1045,7 @@ cdef class PartitionRefinementLinearCode(PartitionRefinement_generic): self._hyp_part.depth -= 1 return ret_val[0] - cdef tuple _store_state_(self): + cdef tuple _store_state_(self) noexcept: r""" Store the current state of the node to a tuple, such that it can be restored by :meth:`_restore_state_`. @@ -1054,7 +1054,7 @@ cdef class PartitionRefinementLinearCode(PartitionRefinement_generic): self._nr_of_point_refine_calls, self._nr_of_hyp_refine_calls, self._hyp_part.depth) - cdef void _restore_state_(self, tuple act_state): + cdef void _restore_state_(self, tuple act_state) noexcept: r""" The inverse of :meth:`_store_state_`. """ @@ -1064,13 +1064,13 @@ cdef class PartitionRefinementLinearCode(PartitionRefinement_generic): self._nr_of_hyp_refine_calls = act_state[3] self._hyp_part.depth = act_state[4] - cdef void _store_best_(self): + cdef void _store_best_(self) noexcept: """ Store this node as the actual best candidate for the canonical form. """ self._best_candidate = copy(self._matrix) - cdef void _latex_act_node(self, str comment="", int printlvl=0): + cdef void _latex_act_node(self, str comment="", int printlvl=0) noexcept: """ Print the actual status as latex (tikz) commands to ``self._latex_debug_string``. Only needed if one wants to visualize diff --git a/src/sage/coding/guruswami_sudan/interpolation.py b/src/sage/coding/guruswami_sudan/interpolation.py index 8625bae5b49..eea537a115a 100644 --- a/src/sage/coding/guruswami_sudan/interpolation.py +++ b/src/sage/coding/guruswami_sudan/interpolation.py @@ -46,8 +46,7 @@ def _flatten_once(lstlst): [1, 2, 3, 4, 5, 6] """ for lst in lstlst: - for e in lst: - yield e + yield from lst #************************************************************* # Linear algebraic Interpolation algorithm, helper functions diff --git a/src/sage/combinat/abstract_tree.py b/src/sage/combinat/abstract_tree.py index 1dd26c41222..ee797d990fa 100644 --- a/src/sage/combinat/abstract_tree.py +++ b/src/sage/combinat/abstract_tree.py @@ -779,8 +779,7 @@ def paths_at_depth(self, depth, path=[]): yield tuple(path) else: for i in range(len(self)): - for p in self[i].paths_at_depth(depth - 1, path + [i]): - yield p + yield from self[i].paths_at_depth(depth - 1, path + [i]) def node_number_at_depth(self, depth): r""" diff --git a/src/sage/combinat/alternating_sign_matrix.py b/src/sage/combinat/alternating_sign_matrix.py index ee34e183a70..e4eec5eedaf 100644 --- a/src/sage/combinat/alternating_sign_matrix.py +++ b/src/sage/combinat/alternating_sign_matrix.py @@ -1908,8 +1908,7 @@ def __iter__(self): [[1, 2, 3], [2, 3], [2]], [[1, 2, 3], [2, 3], [3]]] """ - for z in self._iterator_rec(self.n): - yield z + yield from self._iterator_rec(self.n) def _next_column_iterator(previous_column, height, i=None): diff --git a/src/sage/combinat/cluster_algebra_quiver/cluster_seed.py b/src/sage/combinat/cluster_algebra_quiver/cluster_seed.py index 514acb43636..58fa26437fa 100644 --- a/src/sage/combinat/cluster_algebra_quiver/cluster_seed.py +++ b/src/sage/combinat/cluster_algebra_quiver/cluster_seed.py @@ -3878,8 +3878,7 @@ def b_matrix_class_iter(self, depth=infinity, up_to_equivalence=True): ] """ Q = self.quiver() - for M in Q.mutation_class_iter(depth=depth, up_to_equivalence=up_to_equivalence, data_type='matrix'): - yield M + yield from Q.mutation_class_iter(depth=depth, up_to_equivalence=up_to_equivalence, data_type='matrix') def b_matrix_class(self, depth=infinity, up_to_equivalence=True): r""" diff --git a/src/sage/combinat/colored_permutations.py b/src/sage/combinat/colored_permutations.py index d97624a218d..ff9a67e3083 100644 --- a/src/sage/combinat/colored_permutations.py +++ b/src/sage/combinat/colored_permutations.py @@ -1557,7 +1557,7 @@ def _coerce_map_from_(self, C): [1 if v == 0 else -1 for v in x._colors], x._perm) - return super(SignedPermutations, self)._coerce_map_from_(C) + return super()._coerce_map_from_(C) def long_element(self, index_set=None): """ @@ -1587,7 +1587,7 @@ def long_element(self, index_set=None): True """ if index_set is not None: - return super(SignedPermutations, self).long_element() + return super().long_element() return self.element_class(self, [-ZZ.one()] * self._n, self._P.one()) def conjugacy_class_representative(self, nu): diff --git a/src/sage/combinat/combinat.py b/src/sage/combinat/combinat.py index 4b763bb5af8..4c182f7c0da 100644 --- a/src/sage/combinat/combinat.py +++ b/src/sage/combinat/combinat.py @@ -1938,8 +1938,7 @@ def __iterator_from_list(self) -> Iterator: sage: list(C) # indirect doctest [1, 2, 3] """ - for x in self.list(): - yield x + yield from self.list() def __iter__(self): """ @@ -2574,8 +2573,7 @@ def __iter__(self) -> Iterator: raise NotImplementedError i = 0 while True: - for c in finite(i): - yield c + yield from finite(i) i += 1 diff --git a/src/sage/combinat/combinat_cython.pxd b/src/sage/combinat/combinat_cython.pxd index 40cae00a781..dfafe45f589 100644 --- a/src/sage/combinat/combinat_cython.pxd +++ b/src/sage/combinat/combinat_cython.pxd @@ -1,5 +1,5 @@ from sage.libs.gmp.all cimport mpz_t -cdef mpz_stirling_s2(mpz_t s, unsigned long n, unsigned long k) +cdef mpz_stirling_s2(mpz_t s, unsigned long n, unsigned long k) noexcept -cdef list convert(Py_ssize_t* f, Py_ssize_t n) +cdef list convert(Py_ssize_t* f, Py_ssize_t n) noexcept diff --git a/src/sage/combinat/combinat_cython.pyx b/src/sage/combinat/combinat_cython.pyx index c0905491ac2..68a7de2498e 100644 --- a/src/sage/combinat/combinat_cython.pyx +++ b/src/sage/combinat/combinat_cython.pyx @@ -28,7 +28,7 @@ set_partition_iterator_blocks = LazyImport('sage.combinat.set_partition_iterator linear_extension_iterator = LazyImport('sage.combinat.posets.linear_extension_iterator', 'linear_extension_iterator', deprecation=35741) -cdef void mpz_addmul_alt(mpz_t s, mpz_t t, mpz_t u, unsigned long parity): +cdef void mpz_addmul_alt(mpz_t s, mpz_t t, mpz_t u, unsigned long parity) noexcept: """ Set s = s + t*u * (-1)^parity """ @@ -38,7 +38,7 @@ cdef void mpz_addmul_alt(mpz_t s, mpz_t t, mpz_t u, unsigned long parity): mpz_addmul(s, t, u) -cdef mpz_stirling_s2(mpz_t s, unsigned long n, unsigned long k): +cdef mpz_stirling_s2(mpz_t s, unsigned long n, unsigned long k) noexcept: """ Set s = S(n,k) where S(n,k) denotes a Stirling number of the second kind. @@ -134,6 +134,7 @@ cdef mpz_stirling_s2(mpz_t s, unsigned long n, unsigned long k): mpz_clear(t) mpz_clear(u) + def _stirling_number2(n, k): """ Python wrapper of mpz_stirling_s2. @@ -148,8 +149,9 @@ def _stirling_number2(n, k): mpz_stirling_s2(s.value, n, k) return s + ##################################################################### -## Lyndon word iterator +# Lyndon word iterator def lyndon_word_iterator(Py_ssize_t n, Py_ssize_t k): r""" @@ -204,7 +206,8 @@ def lyndon_word_iterator(Py_ssize_t n, Py_ssize_t k): while a[i] == n - 1: i -= 1 -## Perfect matchings iterator + +# Perfect matchings iterator def perfect_matchings_iterator(Py_ssize_t n): r""" @@ -276,7 +279,8 @@ def perfect_matchings_iterator(Py_ssize_t n): sig_free(e) sig_free(f) -cdef list convert(Py_ssize_t* f, Py_ssize_t n): + +cdef list convert(Py_ssize_t* f, Py_ssize_t n) noexcept: """ Convert a list ``f`` representing a fixed-point free involution to a set partition. @@ -288,8 +292,9 @@ cdef list convert(Py_ssize_t* f, Py_ssize_t n): ret.append((i, f[i])) return ret + ##################################################################### -## Set partition composition +# Set partition composition def set_partition_composition(tuple sp1, tuple sp2): r""" diff --git a/src/sage/combinat/crystals/letters.pxd b/src/sage/combinat/crystals/letters.pxd index 4b9598127cd..e473a02dc24 100644 --- a/src/sage/combinat/crystals/letters.pxd +++ b/src/sage/combinat/crystals/letters.pxd @@ -5,74 +5,74 @@ cdef class Letter(Element): cdef class EmptyLetter(Element): cdef readonly str value - cpdef e(self, int i) - cpdef f(self, int i) - cpdef int epsilon(self, int i) - cpdef int phi(self, int i) + cpdef e(self, int i) noexcept + cpdef f(self, int i) noexcept + cpdef int epsilon(self, int i) noexcept + cpdef int phi(self, int i) noexcept cdef class Crystal_of_letters_type_A_element(Letter): - cpdef Letter e(self, int i) - cpdef Letter f(self, int i) - cpdef int epsilon(self, int i) - cpdef int phi(self, int i) + cpdef Letter e(self, int i) noexcept + cpdef Letter f(self, int i) noexcept + cpdef int epsilon(self, int i) noexcept + cpdef int phi(self, int i) noexcept cdef class Crystal_of_letters_type_B_element(Letter): - cpdef Letter e(self, int i) - cpdef Letter f(self, int i) - cpdef int epsilon(self, int i) - cpdef int phi(self, int i) + cpdef Letter e(self, int i) noexcept + cpdef Letter f(self, int i) noexcept + cpdef int epsilon(self, int i) noexcept + cpdef int phi(self, int i) noexcept cdef class Crystal_of_letters_type_C_element(Letter): - cpdef Letter e(self, int i) - cpdef Letter f(self, int i) - cpdef int epsilon(self, int i) - cpdef int phi(self, int i) + cpdef Letter e(self, int i) noexcept + cpdef Letter f(self, int i) noexcept + cpdef int epsilon(self, int i) noexcept + cpdef int phi(self, int i) noexcept cdef class Crystal_of_letters_type_D_element(Letter): - cpdef Letter e(self, int i) - cpdef Letter f(self, int i) - cpdef int epsilon(self, int i) - cpdef int phi(self, int i) + cpdef Letter e(self, int i) noexcept + cpdef Letter f(self, int i) noexcept + cpdef int epsilon(self, int i) noexcept + cpdef int phi(self, int i) noexcept cdef class Crystal_of_letters_type_G_element(Letter): - cpdef Letter e(self, int i) - cpdef Letter f(self, int i) - cpdef int epsilon(self, int i) - cpdef int phi(self, int i) + cpdef Letter e(self, int i) noexcept + cpdef Letter f(self, int i) noexcept + cpdef int epsilon(self, int i) noexcept + cpdef int phi(self, int i) noexcept cdef class LetterTuple(Element): cdef readonly tuple value - cpdef int epsilon(self, int i) - cpdef int phi(self, int i) + cpdef int epsilon(self, int i) noexcept + cpdef int phi(self, int i) noexcept cdef class Crystal_of_letters_type_E6_element(LetterTuple): - cpdef LetterTuple e(self, int i) - cpdef LetterTuple f(self, int i) + cpdef LetterTuple e(self, int i) noexcept + cpdef LetterTuple f(self, int i) noexcept cdef class Crystal_of_letters_type_E6_element_dual(LetterTuple): - cpdef LetterTuple lift(self) - cpdef LetterTuple retract(self, LetterTuple p) - cpdef LetterTuple e(self, int i) - cpdef LetterTuple f(self, int i) + cpdef LetterTuple lift(self) noexcept + cpdef LetterTuple retract(self, LetterTuple p) noexcept + cpdef LetterTuple e(self, int i) noexcept + cpdef LetterTuple f(self, int i) noexcept cdef class Crystal_of_letters_type_E7_element(LetterTuple): - cpdef LetterTuple e(self, int i) - cpdef LetterTuple f(self, int i) + cpdef LetterTuple e(self, int i) noexcept + cpdef LetterTuple f(self, int i) noexcept cdef class BKKLetter(Letter): - cpdef Letter e(self, int i) - cpdef Letter f(self, int i) + cpdef Letter e(self, int i) noexcept + cpdef Letter f(self, int i) noexcept cdef class QueerLetter_element(Letter): - cpdef Letter e(self, int i) - cpdef Letter f(self, int i) - cpdef int epsilon(self, int i) - cpdef int phi(self, int i) + cpdef Letter e(self, int i) noexcept + cpdef Letter f(self, int i) noexcept + cpdef int epsilon(self, int i) noexcept + cpdef int phi(self, int i) noexcept cdef class LetterWrapped(Element): cdef readonly Element value - cpdef tuple _to_tuple(self) - cpdef LetterWrapped e(self, int i) - cpdef LetterWrapped f(self, int i) - cpdef int epsilon(self, int i) - cpdef int phi(self, int i) + cpdef tuple _to_tuple(self) noexcept + cpdef LetterWrapped e(self, int i) noexcept + cpdef LetterWrapped f(self, int i) noexcept + cpdef int epsilon(self, int i) noexcept + cpdef int phi(self, int i) noexcept diff --git a/src/sage/combinat/crystals/letters.pyx b/src/sage/combinat/crystals/letters.pyx index d204a979563..cf8d25587d8 100644 --- a/src/sage/combinat/crystals/letters.pyx +++ b/src/sage/combinat/crystals/letters.pyx @@ -464,7 +464,7 @@ cdef class Letter(Element): """ return self.value - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Return ``True`` if ``left`` compares with ``right`` based on ``op``. @@ -585,7 +585,7 @@ cdef class EmptyLetter(Element): """ return hash(self.value) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Return ``True`` if ``left`` compares with ``right`` based on ``op``. @@ -625,7 +625,7 @@ cdef class EmptyLetter(Element): """ return self._parent.weight_lattice_realization().zero() - cpdef e(self, int i): + cpdef e(self, int i) noexcept: """ Return `e_i` of ``self`` which is ``None``. @@ -636,7 +636,7 @@ cdef class EmptyLetter(Element): """ return None - cpdef f(self, int i): + cpdef f(self, int i) noexcept: """ Return `f_i` of ``self`` which is ``None``. @@ -647,7 +647,7 @@ cdef class EmptyLetter(Element): """ return None - cpdef int epsilon(self, int i): + cpdef int epsilon(self, int i) noexcept: r""" Return `\varepsilon_i` of ``self``. @@ -659,7 +659,7 @@ cdef class EmptyLetter(Element): """ return 0 - cpdef int phi(self, int i): + cpdef int phi(self, int i) noexcept: r""" Return `\varphi_i` of ``self``. @@ -711,7 +711,7 @@ cdef class Crystal_of_letters_type_A_element(Letter): """ return self._parent.weight_lattice_realization().monomial(self.value-1) - cpdef Letter e(self, int i): + cpdef Letter e(self, int i) noexcept: r""" Return the action of `e_i` on ``self``. @@ -726,7 +726,7 @@ cdef class Crystal_of_letters_type_A_element(Letter): else: return None - cpdef Letter f(self, int i): + cpdef Letter f(self, int i) noexcept: r""" Return the action of `f_i` on ``self``. @@ -741,7 +741,7 @@ cdef class Crystal_of_letters_type_A_element(Letter): else: return None - cpdef int epsilon(self, int i): + cpdef int epsilon(self, int i) noexcept: r""" Return `\varepsilon_i` of ``self``. @@ -755,7 +755,7 @@ cdef class Crystal_of_letters_type_A_element(Letter): return 1 return 0 - cpdef int phi(self, int i): + cpdef int phi(self, int i) noexcept: r""" Return `\varphi_i` of ``self``. @@ -804,7 +804,7 @@ cdef class Crystal_of_letters_type_B_element(Letter): else: return self._parent.weight_lattice_realization()(0) - cpdef Letter e(self, int i): + cpdef Letter e(self, int i) noexcept: r""" Return the action of `e_i` on ``self``. @@ -833,7 +833,7 @@ cdef class Crystal_of_letters_type_B_element(Letter): else: return None - cpdef Letter f(self, int i): + cpdef Letter f(self, int i) noexcept: r""" Return the actions of `f_i` on ``self``. @@ -862,7 +862,7 @@ cdef class Crystal_of_letters_type_B_element(Letter): else: return None - cpdef int epsilon(self, int i): + cpdef int epsilon(self, int i) noexcept: r""" Return `\varepsilon_i` of ``self``. @@ -883,7 +883,7 @@ cdef class Crystal_of_letters_type_B_element(Letter): return 1 return 0 - cpdef int phi(self, int i): + cpdef int phi(self, int i) noexcept: r""" Return `\varphi_i` of ``self``. @@ -942,7 +942,7 @@ cdef class Crystal_of_letters_type_C_element(Letter): else: return self._parent.weight_lattice_realization()(0) - cpdef Letter e(self, int i): + cpdef Letter e(self, int i) noexcept: r""" Return the action of `e_i` on ``self``. @@ -965,7 +965,7 @@ cdef class Crystal_of_letters_type_C_element(Letter): else: return None - cpdef Letter f(self, int i): + cpdef Letter f(self, int i) noexcept: r""" Return the action of `f_i` on ``self``. @@ -983,7 +983,7 @@ cdef class Crystal_of_letters_type_C_element(Letter): else: return None - cpdef int epsilon(self, int i): + cpdef int epsilon(self, int i) noexcept: r""" Return `\varepsilon_i` of ``self``. @@ -997,7 +997,7 @@ cdef class Crystal_of_letters_type_C_element(Letter): return 1 return 0 - cpdef int phi(self, int i): + cpdef int phi(self, int i) noexcept: r""" Return `\varphi_i` of ``self``. @@ -1049,7 +1049,7 @@ cdef class Crystal_of_letters_type_D_element(Letter): else: return self._parent.weight_lattice_realization()(0) - cpdef Letter e(self, int i): + cpdef Letter e(self, int i) noexcept: r""" Return the action of `e_i` on ``self``. @@ -1082,7 +1082,7 @@ cdef class Crystal_of_letters_type_D_element(Letter): else: return None - cpdef Letter f(self, int i): + cpdef Letter f(self, int i) noexcept: r""" Return the action of `f_i` on ``self``. @@ -1113,7 +1113,7 @@ cdef class Crystal_of_letters_type_D_element(Letter): else: return None - cpdef int epsilon(self, int i): + cpdef int epsilon(self, int i) noexcept: r""" Return `\varepsilon_i` of ``self``. @@ -1130,7 +1130,7 @@ cdef class Crystal_of_letters_type_D_element(Letter): return 1 return 0 - cpdef int phi(self, int i): + cpdef int phi(self, int i) noexcept: r""" Return `\varphi_i` of ``self``. @@ -1188,7 +1188,7 @@ cdef class Crystal_of_letters_type_G_element(Letter): else: raise RuntimeError("G2 crystal of letters element %d not valid" % self.value) - cpdef Letter e(self, int i): + cpdef Letter e(self, int i) noexcept: r""" Return the action of `e_i` on ``self``. @@ -1222,7 +1222,7 @@ cdef class Crystal_of_letters_type_G_element(Letter): else: return None - cpdef Letter f(self, int i): + cpdef Letter f(self, int i) noexcept: r""" Return the action of `f_i` on ``self``. @@ -1256,7 +1256,7 @@ cdef class Crystal_of_letters_type_G_element(Letter): else: return None - cpdef int epsilon(self, int i): + cpdef int epsilon(self, int i) noexcept: r""" Return `\varepsilon_i` of ``self``. @@ -1276,7 +1276,7 @@ cdef class Crystal_of_letters_type_G_element(Letter): return 1 return 0 - cpdef int phi(self, int i): + cpdef int phi(self, int i) noexcept: r""" Return `\varphi_i` of ``self``. @@ -1358,7 +1358,7 @@ cdef class LetterTuple(Element): """ return hash(self.value) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Check comparison between ``left`` and ``right`` based on ``op`` @@ -1438,7 +1438,7 @@ cdef class LetterTuple(Element): ret+= repr(v) return ret + "\\right)" - cpdef int epsilon(self, int i): + cpdef int epsilon(self, int i) noexcept: r""" Return `\varepsilon_i` of ``self``. @@ -1454,7 +1454,7 @@ cdef class LetterTuple(Element): return 1 return 0 - cpdef int phi(self, int i): + cpdef int phi(self, int i) noexcept: r""" Return `\varphi_i` of ``self``. @@ -1555,7 +1555,7 @@ cdef class Crystal_of_letters_type_E6_element(LetterTuple): R = self._parent.weight_lattice_realization().fundamental_weights() return sum(Integer(i).sign() * R[abs(i)] for i in self.value) - cpdef LetterTuple e(self, int i): + cpdef LetterTuple e(self, int i) noexcept: r""" Return the action of `e_i` on ``self``. @@ -1643,7 +1643,7 @@ cdef class Crystal_of_letters_type_E6_element(LetterTuple): else: return None - cpdef LetterTuple f(self, int i): + cpdef LetterTuple f(self, int i) noexcept: r""" Return the action of `f_i` on ``self``. @@ -1774,7 +1774,7 @@ cdef class Crystal_of_letters_type_E6_element_dual(LetterTuple): return l[self._parent.list().index(self)] return repr(self.value) - cpdef LetterTuple lift(self): + cpdef LetterTuple lift(self) noexcept: """ Lift an element of ``self`` to the crystal of letters ``crystals.Letters(['E',6])`` by taking its inverse weight. @@ -1791,7 +1791,7 @@ cdef class Crystal_of_letters_type_E6_element_dual(LetterTuple): # tuple from a list return self._parent._ambient(tuple([-i for i in self.value])) - cpdef LetterTuple retract(self, LetterTuple p): + cpdef LetterTuple retract(self, LetterTuple p) noexcept: """ Retract element ``p``, which is an element in ``crystals.Letters(['E',6])`` to an element in @@ -1814,7 +1814,7 @@ cdef class Crystal_of_letters_type_E6_element_dual(LetterTuple): # tuple from a list return self._parent._element_constructor_(tuple([-i for i in p.value])) - cpdef LetterTuple e(self, int i): + cpdef LetterTuple e(self, int i) noexcept: r""" Return the action of `e_i` on ``self``. @@ -1826,7 +1826,7 @@ cdef class Crystal_of_letters_type_E6_element_dual(LetterTuple): """ return self.retract(self.lift().f(i)) - cpdef LetterTuple f(self, int i): + cpdef LetterTuple f(self, int i) noexcept: r""" Return the action of `f_i` on ``self``. @@ -1956,7 +1956,7 @@ cdef class Crystal_of_letters_type_E7_element(LetterTuple): R = self._parent.weight_lattice_realization().fundamental_weights() return sum(Integer(i).sign() * R[abs(i)] for i in self.value) - cpdef LetterTuple e(self, int i): + cpdef LetterTuple e(self, int i) noexcept: r""" Return the action of `e_i` on ``self``. @@ -2138,7 +2138,7 @@ cdef class Crystal_of_letters_type_E7_element(LetterTuple): else: return None - cpdef LetterTuple f(self, int i): + cpdef LetterTuple f(self, int i) noexcept: r""" Return the action of `f_i` on ``self``. @@ -2395,7 +2395,7 @@ cdef class BKKLetter(Letter): ret = "\\underline{{{}}}".format(ret) return ret - cpdef Letter e(self, int i): + cpdef Letter e(self, int i) noexcept: r""" Return the action of `e_i` on ``self``. @@ -2435,7 +2435,7 @@ cdef class BKKLetter(Letter): return self._parent._element_constructor_(-1) return None - cpdef Letter f(self, int i): + cpdef Letter f(self, int i) noexcept: r""" Return the action of `f_i` on ``self``. @@ -2715,7 +2715,7 @@ cdef class QueerLetter_element(Letter): """ return self._parent.weight_lattice_realization().monomial(self.value-1) - cpdef Letter e(self, int i): + cpdef Letter e(self, int i) noexcept: r""" Return the action of `e_i` on ``self``. @@ -2731,7 +2731,7 @@ cdef class QueerLetter_element(Letter): return self._parent._element_constructor_(self.value-1) return None - cpdef Letter f(self, int i): + cpdef Letter f(self, int i) noexcept: r""" Return the action of `f_i` on ``self``. @@ -2747,7 +2747,7 @@ cdef class QueerLetter_element(Letter): return self._parent._element_constructor_(self.value+1) return None - cpdef int epsilon(self, int i): + cpdef int epsilon(self, int i) noexcept: r""" Return `\varepsilon_i` of ``self``. @@ -2761,7 +2761,7 @@ cdef class QueerLetter_element(Letter): return 1 return 0 - cpdef int phi(self, int i): + cpdef int phi(self, int i) noexcept: r""" Return `\varphi_i` of ``self``. @@ -2823,7 +2823,7 @@ cdef class LetterWrapped(Element): """ return hash(self.value) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Check comparison between ``left`` and ``right`` based on ``op`` @@ -2854,7 +2854,7 @@ cdef class LetterWrapped(Element): return self.value == x.value or x._parent.lt_elements(x, self) return False - cpdef tuple _to_tuple(self): + cpdef tuple _to_tuple(self) noexcept: r""" Return a tuple encoding the `\varepsilon_i` and `\varphi_i` values of ``elt``. @@ -2923,7 +2923,7 @@ cdef class LetterWrapped(Element): ret+= repr(v) return ret + "\\right)" - cpdef LetterWrapped e(self, int i): + cpdef LetterWrapped e(self, int i) noexcept: r""" Return `e_i` of ``self``. @@ -2939,7 +2939,7 @@ cdef class LetterWrapped(Element): return None return type(self)(self._parent, ret) - cpdef LetterWrapped f(self, int i): + cpdef LetterWrapped f(self, int i) noexcept: r""" Return `f_i` of ``self``. @@ -2955,7 +2955,7 @@ cdef class LetterWrapped(Element): return None return type(self)(self._parent, ret) - cpdef int epsilon(self, int i): + cpdef int epsilon(self, int i) noexcept: r""" Return `\varepsilon_i` of ``self``. @@ -2969,7 +2969,7 @@ cdef class LetterWrapped(Element): """ return self.value.epsilon(i) - cpdef int phi(self, int i): + cpdef int phi(self, int i) noexcept: r""" Return `\varphi_i` of ``self``. diff --git a/src/sage/combinat/crystals/pbw_datum.pxd b/src/sage/combinat/crystals/pbw_datum.pxd index 9c3aab083df..ecfbf60b842 100644 --- a/src/sage/combinat/crystals/pbw_datum.pxd +++ b/src/sage/combinat/crystals/pbw_datum.pxd @@ -1,3 +1,3 @@ -cpdef tuple compute_new_lusztig_datum(list enhanced_braid_chain, initial_lusztig_datum) -cpdef tuple tropical_plucker_relation(tuple a, lusztig_datum) -cpdef list enhance_braid_move_chain(braid_move_chain, cartan_type) +cpdef tuple compute_new_lusztig_datum(list enhanced_braid_chain, initial_lusztig_datum) noexcept +cpdef tuple tropical_plucker_relation(tuple a, lusztig_datum) noexcept +cpdef list enhance_braid_move_chain(braid_move_chain, cartan_type) noexcept diff --git a/src/sage/combinat/crystals/pbw_datum.pyx b/src/sage/combinat/crystals/pbw_datum.pyx index 2adcb09d902..a81732cdc73 100644 --- a/src/sage/combinat/crystals/pbw_datum.pyx +++ b/src/sage/combinat/crystals/pbw_datum.pyx @@ -282,7 +282,7 @@ class PBWData(): # UniqueRepresentation? # enhanced_braid_chain is an ugly data structure. @cython.boundscheck(False) @cython.wraparound(False) -cpdef tuple compute_new_lusztig_datum(list enhanced_braid_chain, initial_lusztig_datum): +cpdef tuple compute_new_lusztig_datum(list enhanced_braid_chain, initial_lusztig_datum) noexcept: """ Return the Lusztig datum obtained by applying tropical Plücker relations along ``enhanced_braid_chain`` starting with @@ -330,7 +330,7 @@ cpdef tuple compute_new_lusztig_datum(list enhanced_braid_chain, initial_lusztig # The tropical Plücker relations @cython.boundscheck(False) @cython.wraparound(False) -cpdef tuple tropical_plucker_relation(tuple a, lusztig_datum): +cpdef tuple tropical_plucker_relation(tuple a, lusztig_datum) noexcept: r""" Apply the tropical Plücker relation of type ``a`` to ``lusztig_datum``. @@ -403,7 +403,7 @@ cpdef tuple tropical_plucker_relation(tuple a, lusztig_datum): # TODO: Move to PBW_data? @cython.boundscheck(False) @cython.wraparound(False) -cpdef list enhance_braid_move_chain(braid_move_chain, cartan_type): +cpdef list enhance_braid_move_chain(braid_move_chain, cartan_type) noexcept: r""" Return a list of tuples that records the data of the long words in ``braid_move_chain`` plus the data of the intervals where the braid moves diff --git a/src/sage/combinat/crystals/spins.pxd b/src/sage/combinat/crystals/spins.pxd index a486aaa2518..a98f1702508 100644 --- a/src/sage/combinat/crystals/spins.pxd +++ b/src/sage/combinat/crystals/spins.pxd @@ -5,16 +5,16 @@ cdef class Spin(Element): cdef int _n cdef long _hash - cdef Spin _new_c(self, bint* value) + cdef Spin _new_c(self, bint* value) noexcept cdef class Spin_crystal_type_B_element(Spin): - cpdef Spin e(self, int i) - cpdef Spin f(self, int i) - cpdef int epsilon(self, int i) - cpdef int phi(self, int i) + cpdef Spin e(self, int i) noexcept + cpdef Spin f(self, int i) noexcept + cpdef int epsilon(self, int i) noexcept + cpdef int phi(self, int i) noexcept cdef class Spin_crystal_type_D_element(Spin): - cpdef Spin e(self, int i) - cpdef Spin f(self, int i) - cpdef int epsilon(self, int i) - cpdef int phi(self, int i) + cpdef Spin e(self, int i) noexcept + cpdef Spin f(self, int i) noexcept + cpdef int epsilon(self, int i) noexcept + cpdef int phi(self, int i) noexcept diff --git a/src/sage/combinat/crystals/spins.pyx b/src/sage/combinat/crystals/spins.pyx index 7548b7b695e..97e8157afd5 100644 --- a/src/sage/combinat/crystals/spins.pyx +++ b/src/sage/combinat/crystals/spins.pyx @@ -297,7 +297,7 @@ cdef class Spin(Element): self._value[i] = (val[i] != 1) Element.__init__(self, parent) - cdef Spin _new_c(self, bint* value): + cdef Spin _new_c(self, bint* value) noexcept: r""" Fast creation of a spin element. """ @@ -349,7 +349,7 @@ cdef class Spin(Element): tup = tuple([-1 if self._value[i] else 1 for i in range(self._n)]) return (self._parent, (tup,)) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Return ``True`` if ``left`` compares with ``right`` based on ``op``. @@ -534,7 +534,7 @@ cdef class Spin_crystal_type_B_element(Spin): r""" Type B spin representation crystal element """ - cpdef Spin e(self, int i): + cpdef Spin e(self, int i) noexcept: r""" Return the action of `e_i` on ``self``. @@ -567,7 +567,7 @@ cdef class Spin_crystal_type_B_element(Spin): return self._new_c(ret) return None - cpdef Spin f(self, int i): + cpdef Spin f(self, int i) noexcept: r""" Return the action of `f_i` on ``self``. @@ -600,7 +600,7 @@ cdef class Spin_crystal_type_B_element(Spin): return self._new_c(ret) return None - cpdef int epsilon(self, int i): + cpdef int epsilon(self, int i) noexcept: r""" Return `\varepsilon_i` of ``self``. @@ -617,7 +617,7 @@ cdef class Spin_crystal_type_B_element(Spin): return self._value[i-1] return self._value[i-1] and not self._value[i] - cpdef int phi(self, int i): + cpdef int phi(self, int i) noexcept: r""" Return `\varphi_i` of ``self``. @@ -638,7 +638,7 @@ cdef class Spin_crystal_type_D_element(Spin): r""" Type D spin representation crystal element """ - cpdef Spin e(self, int i): + cpdef Spin e(self, int i) noexcept: r""" Return the action of `e_i` on ``self``. @@ -679,7 +679,7 @@ cdef class Spin_crystal_type_D_element(Spin): return self._new_c(ret) return None - cpdef Spin f(self, int i): + cpdef Spin f(self, int i) noexcept: r""" Return the action of `f_i` on ``self``. @@ -720,7 +720,7 @@ cdef class Spin_crystal_type_D_element(Spin): return self._new_c(ret) return None - cpdef int epsilon(self, int i): + cpdef int epsilon(self, int i) noexcept: r""" Return `\varepsilon_i` of ``self``. @@ -737,7 +737,7 @@ cdef class Spin_crystal_type_D_element(Spin): return self._value[i-1] and self._value[i-2] return self._value[i-1] and not self._value[i] - cpdef int phi(self, int i): + cpdef int phi(self, int i) noexcept: r""" Return `\varphi_i` of ``self``. diff --git a/src/sage/combinat/crystals/tensor_product_element.pxd b/src/sage/combinat/crystals/tensor_product_element.pxd index aae31eb7a03..c1af4e1cb20 100644 --- a/src/sage/combinat/crystals/tensor_product_element.pxd +++ b/src/sage/combinat/crystals/tensor_product_element.pxd @@ -1,14 +1,14 @@ from sage.structure.list_clone cimport ClonableArray cdef class ImmutableListWithParent(ClonableArray): - cpdef _set_index(self, k, value) + cpdef _set_index(self, k, value) noexcept cdef class TensorProductOfCrystalsElement(ImmutableListWithParent): pass cdef class TensorProductOfRegularCrystalsElement(TensorProductOfCrystalsElement): - cpdef position_of_last_unmatched_minus(self, i) - cpdef position_of_first_unmatched_plus(self, i) + cpdef position_of_last_unmatched_minus(self, i) noexcept + cpdef position_of_first_unmatched_plus(self, i) noexcept cdef class CrystalOfTableauxElement(TensorProductOfRegularCrystalsElement): pass @@ -31,4 +31,4 @@ cdef class TensorProductOfQueerSuperCrystalsElement(TensorProductOfRegularCrysta cdef class InfinityQueerCrystalOfTableauxElement(TensorProductOfQueerSuperCrystalsElement): cdef list _row_lengths -cdef Py_ssize_t count_leading(list row, letter) +cdef Py_ssize_t count_leading(list row, letter) noexcept diff --git a/src/sage/combinat/crystals/tensor_product_element.pyx b/src/sage/combinat/crystals/tensor_product_element.pyx index bafdb5e175a..abc5a743a4e 100644 --- a/src/sage/combinat/crystals/tensor_product_element.pyx +++ b/src/sage/combinat/crystals/tensor_product_element.pyx @@ -73,7 +73,7 @@ cdef class ImmutableListWithParent(ClonableArray): self._is_immutable = True self._hash = 0 - cpdef _set_index(self, k, value): + cpdef _set_index(self, k, value) noexcept: r""" Return a sibling of ``self`` obtained by setting the `k^{th}` entry of self to value. @@ -573,7 +573,7 @@ cdef class TensorProductOfRegularCrystalsElement(TensorProductOfCrystalsElement) height = height - minus + plus return height - cpdef position_of_last_unmatched_minus(self, i): + cpdef position_of_last_unmatched_minus(self, i) noexcept: """ Return the position of the last unmatched `-` or ``None`` if there is no unmatched `-`. @@ -599,7 +599,7 @@ cdef class TensorProductOfRegularCrystalsElement(TensorProductOfCrystalsElement) height = height - minus + plus return unmatched_minus - cpdef position_of_first_unmatched_plus(self, i): + cpdef position_of_first_unmatched_plus(self, i) noexcept: """ Return the position of the first unmatched `+` or ``None`` if there is no unmatched `+`. @@ -1858,7 +1858,7 @@ cdef class InfinityQueerCrystalOfTableauxElement(TensorProductOfQueerSuperCrysta ret -= L(1).weight() # From the 1 on the bottom row return ret -cdef Py_ssize_t count_leading(list row, letter): +cdef Py_ssize_t count_leading(list row, letter) noexcept: cdef Py_ssize_t i for i in range(len(row)-1,-1,-1): if row[i] != letter: diff --git a/src/sage/combinat/debruijn_sequence.pyx b/src/sage/combinat/debruijn_sequence.pyx index d98a3e66c87..18fe9212504 100644 --- a/src/sage/combinat/debruijn_sequence.pyx +++ b/src/sage/combinat/debruijn_sequence.pyx @@ -57,15 +57,16 @@ AUTHOR: """ -#******************************************************************************* +# ****************************************************************************** # Copyright (C) 2011 Eviatar Bach # # Distributed under the terms of the GNU General Public License (GPL) -# http://www.gnu.org/licenses/ -#******************************************************************************* +# https://www.gnu.org/licenses/ +# ****************************************************************************** from sage.data_structures.bitset_base cimport * + def debruijn_sequence(int k, int n): """ The generating function for De Bruijn sequences. This avoids the object @@ -93,7 +94,8 @@ def debruijn_sequence(int k, int n): gen(1, 1, k, n) return sequence -cdef gen(int t, int p, k, n): + +cdef gen(int t, int p, k, n) noexcept: """ The internal generation function. This should not be accessed by the user. @@ -183,6 +185,7 @@ def is_debruijn_sequence(seq, k, n): return answer + from sage.categories.finite_sets import FiniteSets from sage.structure.unique_representation import UniqueRepresentation from sage.structure.parent import Parent @@ -190,6 +193,7 @@ from sage.structure.parent import Parent from sage.rings.integer cimport Integer from sage.rings.integer_ring import ZZ + class DeBruijnSequences(UniqueRepresentation, Parent): """ Represents the De Bruijn sequences of given parameters `k` and `n`. @@ -256,35 +260,32 @@ class DeBruijnSequences(UniqueRepresentation, Parent): """ Constructor. - Checks the consistency of the given arguments. + This checks the consistency of the given arguments. TESTS: - Setting ``n`` orr ``k`` to anything under 1 will return a ValueError: - - :: + Setting ``n`` or ``k`` to anything under 1 will return + a :class:`ValueError`:: sage: DeBruijnSequences(3, 0).an_element() Traceback (most recent call last): ... - ValueError: k and n cannot be under 1. + ValueError: k and n cannot be under 1 Setting ``n`` or ``k`` to any type except an integer will return a - TypeError: - - :: + :class:`TypeError`:: sage: DeBruijnSequences(2.5, 3).an_element() Traceback (most recent call last): ... - TypeError: k and n must be integers. + TypeError: k and n must be integers """ Parent.__init__(self, category=FiniteSets()) if n < 1 or k < 1: - raise ValueError('k and n cannot be under 1.') + raise ValueError('k and n cannot be under 1') if (not isinstance(n, (Integer, int)) or - not isinstance(k, (Integer,int))): - raise TypeError('k and n must be integers.') + not isinstance(k, (Integer, int))): + raise TypeError('k and n must be integers') self.k = k self.n = n diff --git a/src/sage/combinat/degree_sequences.pyx b/src/sage/combinat/degree_sequences.pyx index 0ccc2377f2c..2052677a4a4 100644 --- a/src/sage/combinat/degree_sequences.pyx +++ b/src/sage/combinat/degree_sequences.pyx @@ -57,9 +57,9 @@ An integer sequence need not necessarily be a degree sequence. Indeed, in a degree sequence of length `n` no integer can be larger than `n-1` -- the degree of a vertex is at most `n-1` -- and the sum of them is at most `n(n-1)`. -Degree sequences are completely characterized by a result from Erdos and Gallai: +Degree sequences are completely characterized by a result from Erdős and Gallai: -**Erdos and Gallai:** *The sequence of integers* `d_1 \geq \cdots \geq d_n` +**Erdős and Gallai:** *The sequence of integers* `d_1 \geq \cdots \geq d_n` *is a degree sequence if and only if* `\sum_i d_i` is even and `\forall i` .. MATH:: @@ -281,6 +281,7 @@ from cysignals.signals cimport sig_on, sig_off cdef unsigned char * seq cdef list sequences + class DegreeSequences: def __init__(self, n): @@ -307,16 +308,16 @@ class DegreeSequences: sage: DegreeSequences(-1) Traceback (most recent call last): ... - ValueError: The input parameter must be >= 0. + ValueError: the input parameter must be >= 0 """ if n < 0: - raise ValueError("The input parameter must be >= 0.") + raise ValueError("the input parameter must be >= 0") self._n = n def __contains__(self, seq): """ - Checks whether a given integer sequence is the degree sequence - of a graph on `n` elements + Check whether a given integer sequence is the degree sequence + of a graph on `n` elements. EXAMPLES:: @@ -342,7 +343,7 @@ class DegreeSequences: [[0]] """ cdef int n = self._n - if len(seq)!=n: + if len(seq) != n: return False # Is the sum even ? @@ -352,13 +353,13 @@ class DegreeSequences: # Partial represents the left side of Erdos and Gallai's inequality, # i.e. the sum of the i first integers. cdef int partial = 0 - cdef int i,d,dd, right + cdef int i, d, dd, right # Temporary variable to ensure that the sequence is indeed # non-increasing - cdef int prev = n-1 + cdef int prev = n - 1 - for i,d in enumerate(seq): + for i, d in enumerate(seq): # Non-increasing ? if d > prev: @@ -370,9 +371,9 @@ class DegreeSequences: partial += d # Evaluating the right hand side - right = i*(i+1) - for dd in seq[i+1:]: - right += min(dd,i+1) + right = i * (i + 1) + for dd in seq[i + 1:]: + right += min(dd, i + 1) # Comparing the two if partial > right: @@ -404,7 +405,7 @@ class DegreeSequences: sage: all(seq in DS for seq in DS) True """ - return iter( init(self._n) ) + yield from init(self._n) def __dealloc__(): """ @@ -412,7 +413,8 @@ class DegreeSequences: """ sig_free(seq) -cdef init(int n): + +cdef init(int n) noexcept: """ Initializes the memory and starts the enumeration algorithm. """ @@ -432,11 +434,11 @@ cdef init(int n): N = n sequences = [] - enum(1,0) + enum(1, 0) sig_free(seq) return sequences -cdef inline add_seq(): +cdef inline add_seq() noexcept: """ This function is called whenever a sequence is found. @@ -457,7 +459,7 @@ cdef inline add_seq(): sequences.append(s) -cdef void enum(int k, int M): +cdef void enum(int k, int M) noexcept: r""" Main function; for an explanation of the algorithm please refer to the :mod:`sage.combinat.degree_sequences` documentation. @@ -467,7 +469,7 @@ cdef void enum(int k, int M): - ``k`` -- depth of the partial degree sequence - ``M`` -- value of a maximum element in the partial degree sequence """ - cdef int i,j + cdef int i, j global seq cdef int taken = 0 cdef int current_box @@ -491,21 +493,21 @@ cdef void enum(int k, int M): if M == 0: seq[0] += 1 - enum(k+1, M) + enum(k + 1, M) seq[0] -= 1 # We need not automatically increase the degree at each step. In this case, # we have no other choice but to link the new vertex of degree M to vertices # of degree M-1, which will become vertices of degree M too. - elif seq[M-1] >= M: + elif seq[M - 1] >= M: - seq[M] += M+1 - seq[M-1] -= M + seq[M] += M + 1 + seq[M - 1] -= M - enum(k+1, M) + enum(k + 1, M) - seq[M] -= M+1 - seq[M-1] += M + seq[M] -= M + 1 + seq[M - 1] += M ############################################### # Creating vertices of Vertices of degree > M # @@ -542,13 +544,13 @@ cdef void enum(int k, int M): seq[current_box] -= i seq[current_box+1] += i - for max(0,((M+1)-taken-i)) <= j <= n_previous_box: + for max(0, ((M+1)-taken-i)) <= j <= n_previous_box: seq[current_box-1] -= j seq[current_box] += j new_vertex = taken + i + j seq[new_vertex] += 1 - enum(k+1,new_vertex) + enum(k+1, new_vertex) seq[new_vertex] -= 1 seq[current_box-1] += j @@ -566,7 +568,7 @@ cdef void enum(int k, int M): # Now current_box = 0. All the vertices of nonzero degree are taken, we just # want to know how many vertices of degree 0 will be neighbors of the new # vertex. - for max(0,((M+1)-taken)) <= i <= seq[0]: + for max(0, ((M+1)-taken)) <= i <= seq[0]: seq[1] += i seq[0] -= i diff --git a/src/sage/combinat/designs/design_catalog.py b/src/sage/combinat/designs/design_catalog.py index 26b899cb93d..8bf7f14fd0b 100644 --- a/src/sage/combinat/designs/design_catalog.py +++ b/src/sage/combinat/designs/design_catalog.py @@ -118,4 +118,4 @@ 'OAMainFunctions', as_='orthogonal_arrays') lazy_import('sage.combinat.designs.gen_quadrangles_with_spread', - ('generalised_quadrangle_with_spread', 'generalised_quadrangle_hermitian_with_ovoid')) \ No newline at end of file + ('generalised_quadrangle_with_spread', 'generalised_quadrangle_hermitian_with_ovoid')) diff --git a/src/sage/combinat/designs/designs_pyx.pxd b/src/sage/combinat/designs/designs_pyx.pxd index 345a41f2945..8ff6bee5bd4 100644 --- a/src/sage/combinat/designs/designs_pyx.pxd +++ b/src/sage/combinat/designs/designs_pyx.pxd @@ -17,4 +17,4 @@ cdef struct cache_entry: cdef cache_entry * _OA_cache cdef int _OA_cache_size -cpdef _OA_cache_get(int k, int n) +cpdef _OA_cache_get(int k, int n) noexcept diff --git a/src/sage/combinat/designs/designs_pyx.pyx b/src/sage/combinat/designs/designs_pyx.pyx index 4b6638634f6..027cc00fbb0 100644 --- a/src/sage/combinat/designs/designs_pyx.pyx +++ b/src/sage/combinat/designs/designs_pyx.pyx @@ -15,6 +15,7 @@ from cysignals.memory cimport sig_malloc, sig_calloc, sig_realloc, sig_free from sage.misc.unknown import Unknown + def is_covering_array(array, strength=None, levels=None, verbose=False, parameters=False): r""" Check if the input is a covering array with given strength. @@ -349,6 +350,7 @@ def is_orthogonal_array(OA, int k, int n, int t=2, verbose=False, terminology="O bitset_free(seen) return True + def is_group_divisible_design(groups,blocks,v,G=None,K=None,lambd=1,verbose=False): r""" Checks that input is a Group Divisible Design on `\{0,...,v-1\}` @@ -588,6 +590,7 @@ def is_pairwise_balanced_design(blocks,v,K=None,lambd=1,verbose=False): lambd=lambd, verbose=verbose) + def is_projective_plane(blocks, verbose=False): r""" Test whether the blocks form a projective plane on `\{0,...,v-1\}` @@ -661,6 +664,7 @@ def is_projective_plane(blocks, verbose=False): lambd=1, verbose=verbose) + def is_difference_matrix(M,G,k,lmbda=1,verbose=False): r""" Test if `M` is a `(G,k,\lambda)`-difference matrix. @@ -725,6 +729,7 @@ def is_difference_matrix(M,G,k,lmbda=1,verbose=False): """ return is_quasi_difference_matrix(M,G,k,lmbda=lmbda,mu=lmbda,u=0,verbose=verbose) + def is_quasi_difference_matrix(M,G,int k,int lmbda,int mu,int u,verbose=False): r""" Test if the matrix is a `(G,k;\lambda,\mu;u)`-quasi-difference matrix @@ -938,6 +943,7 @@ def is_quasi_difference_matrix(M,G,int k,int lmbda,int mu,int u,verbose=False): sig_free(M_c) return True + # Cached information for OA constructions (see .pxd file for more info) _OA_cache = sig_malloc(2*sizeof(cache_entry)) @@ -948,7 +954,7 @@ _OA_cache[0].max_true = -1 _OA_cache[1].max_true = -1 _OA_cache_size = 2 -cpdef _OA_cache_set(int k,int n,truth_value): +cpdef _OA_cache_set(int k,int n,truth_value) noexcept: r""" Sets a value in the OA cache of existence results @@ -983,7 +989,7 @@ cpdef _OA_cache_set(int k,int n,truth_value): else: _OA_cache[n].min_false = k if k<_OA_cache[n].min_false else _OA_cache[n].min_false -cpdef _OA_cache_get(int k,int n): +cpdef _OA_cache_get(int k,int n) noexcept: r""" Gets a value from the OA cache of existence results @@ -1002,7 +1008,7 @@ cpdef _OA_cache_get(int k,int n): return None -cpdef _OA_cache_construction_available(int k,int n): +cpdef _OA_cache_construction_available(int k,int n) noexcept: r""" Tests if a construction is implemented using the cache's information diff --git a/src/sage/combinat/designs/gen_quadrangles_with_spread.pyx b/src/sage/combinat/designs/gen_quadrangles_with_spread.pyx index 26da661f3cd..72baf1a5d28 100644 --- a/src/sage/combinat/designs/gen_quadrangles_with_spread.pyx +++ b/src/sage/combinat/designs/gen_quadrangles_with_spread.pyx @@ -123,6 +123,7 @@ def generalised_quadrangle_with_spread(const int s, const int t, raise RuntimeError( f"Sage can't build a GQ of order ({s}, {t}) with a spread") + def is_GQ_with_spread(GQ, S, s=None, t=None): r""" Check if GQ is a generalised quadrangle of order `(s,t)` and @@ -233,6 +234,7 @@ def dual_GQ_ovoid(GQ, O): D = IncidenceStructure(newBlocks) return (D, S) + def generalised_quadrangle_hermitian_with_ovoid(const int q): r""" Construct the generalised quadrangle `H(3,q^2)` with an ovoid. diff --git a/src/sage/combinat/designs/orthogonal_arrays_find_recursive.pyx b/src/sage/combinat/designs/orthogonal_arrays_find_recursive.pyx index 066eecb9197..6b6bd11dfb1 100644 --- a/src/sage/combinat/designs/orthogonal_arrays_find_recursive.pyx +++ b/src/sage/combinat/designs/orthogonal_arrays_find_recursive.pyx @@ -51,6 +51,7 @@ from .orthogonal_arrays import orthogonal_array from sage.rings.integer cimport smallInteger from sage.arith.misc import prime_powers + @cached_function def find_recursive_construction(k, n): r""" @@ -114,7 +115,8 @@ def find_recursive_construction(k, n): return res return False -cpdef find_product_decomposition(int k,int n): + +cpdef find_product_decomposition(int k,int n) noexcept: r""" Find `n_1n_2=n` to obtain an `OA(k,n)` by the product construction. @@ -155,7 +157,7 @@ cpdef find_product_decomposition(int k,int n): return wilson_construction, (None,k,n1,n2,(),False) return False -cpdef find_wilson_decomposition_with_one_truncated_group(int k,int n): +cpdef find_wilson_decomposition_with_one_truncated_group(int k,int n) noexcept: r""" Find `rm+u=n` to obtain an `OA(k,n)` by Wilson's construction with one truncated column. @@ -206,7 +208,7 @@ cpdef find_wilson_decomposition_with_one_truncated_group(int k,int n): return False -cpdef find_wilson_decomposition_with_two_truncated_groups(int k,int n): +cpdef find_wilson_decomposition_with_two_truncated_groups(int k,int n) noexcept: r""" Find `rm+r_1+r_2=n` to obtain an `OA(k,n)` by Wilson's construction with two truncated columns. @@ -268,7 +270,7 @@ cpdef find_wilson_decomposition_with_two_truncated_groups(int k,int n): return wilson_construction, (None,k,r,m,(r1,r2),False) return False -cpdef find_construction_3_3(int k,int n): +cpdef find_construction_3_3(int k,int n) noexcept: r""" Find a decomposition for construction 3.3 from [AC07]_ @@ -307,7 +309,7 @@ cpdef find_construction_3_3(int k,int n): from .orthogonal_arrays_build_recursive import construction_3_3 return construction_3_3, (k,nn,mm,i) -cpdef find_construction_3_4(int k,int n): +cpdef find_construction_3_4(int k,int n) noexcept: r""" Find a decomposition for construction 3.4 from [AC07]_ @@ -350,7 +352,7 @@ cpdef find_construction_3_4(int k,int n): from .orthogonal_arrays_build_recursive import construction_3_4 return construction_3_4, (k,nn,mm,r,s) -cpdef find_construction_3_5(int k,int n): +cpdef find_construction_3_5(int k,int n) noexcept: r""" Find a decomposition for construction 3.5 from [AC07]_ @@ -400,7 +402,7 @@ cpdef find_construction_3_5(int k,int n): from .orthogonal_arrays_build_recursive import construction_3_5 return construction_3_5, (k,nn,mm,r,s,t) -cpdef find_construction_3_6(int k,int n): +cpdef find_construction_3_6(int k,int n) noexcept: r""" Find a decomposition for construction 3.6 from [AC07]_ @@ -441,7 +443,7 @@ cpdef find_construction_3_6(int k,int n): from .orthogonal_arrays_build_recursive import construction_3_6 return construction_3_6, (k,nn,mm,i) -cpdef find_q_x(int k,int n): +cpdef find_q_x(int k,int n) noexcept: r""" Find integers `q,x` such that the `q-x` construction yields an `OA(k,n)`. @@ -494,7 +496,7 @@ cpdef find_q_x(int k,int n): return construction_q_x, (k,q,x) return False -cpdef find_thwart_lemma_3_5(int k,int N): +cpdef find_thwart_lemma_3_5(int k,int N) noexcept: r""" Find the values on which Lemma 3.5 from [Thwarts]_ applies. @@ -615,7 +617,7 @@ cpdef find_thwart_lemma_3_5(int k,int N): return False -cpdef find_thwart_lemma_4_1(int k,int n): +cpdef find_thwart_lemma_4_1(int k,int n) noexcept: r""" Find a decomposition for Lemma 4.1 from [Thwarts]_. @@ -664,7 +666,7 @@ cpdef find_thwart_lemma_4_1(int k,int n): return False -cpdef find_three_factor_product(int k,int n): +cpdef find_three_factor_product(int k,int n) noexcept: r""" Find `n_1n_2n_3=n` to obtain an `OA(k,n)` by the three-factor product from [DukesLing14]_ @@ -709,7 +711,7 @@ cpdef find_three_factor_product(int k,int n): return False -cpdef find_brouwer_separable_design(int k,int n): +cpdef find_brouwer_separable_design(int k,int n) noexcept: r""" Find `t(q^2+q+1)+x=n` to obtain an `OA(k,n)` by Brouwer's separable design construction. @@ -880,7 +882,8 @@ def int_as_sum(int value, list S, int k_max): return None -cpdef find_brouwer_van_rees_with_one_truncated_column(int k,int n): + +cpdef find_brouwer_van_rees_with_one_truncated_column(int k,int n) noexcept: r""" Find `rm+x_1+...+x_c=n` such that the Brouwer-van Rees constructions yields a `OA(k,n)`. diff --git a/src/sage/combinat/designs/subhypergraph_search.pyx b/src/sage/combinat/designs/subhypergraph_search.pyx index ace387a4bf2..267ff3b2fe0 100644 --- a/src/sage/combinat/designs/subhypergraph_search.pyx +++ b/src/sage/combinat/designs/subhypergraph_search.pyx @@ -129,13 +129,13 @@ ctypedef struct hypergraph: uint64_t * set_space int * names -cdef inline int bs_get(uint64_t * bitset, int index): +cdef inline int bs_get(uint64_t * bitset, int index) noexcept: r""" Return a bit of a bitset """ return (bitset[index/64]>>(index%64))&1 -cdef inline void bs_set(uint64_t * bitset, int index, int bit): +cdef inline void bs_set(uint64_t * bitset, int index, int bit) noexcept: r""" Set a bit of a bitset. @@ -145,7 +145,7 @@ cdef inline void bs_set(uint64_t * bitset, int index, int bit): bitset[index/64] &= ~(( 1)< bit)<=c` sets of size `k` containing `S` in h1. This @@ -295,7 +295,7 @@ cdef int is_subhypergraph_admissible(hypergraph h1,hypergraph * h2_trace,int n,h return 1 -cdef int cmp_128_bits(void * a, void * b) nogil: +cdef int cmp_128_bits(void * a, void * b) noexcept nogil: r""" Lexicographic order on 128-bits words """ @@ -308,7 +308,7 @@ cdef int cmp_128_bits(void * a, void * b) nogil: else: return -1 -cdef int is_induced_admissible64(hypergraph h1,hypergraph * h2_induced,int n,hypergraph tmp1): +cdef int is_induced_admissible64(hypergraph h1,hypergraph * h2_induced,int n,hypergraph tmp1) noexcept: r""" Test if the hypergraph induced in h1 by 0,...,n-1 is equal to the hypergraph induced in h2 by 0,...,n-1. diff --git a/src/sage/combinat/enumeration_mod_permgroup.pxd b/src/sage/combinat/enumeration_mod_permgroup.pxd index 2f457429ccf..6d73f402321 100644 --- a/src/sage/combinat/enumeration_mod_permgroup.pxd +++ b/src/sage/combinat/enumeration_mod_permgroup.pxd @@ -1,9 +1,9 @@ from sage.structure.list_clone cimport ClonableIntArray -cpdef list all_children(ClonableIntArray v, int max_part) -cpdef int lex_cmp_partial(ClonableIntArray t1, ClonableIntArray t2, int step) -cpdef int lex_cmp(ClonableIntArray t1, ClonableIntArray t2) +cpdef list all_children(ClonableIntArray v, int max_part) noexcept +cpdef int lex_cmp_partial(ClonableIntArray t1, ClonableIntArray t2, int step) noexcept +cpdef int lex_cmp(ClonableIntArray t1, ClonableIntArray t2) noexcept cpdef bint is_canonical(list sgs, ClonableIntArray v) except -1 -cpdef ClonableIntArray canonical_representative_of_orbit_of(list sgs, ClonableIntArray v) -cpdef list canonical_children(list sgs, ClonableIntArray v, int max_part) -cpdef set orbit(list sgs, ClonableIntArray v) +cpdef ClonableIntArray canonical_representative_of_orbit_of(list sgs, ClonableIntArray v) noexcept +cpdef list canonical_children(list sgs, ClonableIntArray v, int max_part) noexcept +cpdef set orbit(list sgs, ClonableIntArray v) noexcept diff --git a/src/sage/combinat/enumeration_mod_permgroup.pyx b/src/sage/combinat/enumeration_mod_permgroup.pyx index 3e0b891165f..0da6b2d2638 100644 --- a/src/sage/combinat/enumeration_mod_permgroup.pyx +++ b/src/sage/combinat/enumeration_mod_permgroup.pyx @@ -12,7 +12,7 @@ Tools for enumeration modulo the action of a permutation group from sage.groups.perm_gps.permgroup_element cimport PermutationGroupElement -cpdef list all_children(ClonableIntArray v, int max_part): +cpdef list all_children(ClonableIntArray v, int max_part) noexcept: r""" Returns all the children of an integer vector (:class:`~sage.structure.list_clone.ClonableIntArray`) ``v`` in the tree of enumeration by lexicographic order. The children of @@ -56,7 +56,7 @@ cpdef list all_children(ClonableIntArray v, int max_part): all_children.append(child) return all_children -cpdef int lex_cmp_partial(ClonableIntArray v1, ClonableIntArray v2, int step): +cpdef int lex_cmp_partial(ClonableIntArray v1, ClonableIntArray v2, int step) noexcept: r""" Partial comparison of the two lists according the lexicographic order. It compares the ``step``-th first entries. @@ -85,7 +85,7 @@ cpdef int lex_cmp_partial(ClonableIntArray v1, ClonableIntArray v2, int step): return -1 return 0 -cpdef int lex_cmp(ClonableIntArray v1, ClonableIntArray v2): +cpdef int lex_cmp(ClonableIntArray v1, ClonableIntArray v2) noexcept: """ Lexicographic comparison of :class:`~sage.structure.list_clone.ClonableIntArray`. @@ -183,7 +183,7 @@ cpdef bint is_canonical(list sgs, ClonableIntArray v) except -1: return True -cpdef ClonableIntArray canonical_representative_of_orbit_of(list sgs, ClonableIntArray v): +cpdef ClonableIntArray canonical_representative_of_orbit_of(list sgs, ClonableIntArray v) noexcept: r""" Returns the maximal vector for the lexicographic order living in the orbit of `v` under the action of the permutation group whose @@ -229,7 +229,7 @@ cpdef ClonableIntArray canonical_representative_of_orbit_of(list sgs, ClonableIn representative = max(to_analyse) return representative -cpdef list canonical_children(list sgs, ClonableIntArray v, int max_part): +cpdef list canonical_children(list sgs, ClonableIntArray v, int max_part) noexcept: r""" Returns the canonical children of the integer vector ``v``. This function computes all children of the integer vector ``v`` via the @@ -250,7 +250,7 @@ cpdef list canonical_children(list sgs, ClonableIntArray v, int max_part): cdef ClonableIntArray child return [child for child in all_children(v, max_part) if is_canonical(sgs, child)] -cpdef set orbit(list sgs, ClonableIntArray v): +cpdef set orbit(list sgs, ClonableIntArray v) noexcept: r""" Returns the orbit of the integer vector ``v`` under the action of the permutation group whose strong generating system is ``sgs``. diff --git a/src/sage/combinat/expnums.pyx b/src/sage/combinat/expnums.pyx index bff30b763d7..216850b43f1 100644 --- a/src/sage/combinat/expnums.pyx +++ b/src/sage/combinat/expnums.pyx @@ -117,6 +117,7 @@ def expnums(int n, int aa): # return bell[1]; # end); + def expnums2(n, aa): r""" A vanilla python (but compiled via Cython) implementation of diff --git a/src/sage/combinat/fast_vector_partitions.pyx b/src/sage/combinat/fast_vector_partitions.pyx index 2a1e093104b..5142eb79108 100644 --- a/src/sage/combinat/fast_vector_partitions.pyx +++ b/src/sage/combinat/fast_vector_partitions.pyx @@ -30,7 +30,7 @@ AUTHORS: # # To understand the code below, consult the ALGORITHM. -cdef list vector_halve(list v): +cdef list vector_halve(list v) noexcept: r""" Return the vector halfway (lexicographically) between ``v`` and zero. @@ -126,19 +126,20 @@ def recursive_within_from_to(list m, list s, list e, bint useS, bint useE): if len(m) == 1: # We use this style of Cython code for now in order to get this to convert # to an optimized pure C for loop. See Cython github issue #532. - #for x in range(start, end - 1, -1): + # for x in range(start, end - 1, -1): for x from start >= x >= end by 1: yield [x] # we know the answer for singletons else: # We use this style of Cython code for now in order to get this to convert # to an optimized pure C for loop. See Cython github issue #532. - #for x in range(start, end - 1, -1): + # for x in range(start, end - 1, -1): for x from start >= x >= end by 1: useSS = useS and x == s[0] useEE = useE and x == e[0] for o in recursive_within_from_to(m[1:], s[1:], e[1:], useSS, useEE): yield [x] + o + def within_from_to(list m, list s, list e): r""" Iterate over a lexicographically ordered list of lists ``v`` satisfying @@ -229,7 +230,8 @@ def within_from_to(list m, list s, list e): return yield from recursive_within_from_to(m, ss, e, True, True) -cdef inline list vector_sub(list a, list b): + +cdef inline list vector_sub(list a, list b) noexcept: """ Return ``a - b`` considered as vectors. @@ -241,6 +243,7 @@ cdef inline list vector_sub(list a, list b): ret.append(( a[i]) - ( b[i])) return ret + def recursive_vector_partitions(list v, list vL): r""" Iterate over a lexicographically ordered list of lists, each list diff --git a/src/sage/combinat/finite_state_machine.py b/src/sage/combinat/finite_state_machine.py index acd0adb2718..8bfddfaf76a 100644 --- a/src/sage/combinat/finite_state_machine.py +++ b/src/sage/combinat/finite_state_machine.py @@ -949,7 +949,7 @@ from sage.structure.sage_object import SageObject -def full_group_by(l, key=lambda x: x): +def full_group_by(l, key=None): """ Group iterable ``l`` by values of ``key``. @@ -1003,6 +1003,8 @@ def full_group_by(l, key=lambda x: x): Here, the result ``r`` has been sorted in order to guarantee a consistent order for the doctest suite. """ + if key is None: + key = lambda x: x elements = defaultdict(list) original_keys = {} for item in l: @@ -5406,8 +5408,7 @@ def _iter_transitions_all_(self): [('1', '2'), ('2', '2')] """ for state in self.iter_states(): - for t in state.transitions: - yield t + yield from state.transitions def initial_states(self): """ @@ -6461,8 +6462,7 @@ def _iter_process_simple_(self, iterator): "here." % (len(branch.outputs),)) - for o in branch.outputs[0]: - yield o + yield from branch.outputs[0] branch.outputs[0] = [] # Reset output so that in the next round # (of "for current in iterator") only new diff --git a/src/sage/combinat/free_module.py b/src/sage/combinat/free_module.py index 2dce68651a2..14711e8713e 100644 --- a/src/sage/combinat/free_module.py +++ b/src/sage/combinat/free_module.py @@ -328,7 +328,7 @@ def __classcall_private__(cls, base_ring, basis_keys=None, category=None, latex_names = tuple(latex_names) keywords['latex_names'] = latex_names - return super(CombinatorialFreeModule, cls).__classcall__(cls, + return super().__classcall__(cls, base_ring, basis_keys, category=category, prefix=prefix, names=names, **keywords) @@ -1674,7 +1674,7 @@ def _coerce_map_from_(self, R): [vector_map[i](M.monomial(x[i])) for i, M in enumerate(modules)]), codomain=self) - return super(CombinatorialFreeModule_Tensor, self)._coerce_map_from_(R) + return super()._coerce_map_from_(R) class CartesianProductWithFlattening(): diff --git a/src/sage/combinat/integer_matrices.py b/src/sage/combinat/integer_matrices.py index 8d737c64349..238d0ef4091 100644 --- a/src/sage/combinat/integer_matrices.py +++ b/src/sage/combinat/integer_matrices.py @@ -77,7 +77,7 @@ def __classcall__(cls, row_sums, column_sums): from sage.combinat.composition import Composition row_sums = Composition(row_sums) column_sums = Composition(column_sums) - return super(IntegerMatrices, cls).__classcall__(cls, row_sums, column_sums) + return super().__classcall__(cls, row_sums, column_sums) def __init__(self, row_sums, column_sums): r""" diff --git a/src/sage/combinat/integer_vector_weighted.py b/src/sage/combinat/integer_vector_weighted.py index bd2198f29da..c7700671c61 100644 --- a/src/sage/combinat/integer_vector_weighted.py +++ b/src/sage/combinat/integer_vector_weighted.py @@ -101,7 +101,7 @@ def __classcall_private__(cls, n=None, weight=None): if n is None: return WeightedIntegerVectors_all(weight) - return super(WeightedIntegerVectors, cls).__classcall__(cls, n, weight) + return super().__classcall__(cls, n, weight) def __init__(self, n, weight): """ diff --git a/src/sage/combinat/k_tableau.py b/src/sage/combinat/k_tableau.py index 530f621ca31..0e4bbc41758 100644 --- a/src/sage/combinat/k_tableau.py +++ b/src/sage/combinat/k_tableau.py @@ -4104,8 +4104,7 @@ def __iter__(self): yield self([[None]*(row) for row in self._inner_shape]) else: for unT in StrongTableaux.standard_unmarked_iterator( self.k, size, self._outer_shape, self._inner_shape ): - for T in StrongTableaux.marked_given_unmarked_and_weight_iterator( unT, self.k, self._weight ): - yield T + yield from StrongTableaux.marked_given_unmarked_and_weight_iterator( unT, self.k, self._weight ) @classmethod def standard_unmarked_iterator( cls, k, size, outer_shape=None, inner_shape=[] ): @@ -4410,8 +4409,7 @@ def standard_marked_iterator( cls, k, size, outer_shape=None, inner_shape=[] ): [[]] """ for T in cls.standard_unmarked_iterator( k, size, outer_shape, inner_shape ): - for TT in cls.marked_given_unmarked_and_weight_iterator( T, k, [1]*(size) ): - yield TT + yield from cls.marked_given_unmarked_and_weight_iterator( T, k, [1]*(size) ) @classmethod def cells_head_dictionary( cls, T ): diff --git a/src/sage/combinat/lr_tableau.py b/src/sage/combinat/lr_tableau.py index c19effc2173..a94f576a134 100644 --- a/src/sage/combinat/lr_tableau.py +++ b/src/sage/combinat/lr_tableau.py @@ -174,7 +174,7 @@ def __classcall_private__(cls, shape, weight): weight = tuple(Partition(a) for a in weight) if shape.size() != sum(a.size() for a in weight): raise ValueError("the sizes of shapes and sequence of weights do not match") - return super(LittlewoodRichardsonTableaux, cls).__classcall__(cls, shape, weight) + return super().__classcall__(cls, shape, weight) def __init__(self, shape, weight): r""" @@ -193,7 +193,7 @@ def __init__(self, shape, weight): self._shape = shape self._weight = weight self._heights = [a.length() for a in self._weight] - super(LittlewoodRichardsonTableaux, self).__init__(category=FiniteEnumeratedSets()) + super().__init__(category=FiniteEnumeratedSets()) def _repr_(self): """ diff --git a/src/sage/combinat/matrices/dancing_links.pyx b/src/sage/combinat/matrices/dancing_links.pyx index df6cb7915f8..f0ecfeacd17 100644 --- a/src/sage/combinat/matrices/dancing_links.pyx +++ b/src/sage/combinat/matrices/dancing_links.pyx @@ -67,7 +67,7 @@ There is also a method ``reinitialize`` to reinitialize the algorithm:: sage: x.get_solution() [0, 1] """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2008 Carlo Hamalainen # Copyright (C) 2015-2018 Sébastien Labbé # @@ -75,8 +75,8 @@ There is also a method ``reinitialize`` to reinitialize the algorithm:: # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. -# http://www.gnu.org/licenses/ -#***************************************************************************** +# https://www.gnu.org/licenses/ +# **************************************************************************** from cpython.object cimport PyObject_RichCompare from libcpp.vector cimport vector diff --git a/src/sage/combinat/partitions.pyx b/src/sage/combinat/partitions.pyx index c26ccdb3ddb..c461797067c 100644 --- a/src/sage/combinat/partitions.pyx +++ b/src/sage/combinat/partitions.pyx @@ -8,7 +8,7 @@ AUTHOR: that does all the actual heavy lifting. """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2007 William Stein # Copyright (C) 2007 Jonathan Bober # @@ -16,8 +16,9 @@ AUTHOR: # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. -# http://www.gnu.org/licenses/ -#***************************************************************************** +# https://www.gnu.org/licenses/ +# **************************************************************************** + def ZS1_iterator(int n): """ @@ -82,9 +83,10 @@ def ZS1_iterator(int n): if t > 1: h += 1 x[h] = t - #yield [x[i] for i in range(m+1)] + # yield [x[i] for i in range(m+1)] yield x[:m+1] - #free(x) + # free(x) + def ZS1_iterator_nk(int n, int k): """ @@ -176,4 +178,4 @@ def ZS1_iterator_nk(int n, int k): h += 1 x[m] = t yield x[:m+1] - #free(x) + # free(x) diff --git a/src/sage/combinat/permutation.py b/src/sage/combinat/permutation.py index 8b3d1899ba0..eb3e451b0ff 100644 --- a/src/sage/combinat/permutation.py +++ b/src/sage/combinat/permutation.py @@ -7268,7 +7268,7 @@ def algebra(self, base_ring, category=None): Symmetric group algebra of order 4 over Rational Field sage: A.category() # optional - sage.combinat sage.modules - Join of Category of coxeter group algebras over Rational Field + Join of Category of Coxeter group algebras over Rational Field and Category of finite group algebras over Rational Field and Category of finite dimensional cellular algebras with basis over Rational Field diff --git a/src/sage/combinat/permutation_cython.pxd b/src/sage/combinat/permutation_cython.pxd index 9f19d942604..9744b2f549e 100644 --- a/src/sage/combinat/permutation_cython.pxd +++ b/src/sage/combinat/permutation_cython.pxd @@ -1,11 +1,11 @@ from cpython.array cimport array -cdef void reset_swap(int n, int *c, int *o) -cdef int next_swap(int n, int *c, int *o) -cpdef bint next_perm(array l) -cpdef map_to_list(array l, tuple values, int n) -cpdef list left_action_same_n(list l, list r) -cpdef list right_action_same_n(list l, list r) -cpdef list left_action_product(list l, list r) -cpdef list right_action_product(list l, list r) +cdef void reset_swap(int n, int *c, int *o) noexcept +cdef int next_swap(int n, int *c, int *o) noexcept +cpdef bint next_perm(array l) noexcept +cpdef map_to_list(array l, tuple values, int n) noexcept +cpdef list left_action_same_n(list l, list r) noexcept +cpdef list right_action_same_n(list l, list r) noexcept +cpdef list left_action_product(list l, list r) noexcept +cpdef list right_action_product(list l, list r) noexcept diff --git a/src/sage/combinat/permutation_cython.pyx b/src/sage/combinat/permutation_cython.pyx index 1a0b02ac734..17010476cd9 100644 --- a/src/sage/combinat/permutation_cython.pyx +++ b/src/sage/combinat/permutation_cython.pyx @@ -54,7 +54,7 @@ from cysignals.memory cimport check_allocarray, sig_free # ########################################################## -cdef void reset_swap(int n, int *c, int *o): +cdef void reset_swap(int n, int *c, int *o) noexcept: """ Reset the plain_swapper to the initial state. """ @@ -63,7 +63,7 @@ cdef void reset_swap(int n, int *c, int *o): c[i] = -1 o[i] = 1 -cdef int next_swap(int n, int *c, int *o): +cdef int next_swap(int n, int *c, int *o) noexcept: """ Here's the translation of Algorithm P. We've modified it to @@ -174,7 +174,7 @@ def permutation_iterator_transposition_list(int n): @cython.wraparound(False) @cython.boundscheck(False) -cpdef bint next_perm(array l): +cpdef bint next_perm(array l) noexcept: """ Obtain the next permutation under lex order of ``l`` by mutating ``l``. @@ -255,7 +255,7 @@ cpdef bint next_perm(array l): @cython.boundscheck(False) -cpdef map_to_list(array l, tuple values, int n): +cpdef map_to_list(array l, tuple values, int n) noexcept: """ Build a list by mapping the array ``l`` using ``values``. @@ -291,7 +291,7 @@ cpdef map_to_list(array l, tuple values, int n): ##################################################################### ## Multiplication functions for permutations -cpdef list left_action_same_n(list S, list lp): +cpdef list left_action_same_n(list S, list lp) noexcept: r""" Return the permutation obtained by composing a permutation ``S`` with a permutation ``lp`` in such an order that ``lp`` @@ -318,7 +318,7 @@ cpdef list left_action_same_n(list S, list lp): ret.append(S[i-1]) return ret -cpdef list right_action_same_n(list S, list rp): +cpdef list right_action_same_n(list S, list rp) noexcept: """ Return the permutation obtained by composing a permutation ``S`` with a permutation ``rp`` in such an order that ``S`` is @@ -345,7 +345,7 @@ cpdef list right_action_same_n(list S, list rp): ret.append(rp[i-1]) return ret -cpdef list left_action_product(list S, list lp): +cpdef list left_action_product(list S, list lp) noexcept: r""" Return the permutation obtained by composing a permutation ``S`` with a permutation ``lp`` in such an order that ``lp`` is @@ -379,7 +379,7 @@ cpdef list left_action_product(list S, list lp): lp.append(i) return left_action_same_n(S, lp) -cpdef list right_action_product(list S, list rp): +cpdef list right_action_product(list S, list rp) noexcept: """ Return the permutation obtained by composing a permutation ``S`` with a permutation ``rp`` in such an order that ``S`` is diff --git a/src/sage/combinat/plane_partition.py b/src/sage/combinat/plane_partition.py index 14d284b77c6..d18177aac00 100644 --- a/src/sage/combinat/plane_partition.py +++ b/src/sage/combinat/plane_partition.py @@ -1748,7 +1748,7 @@ def __init__(self, n): sage: TestSuite(PP).run() """ - super(PlanePartitions_n, self).__init__(category=FiniteEnumeratedSets()) + super().__init__(category=FiniteEnumeratedSets()) self._n = n def _repr_(self) -> str: diff --git a/src/sage/combinat/posets/hasse_cython_flint.pyx b/src/sage/combinat/posets/hasse_cython_flint.pyx index fcbe29faaf6..fb01d5967f2 100644 --- a/src/sage/combinat/posets/hasse_cython_flint.pyx +++ b/src/sage/combinat/posets/hasse_cython_flint.pyx @@ -22,7 +22,7 @@ from sage.matrix.matrix_space import MatrixSpace from sage.rings.integer_ring import ZZ -cpdef Matrix_integer_dense moebius_matrix_fast(list positions): +cpdef Matrix_integer_dense moebius_matrix_fast(list positions) noexcept: """ Compute the Möbius matrix of a poset by a specific triangular inversion. @@ -61,7 +61,7 @@ cpdef Matrix_integer_dense moebius_matrix_fast(list positions): for i in range(n): pos_lens[i] = len(positions[i]) pos_array[i] = sig_malloc(pos_lens[i]*sizeof(int)) - for jind,j in enumerate(positions[i]): + for jind, j in enumerate(positions[i]): pos_array[i][jind] = j for i in range(n - 1, -1, -1): @@ -81,7 +81,7 @@ cpdef Matrix_integer_dense moebius_matrix_fast(list positions): return A -cpdef Matrix_integer_dense coxeter_matrix_fast(list positions): +cpdef Matrix_integer_dense coxeter_matrix_fast(list positions) noexcept: """ Compute the Coxeter matrix of a poset by a specific algorithm. @@ -120,7 +120,7 @@ cpdef Matrix_integer_dense coxeter_matrix_fast(list positions): for i in range(n): pos_lens[i] = len(positions[i]) pos_array[i] = sig_malloc(pos_lens[i]*sizeof(int)) - for jind,j in enumerate(positions[i]): + for jind, j in enumerate(positions[i]): pos_array[i][jind] = j for i in range(n - 1, -1, -1): diff --git a/src/sage/combinat/posets/linear_extension_iterator.pyx b/src/sage/combinat/posets/linear_extension_iterator.pyx index 5eb101b32e2..142287d88c2 100644 --- a/src/sage/combinat/posets/linear_extension_iterator.pyx +++ b/src/sage/combinat/posets/linear_extension_iterator.pyx @@ -5,6 +5,8 @@ Fast linear extension iterator cimport cython from copy import copy + + def _linear_extension_prepare(D): r""" The preprocessing routine in Figure 7 of "Generating Linear @@ -27,9 +29,8 @@ def _linear_extension_prepare(D): sage: D = Poset({ 0:[1,2], 1:[3], 2:[3,4] })._hasse_diagram sage: _linear_extension_prepare(D) ([0, 1, 2, 3, 4], [1, 3], [2, 4]) - """ - dag_copy = copy(D) # this copy is destroyed during preparation + dag_copy = copy(D) # this copy is destroyed during preparation le = [] a = [] b = [] @@ -57,9 +58,10 @@ def _linear_extension_prepare(D): return (le, a, b) + @cython.wraparound(False) @cython.boundscheck(False) -cdef void _linear_extension_switch(list _le, list _a, list _b, list _is_plus, Py_ssize_t i): +cdef void _linear_extension_switch(list _le, list _a, list _b, list _is_plus, Py_ssize_t i) noexcept: """ This implements the ``Switch`` procedure described on page 7 of "Generating Linear Extensions Fast" by Pruesse and Ruskey. @@ -81,9 +83,10 @@ cdef void _linear_extension_switch(list _le, list _a, list _b, list _is_plus, Py _b[i] = a _a[i] = b + @cython.wraparound(False) @cython.boundscheck(False) -cdef bint _linear_extension_right_a(_D, list _le, list _a, list _b, Py_ssize_t i): +cdef bint _linear_extension_right_a(_D, list _le, list _a, list _b, Py_ssize_t i) noexcept: """ Return ``True`` if and only if ``_a[i]`` is incomparable with the element to its right in ``_le`` and the element to the right is @@ -109,9 +112,10 @@ cdef bint _linear_extension_right_a(_D, list _le, list _a, list _b, Py_ssize_t i y = _le[yindex] return y != _b[i] and _D.are_incomparable(x, y) + @cython.wraparound(False) @cython.boundscheck(False) -cdef bint _linear_extension_right_b(_D, list _le, list _a, list _b, Py_ssize_t i): +cdef bint _linear_extension_right_b(_D, list _le, list _a, list _b, Py_ssize_t i) noexcept: """ Return True if and only if ``_b[i]`` is incomparable with the elements to its right in ``_le``. @@ -136,6 +140,7 @@ cdef bint _linear_extension_right_b(_D, list _le, list _a, list _b, Py_ssize_t i y = _le[yindex] return _D.are_incomparable(x, y) + @cython.wraparound(False) @cython.boundscheck(False) def _linear_extension_gen(_D, list _le, list _a, list _b, list _is_plus, Py_ssize_t i): @@ -276,7 +281,7 @@ def linear_extension_iterator(D): """ _le, _a, _b = _linear_extension_prepare(D) _max_pair = len(_a) - 1 - _is_plus = [True] # this is modified by _linear_extension_switch + _is_plus = [True] # this is modified by _linear_extension_switch yield _le[:] for e in _linear_extension_gen(D, _le, _a, _b, _is_plus, _max_pair): diff --git a/src/sage/combinat/recognizable_series.py b/src/sage/combinat/recognizable_series.py index 698dd959619..173e061276b 100644 --- a/src/sage/combinat/recognizable_series.py +++ b/src/sage/combinat/recognizable_series.py @@ -455,7 +455,7 @@ def __init__(self, parent, mu, left, right): sage: S.mu[0] is M0, S.mu[1] is M1, S.left is L, S.right is R (True, True, True, True) """ - super(RecognizableSeries, self).__init__(parent=parent) + super().__init__(parent=parent) from copy import copy from sage.matrix.constructor import Matrix @@ -1660,7 +1660,7 @@ def __classcall__(cls, *args, **kwds): sage: Rec1 is Rec2 is Rec3 True """ - return super(RecognizableSeriesSpace, cls).__classcall__( + return super().__classcall__( cls, *cls.__normalize__(*args, **kwds)) @classmethod @@ -1782,7 +1782,7 @@ def __init__(self, coefficient_ring, indices, category, minimize_results): """ self._indices_ = indices self._minimize_results_ = minimize_results - super(RecognizableSeriesSpace, self).__init__( + super().__init__( category=category, base=coefficient_ring) def __reduce__(self): diff --git a/src/sage/combinat/regular_sequence.py b/src/sage/combinat/regular_sequence.py index a10ceb7cf17..c585e51e194 100644 --- a/src/sage/combinat/regular_sequence.py +++ b/src/sage/combinat/regular_sequence.py @@ -1510,7 +1510,7 @@ def some_elements(self): """ return iter(element.regenerated() for element - in super(RegularSequenceRing, self).some_elements( + in super().some_elements( allow_degenerated_sequence=True)) def _element_constructor_(self, *args, **kwds): @@ -1537,7 +1537,7 @@ def _element_constructor_(self, *args, **kwds): 2-regular sequence 1, 3, 6, 9, 12, 18, 18, 27, 24, 36, ... """ allow_degenerated_sequence = kwds.pop('allow_degenerated_sequence', False) - element = super(RegularSequenceRing, self)._element_constructor_(*args, **kwds) + element = super()._element_constructor_(*args, **kwds) if not allow_degenerated_sequence: element._error_if_degenerated_() return element diff --git a/src/sage/combinat/ribbon_shaped_tableau.py b/src/sage/combinat/ribbon_shaped_tableau.py index a5bfc841e7b..4115a6a13aa 100644 --- a/src/sage/combinat/ribbon_shaped_tableau.py +++ b/src/sage/combinat/ribbon_shaped_tableau.py @@ -191,7 +191,7 @@ class based on input. # return RibbonShapedTableaux_shape(Partition(shape)) # Otherwise arg0 takes the place of the category in pickling - return super(RibbonShapedTableaux, cls).__classcall__(cls, **kwds) + return super().__classcall__(cls, **kwds) def __init__(self, category=None): """ @@ -262,7 +262,7 @@ class based on input. return StandardRibbonShapedTableaux_shape(Partition(shape)) # Otherwise arg0 takes the place of the category in pickling - return super(StandardRibbonShapedTableaux, cls).__classcall__(cls, **kwds) + return super().__classcall__(cls, **kwds) def __init__(self, category=None): """ diff --git a/src/sage/combinat/rigged_configurations/kleber_tree.py b/src/sage/combinat/rigged_configurations/kleber_tree.py index 2403ad7ab05..b4a57e365f6 100644 --- a/src/sage/combinat/rigged_configurations/kleber_tree.py +++ b/src/sage/combinat/rigged_configurations/kleber_tree.py @@ -609,7 +609,7 @@ def __classcall_private__(cls, cartan_type, B, classical=None): classical = cartan_type.classical() else: classical = CartanType(classical) - return super(KleberTree, cls).__classcall__(cls, cartan_type, B, classical) + return super().__classcall__(cls, cartan_type, B, classical) def __init__(self, cartan_type, B, classical_ct): r""" @@ -811,8 +811,7 @@ def _children_iter(self, node): # tradeoff occurs between the methods. However, this may grow as # the _children_iter_vector is further optimized. if node != self.root and prod(val+1 for val in node.up_root.coefficients()) < 1000: - for x in self._children_iter_vector(node): - yield x + yield from self._children_iter_vector(node) return n = self._classical_ct.rank() @@ -985,8 +984,7 @@ def _depth_first_iter(self, cur): yield cur for child in cur.children: - for x in self._depth_first_iter(child): - yield x + yield from self._depth_first_iter(child) __iter__ = breadth_first_iter @@ -1160,7 +1158,7 @@ def __classcall_private__(cls, cartan_type, B): return KleberTreeTypeA2Even(cartan_type, B) if cartan_type.classical().is_simply_laced(): raise ValueError("use KleberTree for simply-laced types") - return super(VirtualKleberTree, cls).__classcall__(cls, cartan_type, B) + return super().__classcall__(cls, cartan_type, B) def __init__(self, cartan_type, B): """ @@ -1354,7 +1352,7 @@ def __classcall_private__(cls, cartan_type, B): cartan_type = CartanType(cartan_type) # Standardize B input into a tuple of tuples B = tuple(map(tuple, B)) - return super(KleberTreeTypeA2Even, cls).__classcall__(cls, cartan_type, B) + return super().__classcall__(cls, cartan_type, B) def __init__(self, cartan_type, B): """ diff --git a/src/sage/combinat/rigged_configurations/kr_tableaux.py b/src/sage/combinat/rigged_configurations/kr_tableaux.py index 3addee9e2e5..8bdc1d275b9 100644 --- a/src/sage/combinat/rigged_configurations/kr_tableaux.py +++ b/src/sage/combinat/rigged_configurations/kr_tableaux.py @@ -554,7 +554,7 @@ def tensor(self, *crystals, **options): elif isinstance(B, KirillovReshetikhinTableaux): dims.append([B._r, B._s]) return TensorProductOfKirillovReshetikhinTableaux(ct, dims) - return super(KirillovReshetikhinTableaux, self).tensor(*crystals, **options) + return super().tensor(*crystals, **options) @lazy_attribute def _tableau_height(self): diff --git a/src/sage/combinat/rigged_configurations/rc_crystal.py b/src/sage/combinat/rigged_configurations/rc_crystal.py index 647d3c6eb0d..13bc6a86cfa 100644 --- a/src/sage/combinat/rigged_configurations/rc_crystal.py +++ b/src/sage/combinat/rigged_configurations/rc_crystal.py @@ -153,7 +153,7 @@ def __classcall_private__(cls, cartan_type, wt=None, WLR=None): if isinstance(cartan_type, CartanTypeFolded): return CrystalOfNonSimplyLacedRC(cartan_type, wt, WLR) - return super(CrystalOfRiggedConfigurations, cls).__classcall__(cls, wt, WLR=WLR) + return super().__classcall__(cls, wt, WLR=WLR) def __init__(self, wt, WLR): r""" diff --git a/src/sage/combinat/rigged_configurations/rc_infinity.py b/src/sage/combinat/rigged_configurations/rc_infinity.py index e592f9b3656..d633f50abca 100644 --- a/src/sage/combinat/rigged_configurations/rc_infinity.py +++ b/src/sage/combinat/rigged_configurations/rc_infinity.py @@ -147,7 +147,7 @@ def __classcall_private__(cls, cartan_type): return InfinityCrystalOfNonSimplyLacedRC(cartan_type) cartan_type = CartanType(cartan_type) - return super(InfinityCrystalOfRiggedConfigurations, cls).__classcall__(cls, cartan_type) + return super().__classcall__(cls, cartan_type) def __init__(self, cartan_type): r""" @@ -241,7 +241,7 @@ def _coerce_map_from_(self, P): and self.cartan_type().is_simply_laced()): from sage.combinat.rigged_configurations.bij_infinity import FromTableauIsomorphism return FromTableauIsomorphism(Hom(P, self)) - return super(InfinityCrystalOfRiggedConfigurations, self)._coerce_map_from_(P) + return super()._coerce_map_from_(P) def _calc_vacancy_number(self, partitions, a, i, **options): r""" @@ -358,7 +358,7 @@ def _coerce_map_from_(self, P): if isinstance(P, InfinityCrystalOfTableaux): from sage.combinat.rigged_configurations.bij_infinity import FromTableauIsomorphism return FromTableauIsomorphism(Hom(P, self)) - return super(InfinityCrystalOfNonSimplyLacedRC, self)._coerce_map_from_(P) + return super()._coerce_map_from_(P) def _calc_vacancy_number(self, partitions, a, i): r""" diff --git a/src/sage/combinat/rigged_configurations/rigged_configurations.py b/src/sage/combinat/rigged_configurations/rigged_configurations.py index b822a668612..2d558322721 100644 --- a/src/sage/combinat/rigged_configurations/rigged_configurations.py +++ b/src/sage/combinat/rigged_configurations/rigged_configurations.py @@ -358,7 +358,7 @@ def __classcall_private__(cls, cartan_type, B): if not cartan_type.classical().is_simply_laced(): return RCNonSimplyLaced(cartan_type, B) - return super(RiggedConfigurations, cls).__classcall__(cls, cartan_type, B) + return super().__classcall__(cls, cartan_type, B) def __init__(self, cartan_type, B): r""" @@ -476,7 +476,7 @@ def _repr_option(self, key): """ if key == 'element_ascii_art': return self.options.element_ascii_art - return super(RiggedConfigurations, self)._repr_option(key) + return super()._repr_option(key) def __iter__(self): """ @@ -1062,7 +1062,7 @@ def tensor(self, *crystals, **options): for B in crystals: dims += B.dims return RiggedConfigurations(ct, dims) - return super(RiggedConfigurations, self).tensor(*crystals, **options) + return super().tensor(*crystals, **options) Element = KRRCSimplyLacedElement @@ -1093,7 +1093,7 @@ def __classcall_private__(cls, cartan_type, B): # Standardize B input into a tuple of tuples B = tuple(map(tuple, B)) - return super(RCNonSimplyLaced, cls).__classcall__(cls, cartan_type, B) + return super().__classcall__(cls, cartan_type, B) def __init__(self, cartan_type, dims): """ diff --git a/src/sage/combinat/rigged_configurations/rigged_partition.pxd b/src/sage/combinat/rigged_configurations/rigged_partition.pxd index e99258f33b2..9b333b4fdc6 100644 --- a/src/sage/combinat/rigged_configurations/rigged_partition.pxd +++ b/src/sage/combinat/rigged_configurations/rigged_partition.pxd @@ -6,9 +6,9 @@ cdef class RiggedPartition(SageObject): cdef public list rigging cdef long _hash - cpdef get_num_cells_to_column(self, int end_column, t=*) - cpdef insert_cell(self, int max_width) - cpdef remove_cell(self, row, int num_cells=*) + cpdef get_num_cells_to_column(self, int end_column, t=*) noexcept + cpdef insert_cell(self, int max_width) noexcept + cpdef remove_cell(self, row, int num_cells=*) noexcept cdef class RiggedPartitionTypeB(RiggedPartition): pass diff --git a/src/sage/combinat/rigged_configurations/rigged_partition.pyx b/src/sage/combinat/rigged_configurations/rigged_partition.pyx index 694b3dd5977..5b30b15608f 100644 --- a/src/sage/combinat/rigged_configurations/rigged_partition.pyx +++ b/src/sage/combinat/rigged_configurations/rigged_partition.pyx @@ -354,7 +354,7 @@ cdef class RiggedPartition(SageObject): # Should we move these functions to the CP -> RC bijections? - cpdef get_num_cells_to_column(self, int end_column, t=1): + cpdef get_num_cells_to_column(self, int end_column, t=1) noexcept: r""" Get the number of cells in all columns before the ``end_column``. @@ -394,7 +394,7 @@ cdef class RiggedPartition(SageObject): return sum_cells - cpdef insert_cell(self, int max_width): + cpdef insert_cell(self, int max_width) noexcept: r""" Insert a cell given at a singular value as long as its less than the specified width. @@ -446,7 +446,7 @@ cdef class RiggedPartition(SageObject): self.rigging[max_pos] = None # State that we've changed this row return self._list[max_pos] - 1 - cpdef remove_cell(self, row, int num_cells=1): + cpdef remove_cell(self, row, int num_cells=1) noexcept: r""" Removes a cell at the specified ``row``. diff --git a/src/sage/combinat/rigged_configurations/tensor_product_kr_tableaux.py b/src/sage/combinat/rigged_configurations/tensor_product_kr_tableaux.py index 3314986004f..a2ccd72e902 100644 --- a/src/sage/combinat/rigged_configurations/tensor_product_kr_tableaux.py +++ b/src/sage/combinat/rigged_configurations/tensor_product_kr_tableaux.py @@ -133,8 +133,7 @@ def __iter__(self): if self._cache is None: self._cache = tuple([x.to_tensor_product_of_kirillov_reshetikhin_tableaux() for x in self.tp_krt.rigged_configurations().module_generators]) - for x in self._cache: - yield x + yield from self._cache def __repr__(self): """ @@ -296,7 +295,7 @@ def __classcall_private__(cls, cartan_type, B): # Standardize B input into a tuple of tuples B = tuple(tuple(dim) for dim in B) - return super(TensorProductOfKirillovReshetikhinTableaux, cls).__classcall__(cls, cartan_type, B) + return super().__classcall__(cls, cartan_type, B) def __init__(self, cartan_type, B): r""" @@ -493,7 +492,7 @@ def tensor(self, *crystals, **options): elif isinstance(B, KirillovReshetikhinTableaux): dims.append([B._r, B._s]) return TensorProductOfKirillovReshetikhinTableaux(ct, dims) - return super(TensorProductOfKirillovReshetikhinTableaux, self).tensor(*crystals, **options) + return super().tensor(*crystals, **options) TensorProductOfKirillovReshetikhinTableaux.Element = TensorProductOfKirillovReshetikhinTableauxElement diff --git a/src/sage/combinat/root_system/braid_orbit.pyx b/src/sage/combinat/root_system/braid_orbit.pyx index d95bc388f83..c7983eeb43a 100644 --- a/src/sage/combinat/root_system/braid_orbit.pyx +++ b/src/sage/combinat/root_system/braid_orbit.pyx @@ -1,4 +1,4 @@ -#cython: wraparound=False, boundscheck=False +# cython: wraparound=False, boundscheck=False """ Braid Orbit @@ -7,7 +7,7 @@ Cython function to compute the orbit of the braid moves on a reduced word. from cysignals.signals cimport sig_check -cpdef set BraidOrbit(list word, list rels): +cpdef set BraidOrbit(list word, list rels) noexcept: r""" Return the orbit of ``word`` by all replacements given by ``rels``. @@ -48,11 +48,11 @@ cpdef set BraidOrbit(list word, list rels): cdef list rel l = len(word) - cdef set words = set( [tuple(word)] ) - cdef list test_words = [ tuple(word) ] + cdef set words = {tuple(word)} + cdef list test_words = [tuple(word)] - rels = rels + [ [b,a] for a,b in rels ] - rels = [ [tuple(a), tuple(b), len(a)] for a,b in rels ] + rels = rels + [[b, a] for a, b in rels] + rels = [[tuple(a), tuple(b), len(a)] for a, b in rels] loop_ind = 0 list_len = 1 @@ -74,7 +74,7 @@ cpdef set BraidOrbit(list word, list rels): return words -cpdef bint is_fully_commutative(list word, list rels): +cpdef bint is_fully_commutative(list word, list rels) noexcept: r""" Check if the braid orbit of ``word`` is using a braid relation. @@ -101,8 +101,8 @@ cpdef bint is_fully_commutative(list word, list rels): cdef list rel l = len(word) - cdef set words = set( [tuple(word)] ) - cdef list test_words = [ tuple(word) ] + cdef set words = {tuple(word)} + cdef list test_words = [tuple(word)] rels = rels + [[b, a] for a, b in rels] rels = [[tuple(a), tuple(b), len(a)] for a, b in rels] @@ -129,7 +129,7 @@ cpdef bint is_fully_commutative(list word, list rels): return True -cdef inline bint pattern_match(tuple L, int i, tuple X, int l): +cdef inline bint pattern_match(tuple L, int i, tuple X, int l) noexcept: r""" Return ``True`` if ``L[i:i+l] == X``. diff --git a/src/sage/combinat/root_system/reflection_group_c.pyx b/src/sage/combinat/root_system/reflection_group_c.pyx index 247e9a62c02..e2f5eff21b1 100644 --- a/src/sage/combinat/root_system/reflection_group_c.pyx +++ b/src/sage/combinat/root_system/reflection_group_c.pyx @@ -1,4 +1,4 @@ -#cython: wraparound=False, boundscheck=False +# cython: wraparound=False, boundscheck=False r""" This contains a few time-critical auxiliary cython functions for finite complex or real reflection groups. @@ -31,7 +31,7 @@ cdef class Iterator(): cdef list noncom cdef list order - cdef list noncom_letters(self): + cdef list noncom_letters(self) noexcept: """ Return a list ``L`` of lists such that ... @@ -51,7 +51,7 @@ cdef class Iterator(): for i in range(n): si = S[i] noncom_i = [] - for j in range(i+1,n): + for j in range(i+1, n): sj = S[j] if si._mul_(sj) == sj._mul_(si): pass @@ -87,29 +87,29 @@ cdef class Iterator(): raise ValueError('the algorithm (="%s") must be either "depth", "breadth", or "parabolic"') self.algorithm = algorithm -# self.noncom = self.noncom_letters() + # self.noncom = self.noncom_letters() - cdef list succ(self, PermutationGroupElement u, int first): + cdef list succ(self, PermutationGroupElement u, int first) noexcept: cdef PermutationGroupElement si cdef int i cdef list successors = [] cdef tuple S = self.S cdef int N = self.N -# cdef list nc = self.noncom[first] + # cdef list nc = self.noncom[first] for i in range(first): si = (S[i]) if self.test(u, si, i): - successors.append((_new_mul_(si,u), i)) - for i in range(first+1,self.n): -# for i in nc: + successors.append((_new_mul_(si, u), i)) + for i in range(first+1, self.n): + # for i in nc: if u.perm[i] < N: si = (S[i]) if self.test(u, si, i): - successors.append((_new_mul_(si,u), i)) + successors.append((_new_mul_(si, u), i)) return successors - cdef list succ_words(self, PermutationGroupElement u, list word, int first): + cdef list succ_words(self, PermutationGroupElement u, list word, int first) noexcept: cdef PermutationGroupElement u1, si cdef int i cdef list successors = [] @@ -120,7 +120,7 @@ cdef class Iterator(): for i in range(first): si = (S[i]) if self.test(u, si, i): - u1 = (_new_mul_(si,u)) + u1 = (_new_mul_(si, u)) # try to use word+[i] and the reversed word_new = [i] + word u1._reduced_word = word_new @@ -129,13 +129,13 @@ cdef class Iterator(): if u.perm[i] < N: si = (S[i]) if self.test(u, si, i): - u1 = (_new_mul_(si,u)) + u1 = (_new_mul_(si, u)) word_new = [i] + word u1._reduced_word = word_new successors.append((u1, word_new, i)) return successors - cdef inline bint test(self, PermutationGroupElement u, PermutationGroupElement si, int i): + cdef inline bint test(self, PermutationGroupElement u, PermutationGroupElement si, int i) noexcept: cdef int j cdef int N = self.N cdef int* siperm = si.perm @@ -375,6 +375,7 @@ cdef class Iterator(): for v in coset_reps: yield _new_mul_(w, v) + def iterator_tracking_words(W): r""" Return an iterator through the elements of ``self`` together @@ -417,7 +418,7 @@ def iterator_tracking_words(W): cdef list index_list = list(range(len(S))) cdef list level_set_cur = [(W.one(), [])] - cdef set level_set_old = set([ W.one() ]) + cdef set level_set_old = {W.one()} cdef list word cdef PermutationGroupElement x, y @@ -432,10 +433,11 @@ def iterator_tracking_words(W): level_set_new.append((y, word+[i])) level_set_cur = level_set_new -cdef inline bint has_left_descent(PermutationGroupElement w, int i, int N): + +cdef inline bint has_left_descent(PermutationGroupElement w, int i, int N) noexcept: return w.perm[i] >= N -cdef int first_descent(PermutationGroupElement w, int n, int N, bint left): +cdef int first_descent(PermutationGroupElement w, int n, int N, bint left) noexcept: cdef int i if not left: w = ~w @@ -445,7 +447,7 @@ cdef int first_descent(PermutationGroupElement w, int n, int N, bint left): return -1 cdef int first_descent_in_parabolic(PermutationGroupElement w, list parabolic, - int N, bint left): + int N, bint left) noexcept: cdef int i if not left: w = ~w @@ -457,7 +459,7 @@ cdef int first_descent_in_parabolic(PermutationGroupElement w, list parabolic, cpdef PermutationGroupElement reduce_in_coset(PermutationGroupElement w, tuple S, - list parabolic, int N, bint right): + list parabolic, int N, bint right) noexcept: r""" Return the minimal length coset representative of ``w`` of the parabolic subgroup indexed by ``parabolic`` (with indices `\{0, \ldots, n\}`). @@ -501,7 +503,7 @@ cpdef PermutationGroupElement reduce_in_coset(PermutationGroupElement w, tuple S w = _new_mul_(w, si) cdef list reduced_coset_representatives(W, list parabolic_big, list parabolic_small, - bint right): + bint right) noexcept: cdef tuple S = tuple(W.simple_reflections()) cdef int N = W.number_of_reflections() cdef set totest = set([W.one()]) @@ -515,10 +517,10 @@ cdef list reduced_coset_representatives(W, list parabolic_big, list parabolic_sm S, parabolic_small, N, right) for i in parabolic_big]) res.update(totest) - totest = new.difference(res)#[ w for w in new if w not in res ] + totest = new.difference(res) # [w for w in new if w not in res] return list(res) -cdef parabolic_recursive(PermutationGroupElement x, list v, f): +cdef parabolic_recursive(PermutationGroupElement x, list v, f) noexcept: if not v: f(x) else: @@ -558,7 +560,8 @@ def parabolic_iteration_application(W, f): parabolic_recursive(W.one(), coset_reps, f) -cpdef list reduced_word_c(W, PermutationGroupElement w): + +cpdef list reduced_word_c(W, PermutationGroupElement w) noexcept: r""" Computes a reduced word for the element ``w`` in the reflection group ``W`` in the positions ``range(n)``. @@ -584,7 +587,7 @@ cpdef list reduced_word_c(W, PermutationGroupElement w): word.append(fdes) return word -cdef PermutationGroupElement _new_mul_(PermutationGroupElement left, PermutationGroupElement right): +cdef PermutationGroupElement _new_mul_(PermutationGroupElement left, PermutationGroupElement right) noexcept: """ Multiply two :class:`PermutationGroupElement` directly without the coercion framework. diff --git a/src/sage/combinat/root_system/reflection_group_element.pxd b/src/sage/combinat/root_system/reflection_group_element.pxd index 04e98fc3fb2..194688e25b6 100644 --- a/src/sage/combinat/root_system/reflection_group_element.pxd +++ b/src/sage/combinat/root_system/reflection_group_element.pxd @@ -1,11 +1,11 @@ from sage.groups.perm_gps.permgroup_element cimport PermutationGroupElement cdef class ComplexReflectionGroupElement(PermutationGroupElement): - cpdef action(self, vec, on_space=*) - cpdef action_on_root_indices(self, i) + cpdef action(self, vec, on_space=*) noexcept + cpdef action_on_root_indices(self, i) noexcept cdef class RealReflectionGroupElement(ComplexReflectionGroupElement): - cpdef bint has_left_descent(self, i) - cpdef bint has_descent(self, i, side=*, positive=*) - cpdef action(self, vec, side=*, on_space=*) - cpdef action_on_root_indices(self, i, side=*) + cpdef bint has_left_descent(self, i) noexcept + cpdef bint has_descent(self, i, side=*, positive=*) noexcept + cpdef action(self, vec, side=*, on_space=*) noexcept + cpdef action_on_root_indices(self, i, side=*) noexcept diff --git a/src/sage/combinat/root_system/reflection_group_element.pyx b/src/sage/combinat/root_system/reflection_group_element.pyx index 8f5a61ff0a2..6cc6c6e25a2 100644 --- a/src/sage/combinat/root_system/reflection_group_element.pyx +++ b/src/sage/combinat/root_system/reflection_group_element.pyx @@ -115,7 +115,7 @@ cdef class ComplexReflectionGroupElement(PermutationGroupElement): gens = [W.simple_reflection(j) for j in W._index_set] return _gap_factorization(self, gens) - #@cached_in_parent_method + # @cached_in_parent_method def reduced_word_in_reflections(self): r""" Return a word in the reflections to obtain ``self``. @@ -180,7 +180,7 @@ cdef class ComplexReflectionGroupElement(PermutationGroupElement): """ return ZZ(len(self.reduced_word())) - #@cached_in_parent_method + # @cached_in_parent_method def to_matrix(self, on_space="primal"): r""" Return ``self`` as a matrix acting on the underlying vector @@ -347,7 +347,7 @@ cdef class ComplexReflectionGroupElement(PermutationGroupElement): mat.set_immutable() return mat - cpdef action(self, vec, on_space="primal"): + cpdef action(self, vec, on_space="primal") noexcept: r""" Return the image of ``vec`` under the action of ``self``. @@ -372,7 +372,7 @@ cdef class ComplexReflectionGroupElement(PermutationGroupElement): mat = self.matrix(on_space=on_space) return vec * mat - cpdef _act_on_(self, vec, bint self_on_left): + cpdef _act_on_(self, vec, bint self_on_left) noexcept: r""" Defines the action of ``self`` as a linear transformation on the vector space, in the basis given by the simple @@ -396,7 +396,7 @@ cdef class ComplexReflectionGroupElement(PermutationGroupElement): return (~self).action(vec) return self.action(vec) - cpdef action_on_root_indices(self, i): + cpdef action_on_root_indices(self, i) noexcept: """ Return the right action on the set of roots. @@ -481,7 +481,7 @@ cdef class ComplexReflectionGroupElement(PermutationGroupElement): W = self._parent return PermutationGroupElement(self, W) - #@cached_in_parent_method + # @cached_in_parent_method def fix_space(self): r""" Return the fix space of ``self``. @@ -531,7 +531,7 @@ cdef class ComplexReflectionGroupElement(PermutationGroupElement): I = identity_matrix(QQ, self._parent.rank()) return (self.to_matrix() - I).right_kernel() - #@cached_in_parent_method + # @cached_in_parent_method def reflection_eigenvalues(self, is_class_representative=False): r""" Return the reflection eigenvalues of ``self``. @@ -578,7 +578,7 @@ cdef class ComplexReflectionGroupElement(PermutationGroupElement): """ return self._parent.reflection_eigenvalues(self, is_class_representative=is_class_representative) - #@cached_in_parent_method + # @cached_in_parent_method def galois_conjugates(self): r""" Return all Galois conjugates of ``self``. @@ -683,8 +683,8 @@ cdef class ComplexReflectionGroupElement(PermutationGroupElement): """ rk = self._parent.rank() M = self.to_matrix().list() - m = lcm([x.conductor() if hasattr(x,"conductor") else 1 for x in M]) - cdef list M_gals = [x.galois_conjugates(m) if hasattr(x,"galois_conjugates") else [x] for x in M] + m = lcm([x.conductor() if hasattr(x, "conductor") else 1 for x in M]) + cdef list M_gals = [x.galois_conjugates(m) if hasattr(x, "galois_conjugates") else [x] for x in M] cdef list conjugates = [] cdef int i for i in range(len(M_gals[0])): @@ -763,7 +763,7 @@ cdef class RealReflectionGroupElement(ComplexReflectionGroupElement): """ return ZZ(len(self._reduced_word)) - cpdef bint has_left_descent(self, i): + cpdef bint has_left_descent(self, i) noexcept: r""" Return whether ``i`` is a left descent of ``self``. @@ -784,7 +784,7 @@ cdef class RealReflectionGroupElement(ComplexReflectionGroupElement): # we also check == because 0-based indexing return self.perm[W._index_set_inverse[i]] >= W.number_of_reflections() - cpdef bint has_descent(self, i, side="left", positive=False): + cpdef bint has_descent(self, i, side="left", positive=False) noexcept: r""" Return whether ``i`` is a descent (or ascent) of ``self``. @@ -808,10 +808,10 @@ cdef class RealReflectionGroupElement(ComplexReflectionGroupElement): False """ if not isinstance(positive, bool): - raise TypeError("%s is not a boolean"%(bool)) + raise TypeError("%s is not a boolean" % (bool)) if i not in self._parent.index_set(): - raise ValueError("the given index %s is not in the index set"%i) + raise ValueError("the given index %s is not in the index set" % i) negative = not positive @@ -957,7 +957,7 @@ cdef class RealReflectionGroupElement(ComplexReflectionGroupElement): matrix = to_matrix - cpdef action(self, vec, side="right", on_space="primal"): + cpdef action(self, vec, side="right", on_space="primal") noexcept: r""" Return the image of ``vec`` under the action of ``self``. @@ -1020,7 +1020,7 @@ cdef class RealReflectionGroupElement(ComplexReflectionGroupElement): else: raise ValueError('on_space must be "primal" or "dual"') - cpdef _act_on_(self, vec, bint self_on_left): + cpdef _act_on_(self, vec, bint self_on_left) noexcept: r""" Give the action of ``self`` as a linear transformation on the vector space, in the basis given by the simple roots. @@ -1049,11 +1049,10 @@ cdef class RealReflectionGroupElement(ComplexReflectionGroupElement): (1, 1) -> (0, -1) """ if self_on_left: - return self.action(vec,side="left") - else: - return self.action(vec,side="right") + return self.action(vec, side="left") + return self.action(vec, side="right") - cpdef action_on_root_indices(self, i, side="right"): + cpdef action_on_root_indices(self, i, side="right") noexcept: """ Return the action on the set of roots. @@ -1177,11 +1176,12 @@ def _gap_factorization(w, gens): """ from sage.interfaces.gap3 import gap3 - gap3.execute('W := GroupWithGenerators(%s)'%str(gens)) + gap3.execute('W := GroupWithGenerators(%s)' % str(gens)) gap3.execute(_gap_factorization_code) - fac = gap3('MinimalWord(W,%s)'%str(w)).sage() + fac = gap3('MinimalWord(W,%s)' % str(w)).sage() return [i-1 for i in fac] + _gap_factorization_code = r""" # MinimalWord(G,w) # given a permutation group G find some expression of minimal length in the @@ -1232,6 +1232,7 @@ MinimalWord:=function(G,w) od; end;""" + def _gap_return(S, coerce_obj='self'): r""" Return the string ``S`` after a few modifications are done. @@ -1245,6 +1246,6 @@ def _gap_return(S, coerce_obj='self'): sage: _gap_return("[ (), (1,4)(2,3)(5,6), (1,6,2)(3,5,4) ]") # optional - gap3 "[self('()',check=False),self('(1,4)(2,3)(5,6)',check=False),self('(1,6,2)(3,5,4)',check=False)]" """ - S = S.replace(' ','').replace('\n','') - S = S.replace(',(','\',check=False),%s(\'('%coerce_obj).replace('[','[%s(\''%coerce_obj).replace(']','\',check=False)]') + S = S.replace(' ', '').replace('\n', '') + S = S.replace(',(', '\',check=False),%s(\'(' % coerce_obj).replace('[', '[%s(\'' % coerce_obj).replace(']', '\',check=False)]') return S diff --git a/src/sage/combinat/root_system/type_A.py b/src/sage/combinat/root_system/type_A.py index 96bcec25f39..48d1474c1f4 100644 --- a/src/sage/combinat/root_system/type_A.py +++ b/src/sage/combinat/root_system/type_A.py @@ -277,7 +277,7 @@ def dynkin_diagram(self): g.add_edge(i, i+1) return g - def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2): r""" Return a latex representation of the Dynkin diagram. @@ -297,6 +297,8 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; """ + if label is None: + label = lambda i: i if node is None: node = self._latex_draw_node if self.n > 1: @@ -306,7 +308,7 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): return ret + "".join(node((i-1)*node_dist, 0, label(i)) for i in self.index_set()) - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Return an ascii art representation of the Dynkin diagram. @@ -332,6 +334,8 @@ def ascii_art(self, label=lambda i: i, node=None): n = self.n if n == 0: return "" + if label is None: + label = lambda i: i if node is None: node = self._ascii_art_node ret = "---".join(node(label(i)) for i in range(1,n+1)) + "\n" diff --git a/src/sage/combinat/root_system/type_A_affine.py b/src/sage/combinat/root_system/type_A_affine.py index f10d15c7f0e..57ed18afd01 100644 --- a/src/sage/combinat/root_system/type_A_affine.py +++ b/src/sage/combinat/root_system/type_A_affine.py @@ -111,7 +111,7 @@ def dynkin_diagram(self): g.add_edge(0, n) return g - def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2): r""" Return a latex representation of the Dynkin diagram. @@ -128,6 +128,8 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): \draw[fill=white] (3.0 cm, 1.2 cm) circle (.25cm) node[anchor=south east]{$0$}; """ + if label is None: + label = lambda i: i if node is None: node = self._latex_draw_node if self.n == 1: @@ -148,7 +150,7 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): ret += node(mid, 1.2, label(0), 'anchor=south east') return ret - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Return an ascii art representation of the extended Dynkin diagram. @@ -178,6 +180,8 @@ def ascii_art(self, label=lambda i: i, node=None): O<=>O 2 3 """ + if label is None: + label = lambda i: i if node is None: node = self._ascii_art_node n = self.n diff --git a/src/sage/combinat/root_system/type_A_infinity.py b/src/sage/combinat/root_system/type_A_infinity.py index c3a2c603266..9e0f4711ccd 100644 --- a/src/sage/combinat/root_system/type_A_infinity.py +++ b/src/sage/combinat/root_system/type_A_infinity.py @@ -86,7 +86,7 @@ def _latex_(self): """ return 'A_{{{}}}'.format(self.n._latex_()) - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Return an ascii art representation of the extended Dynkin diagram. @@ -100,6 +100,8 @@ def ascii_art(self, label=lambda i: i, node=None): 0 1 2 3 4 5 6 """ + if label is None: + label = lambda i: i if node is None: node = self._ascii_art_node diff --git a/src/sage/combinat/root_system/type_B.py b/src/sage/combinat/root_system/type_B.py index 67794141adc..8e9cb6e75a5 100644 --- a/src/sage/combinat/root_system/type_B.py +++ b/src/sage/combinat/root_system/type_B.py @@ -245,7 +245,7 @@ def dynkin_diagram(self): g.set_edge_label(n-1, n, 2) return g - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Return an ascii art representation of the Dynkin diagram. @@ -261,6 +261,8 @@ def ascii_art(self, label=lambda i: i, node=None): O---O---O---O=>=O 3 4 5 6 7 """ + if label is None: + label = lambda i: i if node is None: node = self._ascii_art_node n = self.n @@ -271,7 +273,7 @@ def ascii_art(self, label=lambda i: i, node=None): ret += "".join("{!s:4}".format(label(i)) for i in range(1, n + 1)) return ret - def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual=False): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. @@ -307,6 +309,8 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual= - :meth:`sage.combinat.root_system.type_C.CartanType._latex_dynkin_diagram` - :meth:`sage.combinat.root_system.type_BC_affine.CartanType._latex_dynkin_diagram` """ + if label is None: + label = lambda i: i if node is None: node = self._latex_draw_node if self.n == 1: diff --git a/src/sage/combinat/root_system/type_BC_affine.py b/src/sage/combinat/root_system/type_BC_affine.py index bbc261902fb..740dfa2e5f3 100644 --- a/src/sage/combinat/root_system/type_BC_affine.py +++ b/src/sage/combinat/root_system/type_BC_affine.py @@ -138,7 +138,7 @@ def _latex_(self): else: return "BC_{%s}^{(2)}" % self.n - def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual=False): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. @@ -180,6 +180,8 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual= \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$}; """ + if label is None: + label = lambda i: i if node is None: node = self._latex_draw_node if self.n == 1: @@ -206,7 +208,7 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual= ret += "}\n" + node(0, 0, label(0)) return ret - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Return a ascii art representation of the extended Dynkin diagram. @@ -227,6 +229,8 @@ def ascii_art(self, label=lambda i: i, node=None): O=<=O 2 3 """ + if label is None: + label = lambda i: i if node is None: node = self._ascii_art_node n = self.n diff --git a/src/sage/combinat/root_system/type_B_affine.py b/src/sage/combinat/root_system/type_B_affine.py index 6cfe46255ae..047144f02d6 100644 --- a/src/sage/combinat/root_system/type_B_affine.py +++ b/src/sage/combinat/root_system/type_B_affine.py @@ -96,7 +96,7 @@ def dynkin_diagram(self): g.add_edge(0,2) return g - def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual=False): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. @@ -130,6 +130,8 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual= \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; """ + if label is None: + label = lambda i: i if node is None: node = self._latex_draw_node if self.n == 1: @@ -155,7 +157,7 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual= ret += node(i*node_dist, 0, label(i+1)) return ret - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Return an ascii art representation of the extended Dynkin diagram. @@ -184,6 +186,8 @@ def ascii_art(self, label=lambda i: i, node=None): """ n = self.n from .cartan_type import CartanType + if label is None: + label = lambda i: i if node is None: node = self._ascii_art_node if n == 1: diff --git a/src/sage/combinat/root_system/type_C.py b/src/sage/combinat/root_system/type_C.py index 57669883bea..8c7ebce3359 100644 --- a/src/sage/combinat/root_system/type_C.py +++ b/src/sage/combinat/root_system/type_C.py @@ -232,7 +232,7 @@ def dynkin_diagram(self): """ return self.dual().dynkin_diagram().dual() - def _latex_dynkin_diagram(self, label=lambda x: x, node=None, node_dist=2, dual=False): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. @@ -268,9 +268,11 @@ def _latex_dynkin_diagram(self, label=lambda x: x, node=None, node_dist=2, dual= - :meth:`sage.combinat.root_system.type_C.CartanType._latex_dynkin_diagram` - :meth:`sage.combinat.root_system.type_BC_affine.CartanType._latex_dynkin_diagram` """ + if label is None: + label = lambda i: i return self.dual()._latex_dynkin_diagram(label=label, node=node, node_dist=node_dist, dual=not dual) - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Return a ascii art representation of the extended Dynkin diagram. @@ -289,6 +291,8 @@ def ascii_art(self, label=lambda i: i, node=None): O---O---O---O=<=O 3 4 5 6 7 """ + if label is None: + label = lambda i: i return self.dual().ascii_art(label=label, node=node).replace("=>=", "=<=") def _default_folded_cartan_type(self): diff --git a/src/sage/combinat/root_system/type_C_affine.py b/src/sage/combinat/root_system/type_C_affine.py index 72843b4d0a9..adaf5c77562 100644 --- a/src/sage/combinat/root_system/type_C_affine.py +++ b/src/sage/combinat/root_system/type_C_affine.py @@ -76,7 +76,7 @@ def dynkin_diagram(self): g.add_edge(0,1,2) return g - def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual=False): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. @@ -117,6 +117,8 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual= \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$}; """ + if label is None: + label = lambda i: i if node is None: node = self._latex_draw_node if self.n == 1: @@ -134,7 +136,7 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual= ret += "}\n" + node(0, 0, label(0)) return ret - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Return a ascii art representation of the extended Dynkin diagram. @@ -156,6 +158,8 @@ def ascii_art(self, label=lambda i: i, node=None): O<=>O 0 1 """ + if label is None: + label = lambda i: i if node is None: node = self._ascii_art_node n = self.n diff --git a/src/sage/combinat/root_system/type_D.py b/src/sage/combinat/root_system/type_D.py index 28d4cd29cb2..5f1469e48a8 100644 --- a/src/sage/combinat/root_system/type_D.py +++ b/src/sage/combinat/root_system/type_D.py @@ -272,7 +272,7 @@ def dynkin_diagram(self): g.add_edge(n-2, n) return g - def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2): r""" Return a latex representation of the Dynkin diagram. @@ -288,6 +288,8 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): \draw[fill=white] (4 cm, -0.7 cm) circle (.25cm) node[right=3pt]{$3$}; """ + if label is None: + label = lambda i: i if node is None: node = self._latex_draw_node if self.n == 2: @@ -305,7 +307,7 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): ret += node(rt_most, -0.7, label(self.n-1), 'right=3pt') return ret - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Return a ascii art representation of the extended Dynkin diagram. @@ -336,6 +338,8 @@ def ascii_art(self, label=lambda i: i, node=None): O---O---O---O---O 3 4 5 6 7 """ + if label is None: + label = lambda i: i if node is None: node = self._ascii_art_node n = self.n diff --git a/src/sage/combinat/root_system/type_D_affine.py b/src/sage/combinat/root_system/type_D_affine.py index 3ea86f32438..f77204e4a01 100644 --- a/src/sage/combinat/root_system/type_D_affine.py +++ b/src/sage/combinat/root_system/type_D_affine.py @@ -111,7 +111,7 @@ def dynkin_diagram(self): g.add_edge(0,2) return g - def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual=False): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. @@ -130,6 +130,8 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual= \draw[fill=white] (4 cm, -0.7 cm) circle (.25cm) node[right=3pt]{$3$}; """ + if label is None: + label = lambda i: i if node is None: node = self._latex_draw_node n = self.n @@ -152,7 +154,7 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual= ret += node(rt_most, -0.7, label(n-1), "right=3pt") return ret - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Return an ascii art representation of the extended Dynkin diagram. @@ -182,6 +184,8 @@ def ascii_art(self, label=lambda i: i, node=None): O---O---O 5 3 4 """ + if label is None: + label = lambda i: i if node is None: node = self._ascii_art_node n = self.n diff --git a/src/sage/combinat/root_system/type_E.py b/src/sage/combinat/root_system/type_E.py index 478c628a5e9..5771d6d948f 100644 --- a/src/sage/combinat/root_system/type_E.py +++ b/src/sage/combinat/root_system/type_E.py @@ -573,7 +573,7 @@ def dynkin_diagram(self): g.add_edge(i, i+1) return g - def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2): r""" Return a latex representation of the Dynkin diagram. @@ -591,6 +591,8 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): \draw[fill=white] (4 cm, 2 cm) circle (.25cm) node[right=3pt]{$2$}; """ + if label is None: + label = lambda i: i if node is None: node = self._latex_draw_node ret = "\\draw (0 cm,0) -- (%s cm,0);\n" % ((self.n-2)*node_dist) @@ -601,7 +603,7 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): ret += node(2*node_dist, node_dist, label(2), 'right=3pt') return ret - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Return a ascii art representation of the extended Dynkin diagram. @@ -626,6 +628,8 @@ def ascii_art(self, label=lambda i: i, node=None): O---O---O---O---O---O---O 2 4 5 6 7 8 9 """ + if label is None: + label = lambda i: i if node is None: node = self._ascii_art_node labels = [label(i) for i in [1,3,4,5,6] + list(range(7, self.n+1))] # We exclude 2 because of the special case diff --git a/src/sage/combinat/root_system/type_E_affine.py b/src/sage/combinat/root_system/type_E_affine.py index ac64cbfbdde..3268d0603e5 100644 --- a/src/sage/combinat/root_system/type_E_affine.py +++ b/src/sage/combinat/root_system/type_E_affine.py @@ -132,7 +132,7 @@ def dynkin_diagram(self): raise ValueError("Invalid Cartan Type for Type E affine") return g - def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2): r""" Return a latex representation of the Dynkin diagram. @@ -152,6 +152,8 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): """ n = self.n + if label is None: + label = lambda i: i if node is None: node = self._latex_draw_node @@ -181,7 +183,7 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): ret += node(2*node_dist, node_dist, label(2), "right=3pt") return ret - def ascii_art(self, label=lambda x: x, node=None): + def ascii_art(self, label=None, node=None): """ Return an ascii art representation of the extended Dynkin diagram. @@ -210,6 +212,8 @@ def ascii_art(self, label=lambda x: x, node=None): -2 0 1 2 3 4 5 -3 """ n = self.n + if label is None: + label = lambda x: x if node is None: node = self._ascii_art_node if n == 6: diff --git a/src/sage/combinat/root_system/type_F.py b/src/sage/combinat/root_system/type_F.py index ac33d97fbee..524dd1f7c35 100644 --- a/src/sage/combinat/root_system/type_F.py +++ b/src/sage/combinat/root_system/type_F.py @@ -290,7 +290,7 @@ def dynkin_diagram(self): g.set_edge_label(2,3,2) return g - def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual=False): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. @@ -308,6 +308,8 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual= \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; """ + if label is None: + label = lambda i: i if node is None: node = self._latex_draw_node ret = "\\draw (0 cm,0) -- (%s cm,0);\n" % node_dist @@ -322,7 +324,7 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual= ret += node(i*node_dist, 0, label(i+1)) return ret - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Return an ascii art representation of the extended Dynkin diagram. @@ -335,6 +337,8 @@ def ascii_art(self, label=lambda i: i, node=None): O---O=>=O---O -1 0 1 2 """ + if label is None: + label = lambda i: i if node is None: node = self._ascii_art_node ret = "{}---{}=>={}---{}\n".format(node(label(1)), node(label(2)), diff --git a/src/sage/combinat/root_system/type_F_affine.py b/src/sage/combinat/root_system/type_F_affine.py index 403c5b6e8ad..3d2dc8350ee 100644 --- a/src/sage/combinat/root_system/type_F_affine.py +++ b/src/sage/combinat/root_system/type_F_affine.py @@ -72,7 +72,7 @@ def dynkin_diagram(self): g.add_edge(0, 1) return g - def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual=False): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. @@ -95,6 +95,8 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual= \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$}; """ + if label is None: + label = lambda i: i if node is None: node = self._latex_draw_node ret = "\\draw (0 cm,0) -- (%s cm,0);\n" % node_dist @@ -103,7 +105,7 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual= ret += "}\n" + node(0, 0, label(0)) return ret - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Returns a ascii art representation of the extended Dynkin diagram @@ -113,6 +115,8 @@ def ascii_art(self, label=lambda i: i, node=None): O---O---O=>=O---O 2 3 4 5 6 """ + if label is None: + label = lambda i: i if node is None: node = self._ascii_art_node ret = "{}---{}---{}=>={}---{}\n".format(node(label(0)), node(label(1)), diff --git a/src/sage/combinat/root_system/type_G.py b/src/sage/combinat/root_system/type_G.py index 15da57bc11c..21dae3effa7 100644 --- a/src/sage/combinat/root_system/type_G.py +++ b/src/sage/combinat/root_system/type_G.py @@ -200,7 +200,7 @@ def dynkin_diagram(self): g.set_edge_label(2,1,3) return g - def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual=False): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. @@ -215,6 +215,8 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual= \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; """ + if label is None: + label = lambda i: i if node is None: node = self._latex_draw_node ret = "\\draw (0,0) -- (%s cm,0);\n" % node_dist @@ -228,7 +230,7 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual= ret += node(node_dist, 0, label(2)) return ret - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Return an ascii art representation of the Dynkin diagram. @@ -239,6 +241,8 @@ def ascii_art(self, label=lambda i: i, node=None): O=<=O 3 4 """ + if label is None: + label = lambda i: i if node is None: node = self._ascii_art_node ret = " 3\n{}=<={}\n".format(node(label(1)), node(label(2))) diff --git a/src/sage/combinat/root_system/type_G_affine.py b/src/sage/combinat/root_system/type_G_affine.py index 2cb1487dfd8..582f7d9ed03 100644 --- a/src/sage/combinat/root_system/type_G_affine.py +++ b/src/sage/combinat/root_system/type_G_affine.py @@ -70,7 +70,7 @@ def dynkin_diagram(self): g.add_edge(0, 2) return g - def _latex_dynkin_diagram(self, label=lambda x: x, node=None, node_dist=2, dual=False): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. @@ -89,6 +89,8 @@ def _latex_dynkin_diagram(self, label=lambda x: x, node=None, node_dist=2, dual= \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$}; """ + if label is None: + label = lambda x: x if node is None: node = self._latex_draw_node ret = "\\draw (%s cm,0) -- (%s cm,0);\n" % (node_dist, node_dist*2.0) @@ -98,7 +100,7 @@ def _latex_dynkin_diagram(self, label=lambda x: x, node=None, node_dist=2, dual= ret += node(2*node_dist, 0, label(0)) return ret - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Returns an ascii art representation of the Dynkin diagram @@ -109,6 +111,8 @@ def ascii_art(self, label=lambda i: i, node=None): O=<=O---O 3 4 2 """ + if label is None: + label = lambda i: i if node is None: node = self._ascii_art_node ret = " 3\n{}=<={}---{}".format(node(label(1)), node(label(2)), node(label(0))) diff --git a/src/sage/combinat/root_system/type_dual.py b/src/sage/combinat/root_system/type_dual.py index c2ea5d978d3..22c4fb809d4 100644 --- a/src/sage/combinat/root_system/type_dual.py +++ b/src/sage/combinat/root_system/type_dual.py @@ -209,7 +209,7 @@ def __reduce__(self): """ return (attrcall("dual"), (self._type,)) - def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2): r""" EXAMPLES:: @@ -229,11 +229,13 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): } \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$}; """ + if label is None: + label = lambda i: i if node is None: node = self._latex_draw_node return self._type._latex_dynkin_diagram(label, node, node_dist, dual=True) - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Return an ascii art representation of this Cartan type @@ -261,6 +263,8 @@ def ascii_art(self, label=lambda i: i, node=None): O=>=O---O---O=>=O 0 1 2 3 4 """ + if label is None: + label = lambda i: i if node is None: node = self._ascii_art_node res = self._type.ascii_art(label, node) diff --git a/src/sage/combinat/root_system/type_marked.py b/src/sage/combinat/root_system/type_marked.py index 5d80ca1052a..a9ca7d15a35 100644 --- a/src/sage/combinat/root_system/type_marked.py +++ b/src/sage/combinat/root_system/type_marked.py @@ -278,7 +278,7 @@ def _latex_draw_mark(self, x, y, color='black', thickness='thin'): ret += "\\draw[shift={{({}, {})}}, {}, {}] (0.25cm, -0.25cm) -- (-0.25cm, 0.25cm);\n".format(x, y, color, thickness) return ret - def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2): r""" Return a latex representation of the Dynkin diagram. @@ -296,11 +296,13 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; """ + if label is None: + label = lambda i: i if node is None: node = self._latex_draw_node return self._type._latex_dynkin_diagram(label, node, node_dist) - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Return an ascii art representation of this Cartan type. @@ -320,6 +322,8 @@ def ascii_art(self, label=lambda i: i, node=None): X---O---X=>=O---O 0 1 2 3 4 """ + if label is None: + label = lambda i: i if node is None: node = self._ascii_art_node return self._type.ascii_art(label, node) diff --git a/src/sage/combinat/root_system/type_reducible.py b/src/sage/combinat/root_system/type_reducible.py index 0f84b3f3b90..46cdccd2ab4 100644 --- a/src/sage/combinat/root_system/type_reducible.py +++ b/src/sage/combinat/root_system/type_reducible.py @@ -308,7 +308,7 @@ def dynkin_diagram(self): g.add_edge(relabelling[i,e1], relabelling[i,e2], label=l) return g - def _latex_dynkin_diagram(self, label=lambda x: x, node=None, node_dist=2): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2): r""" Return a latex representation of the Dynkin diagram. @@ -332,6 +332,8 @@ def _latex_dynkin_diagram(self, label=lambda x: x, node=None, node_dist=2): \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; } """ + if label is None: + label = lambda x: x types = self.component_types() relabelling = self._index_relabelling ret = "{\n" @@ -341,7 +343,7 @@ def _latex_dynkin_diagram(self, label=lambda x: x, node=None, node_dist=2): ret += "}" return ret - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Return an ascii art representation of this reducible Cartan type. @@ -367,6 +369,8 @@ def ascii_art(self, label=lambda i: i, node=None): O---O=<=O 11 12 13 """ + if label is None: + label = lambda i: i types = self.component_types() relabelling = self._index_relabelling return "\n".join(types[i].ascii_art(lambda x: label(relabelling[i,x]), node) diff --git a/src/sage/combinat/root_system/type_relabel.py b/src/sage/combinat/root_system/type_relabel.py index 142ddeffa45..350e290b32a 100644 --- a/src/sage/combinat/root_system/type_relabel.py +++ b/src/sage/combinat/root_system/type_relabel.py @@ -55,7 +55,7 @@ def __classcall__(cls, type, relabelling): return type relabelling = FiniteFamily(relabelling) # Hack to emulate a frozendict which would be hashable!!!! - return super(CartanType, cls).__classcall__(cls, type, relabelling) + return super().__classcall__(cls, type, relabelling) def __init__(self, type, relabelling): """ @@ -271,7 +271,7 @@ def _latex_(self): ret += " \\text{ relabelled by } " + latex(self._relabelling) return ret - def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2): r""" Return a latex representation of the Dynkin diagram. @@ -285,9 +285,11 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; """ + if label is None: + label = lambda i: i return self._type._latex_dynkin_diagram(lambda i: label(self._relabelling[i]), node, node_dist) - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Return an ascii art representation of this Cartan type. @@ -307,6 +309,8 @@ def ascii_art(self, label=lambda i: i, node=None): O---O---O=>=O---O 4 3 2 1 0 """ + if label is None: + label = lambda i: i if node is None: node = self._ascii_art_node return self._type.ascii_art(lambda i: label(self._relabelling[i]), node) diff --git a/src/sage/combinat/root_system/type_super_A.py b/src/sage/combinat/root_system/type_super_A.py index dedc56b9011..c2717a572ff 100644 --- a/src/sage/combinat/root_system/type_super_A.py +++ b/src/sage/combinat/root_system/type_super_A.py @@ -737,7 +737,7 @@ def _latex_draw_node(self, x, y, label, position="below=4pt"): x+.17, y-.17, x-.17, y+.17) return ret - def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): + def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2): r""" Return a latex representation of the Dynkin diagram. @@ -775,6 +775,8 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): \draw[-,thick] (0.17 cm, 0.17 cm) -- (-0.17 cm, -0.17 cm); \draw[-,thick] (0.17 cm, -0.17 cm) -- (-0.17 cm, 0.17 cm); """ + if label is None: + label = lambda i: i if node is None: node = self._latex_draw_node if self.n + self.m > 1: @@ -784,7 +786,7 @@ def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): return ret + "".join(node((self.m+i)*node_dist, 0, label(i)) for i in self.index_set()) - def ascii_art(self, label=lambda i: i, node=None): + def ascii_art(self, label=None, node=None): """ Return an ascii art representation of the Dynkin diagram. @@ -812,6 +814,8 @@ def ascii_art(self, label=lambda i: i, node=None): O---O---O---O---O---X -5 -4 -3 -2 -1 0 """ + if label is None: + label = lambda i: i if node is None: node = lambda i: 'O' ret = "---".join(node(label(i)) for i in range(1,self.m+1)) diff --git a/src/sage/combinat/set_partition_iterator.pyx b/src/sage/combinat/set_partition_iterator.pyx index fff6a71fefe..47667561a71 100644 --- a/src/sage/combinat/set_partition_iterator.pyx +++ b/src/sage/combinat/set_partition_iterator.pyx @@ -7,7 +7,7 @@ cimport cython @cython.wraparound(False) @cython.boundscheck(False) -cdef list from_word(list w, list base_set): +cdef list from_word(list w, list base_set) noexcept: cdef list sp = [] cdef Py_ssize_t i cdef Py_ssize_t b @@ -20,6 +20,7 @@ cdef list from_word(list w, list base_set): sp[b].append(x) return sp + @cython.wraparound(False) @cython.boundscheck(False) def set_partition_iterator(base_set): @@ -74,6 +75,7 @@ def set_partition_iterator(base_set): # H3: increase a_{n-1} a[last] += 1 + @cython.wraparound(False) @cython.boundscheck(False) def _set_partition_block_gen(Py_ssize_t n, Py_ssize_t k, list a): @@ -108,6 +110,7 @@ def _set_partition_block_gen(Py_ssize_t n, Py_ssize_t k, list a): yield P a[n-1] = n-1 + @cython.wraparound(False) @cython.boundscheck(False) def set_partition_iterator_blocks(base_set, Py_ssize_t k): diff --git a/src/sage/combinat/species/cycle_species.py b/src/sage/combinat/species/cycle_species.py index 335223143ed..ed442e75ba9 100644 --- a/src/sage/combinat/species/cycle_species.py +++ b/src/sage/combinat/species/cycle_species.py @@ -113,7 +113,7 @@ def __classcall__(cls, *args, **kwds): sage: C = species.CycleSpecies(); C Cyclic permutation species """ - return super(CycleSpecies, cls).__classcall__(cls, *args, **kwds) + return super().__classcall__(cls, *args, **kwds) def __init__(self, min=None, max=None, weight=None): """ diff --git a/src/sage/combinat/species/linear_order_species.py b/src/sage/combinat/species/linear_order_species.py index a62fde28fb5..6203442ec8f 100644 --- a/src/sage/combinat/species/linear_order_species.py +++ b/src/sage/combinat/species/linear_order_species.py @@ -77,7 +77,7 @@ def __classcall__(cls, *args, **kwds): sage: L = species.LinearOrderSpecies(); L Linear order species """ - return super(LinearOrderSpecies, cls).__classcall__(cls, *args, **kwds) + return super().__classcall__(cls, *args, **kwds) def __init__(self, min=None, max=None, weight=None): """ diff --git a/src/sage/combinat/species/partition_species.py b/src/sage/combinat/species/partition_species.py index 3ed00b45ca4..f9044db7c73 100644 --- a/src/sage/combinat/species/partition_species.py +++ b/src/sage/combinat/species/partition_species.py @@ -142,7 +142,7 @@ def __classcall__(cls, *args, **kwds): sage: P = species.PartitionSpecies(); P Partition species """ - return super(PartitionSpecies, cls).__classcall__(cls, *args, **kwds) + return super().__classcall__(cls, *args, **kwds) def __init__(self, min=None, max=None, weight=None): """ diff --git a/src/sage/combinat/species/permutation_species.py b/src/sage/combinat/species/permutation_species.py index 4549e0354ff..64534c9e8bb 100644 --- a/src/sage/combinat/species/permutation_species.py +++ b/src/sage/combinat/species/permutation_species.py @@ -115,7 +115,7 @@ def __classcall__(cls, *args, **kwds): sage: P = species.PermutationSpecies(); P Permutation species """ - return super(PermutationSpecies, cls).__classcall__(cls, *args, **kwds) + return super().__classcall__(cls, *args, **kwds) def __init__(self, min=None, max=None, weight=None): """ diff --git a/src/sage/combinat/species/set_species.py b/src/sage/combinat/species/set_species.py index c4942dc653d..daa7d7e5835 100644 --- a/src/sage/combinat/species/set_species.py +++ b/src/sage/combinat/species/set_species.py @@ -91,7 +91,7 @@ def __classcall__(cls, *args, **kwds): sage: E = species.SetSpecies(); E Set species """ - return super(SetSpecies, cls).__classcall__(cls, *args, **kwds) + return super().__classcall__(cls, *args, **kwds) def __init__(self, min=None, max=None, weight=None): """ diff --git a/src/sage/combinat/species/subset_species.py b/src/sage/combinat/species/subset_species.py index 2bd89885533..81156e5183d 100644 --- a/src/sage/combinat/species/subset_species.py +++ b/src/sage/combinat/species/subset_species.py @@ -134,7 +134,7 @@ def __classcall__(cls, *args, **kwds): sage: S = species.SubsetSpecies(); S Subset species """ - return super(SubsetSpecies, cls).__classcall__(cls, *args, **kwds) + return super().__classcall__(cls, *args, **kwds) def __init__(self, min=None, max=None, weight=None): """ diff --git a/src/sage/combinat/subword_complex_c.pyx b/src/sage/combinat/subword_complex_c.pyx index 66da5184356..ec85790c133 100644 --- a/src/sage/combinat/subword_complex_c.pyx +++ b/src/sage/combinat/subword_complex_c.pyx @@ -1,7 +1,7 @@ # sage.doctest: needs sage.modules cpdef int _flip_c(W, set positions, list extended_root_conf_indices, - int i, side="both"): + int i, side="both") noexcept: r""" Flip a facet. @@ -57,10 +57,10 @@ cpdef int _flip_c(W, set positions, list extended_root_conf_indices, if j != i: t = R[min(r, r_minus)] for k in range(min(i, j) + 1, max(i, j) + 1): - extended_root_conf_indices[k] = t.action_on_root_indices(extended_root_conf_indices[k],side="left") + extended_root_conf_indices[k] = t.action_on_root_indices(extended_root_conf_indices[k], side="left") return j -cpdef list _construct_facets_c(tuple Q, w, int n=-1, int pos=0, int l=-1): +cpdef list _construct_facets_c(tuple Q, w, int n=-1, int pos=0, int l=-1) noexcept: r""" Return the list of facets of the subword complex associated to the word `Q` and the element `w` in a Coxeter group `W`. diff --git a/src/sage/combinat/tableau.py b/src/sage/combinat/tableau.py index 2103cb810a7..f7e58a15c20 100644 --- a/src/sage/combinat/tableau.py +++ b/src/sage/combinat/tableau.py @@ -9440,8 +9440,7 @@ def __iter__(self): for (r, c) in growth_choice: new_tab[r][c] = growth_num list_of_partial_inc_tabs.append(Tableau(new_tab)) - for inctab in list_of_inc_tabs: - yield inctab + yield from list_of_inc_tabs class IncreasingTableaux_size_weight(IncreasingTableaux): diff --git a/src/sage/combinat/words/abstract_word.py b/src/sage/combinat/words/abstract_word.py index 77174089f78..610dba1437a 100644 --- a/src/sage/combinat/words/abstract_word.py +++ b/src/sage/combinat/words/abstract_word.py @@ -900,8 +900,7 @@ def _iterated_right_palindromic_closure_iterator(self, f=None): w = (w*par([letter])).palindromic_closure(f=f) length_after = w.length() d = length_after - length_before - for a in w[-d:]: - yield a + yield from w[-d:] def _iterated_right_palindromic_closure_recursive_iterator(self, f=None): r""" @@ -991,8 +990,7 @@ def _iterated_right_palindromic_closure_recursive_iterator(self, f=None): else: to_append = ipcw[lengths[pos]:] ipcw += to_append - for a in to_append: - yield a + yield from to_append def iterated_right_palindromic_closure(self, f=None, algorithm='recursive'): r""" diff --git a/src/sage/combinat/words/word_char.pyx b/src/sage/combinat/words/word_char.pyx index 433aae3f4db..f2b7b47edb2 100644 --- a/src/sage/combinat/words/word_char.pyx +++ b/src/sage/combinat/words/word_char.pyx @@ -1,15 +1,15 @@ r""" Fast word datatype using an array of unsigned char """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2014 Vincent Delecroix <20100.delecroix@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. -# http://www.gnu.org/licenses/ -#***************************************************************************** +# https://www.gnu.org/licenses/ +# **************************************************************************** from cysignals.memory cimport check_allocarray, sig_free from cysignals.signals cimport sig_on, sig_off @@ -98,9 +98,9 @@ cdef class WordDatatype_char(WordDatatype): if data: self._set_data(data) - @cython.boundscheck(False) # assume that indexing will not cause any IndexErrors + @cython.boundscheck(False) # assume that indexing will not cause any IndexErrors @cython.wraparound(False) # not check not correctly handle negative indices - cdef _set_data(self, data): + cdef _set_data(self, data) noexcept: r""" set the attribute ._data and ._length from the sequence data (usually data is a word, a tuple or a list) @@ -196,7 +196,7 @@ cdef class WordDatatype_char(WordDatatype): [1, 3, 2] """ cdef bitset_t seen - bitset_init(seen, 256) # allocation + initialization to 0 + bitset_init(seen, 256) # allocation + initialization to 0 cdef size_t i cdef list res = [] @@ -209,7 +209,7 @@ cdef class WordDatatype_char(WordDatatype): bitset_free(seen) return res - cdef _new_c(self, unsigned char * data, size_t length, WordDatatype_char master): + cdef _new_c(self, unsigned char * data, size_t length, WordDatatype_char master) noexcept: r""" TO DISCUSS: in Integer (sage.rings.integer) this method is actually an external function. But we might want to have several possible inheritance. @@ -217,7 +217,7 @@ cdef class WordDatatype_char(WordDatatype): cdef type t = type(self) cdef WordDatatype_char other = t.__new__(t) other._data = data - other._master = master # can be None + other._master = master # can be None other._is_slice = 0 if master is None else 1 other._length = length other._parent = self._parent @@ -367,9 +367,9 @@ cdef class WordDatatype_char(WordDatatype): if isinstance(key, slice): # here the key is a slice PySlice_GetIndicesEx(key, - self._length, - &start, &stop, &step, - &slicelength) + self._length, + &start, &stop, &step, + &slicelength) if slicelength == 0: return self._new_c(NULL, 0, None) if step == 1: @@ -425,7 +425,7 @@ cdef class WordDatatype_char(WordDatatype): """ return reversed_word_iterator(self) - cdef _concatenate(self, WordDatatype_char other): + cdef _concatenate(self, WordDatatype_char other) noexcept: cdef unsigned char * data data = check_allocarray(self._length + other._length, sizeof(unsigned char)) diff --git a/src/sage/combinat/words/word_datatypes.pyx b/src/sage/combinat/words/word_datatypes.pyx index 57c8079aad6..daf21a97469 100644 --- a/src/sage/combinat/words/word_datatypes.pyx +++ b/src/sage/combinat/words/word_datatypes.pyx @@ -1,7 +1,7 @@ r""" Datatypes for finite words """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2009 Franco Saliola # Vincent Delecroix <20100.delecroix@gmail.com> # @@ -9,8 +9,8 @@ Datatypes for finite words # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. -# http://www.gnu.org/licenses/ -#***************************************************************************** +# https://www.gnu.org/licenses/ +# **************************************************************************** from cpython.object cimport Py_EQ, Py_NE from itertools import islice @@ -20,10 +20,10 @@ cdef class WordDatatype(): r""" The generic WordDatatype class. - Any word datatype must contain two attributes (at least):: + Any word datatype must contain two attributes (at least): - - _parent - - _hash + - ``_parent`` + - ``_hash`` They are automatically defined here and it's not necessary (and forbidden) to define them anywhere else. @@ -419,7 +419,7 @@ cdef class WordDatatype_str(WordDatatype): else: return a in self._data - cpdef _has_factor_naive(self, w): + cpdef _has_factor_naive(self, w) noexcept: r""" A naive test for testing whether the word contains ``w`` as a factor. @@ -449,7 +449,7 @@ cdef class WordDatatype_str(WordDatatype): return w in self._data raise ValueError - cpdef find(self, sub, start=0, end=None): + cpdef find(self, sub, start=0, end=None) noexcept: r""" Returns the index of the first occurrence of sub in self, such that sub is contained within self[start:end]. diff --git a/src/sage/combinat/words/word_generators.py b/src/sage/combinat/words/word_generators.py index 06141373c85..d7093ae997c 100644 --- a/src/sage/combinat/words/word_generators.py +++ b/src/sage/combinat/words/word_generators.py @@ -1651,8 +1651,7 @@ def _s_adic_iterator(self, sequence, letters): if not precedent_letter == m(a)[0]: raise ValueError("the hypothesis of the algorithm used is not satisfied; the image of the %s-th letter (=%s) under the %s-th morphism (=%s) should start with the %s-th letter (=%s)" % (i+1,a,i+1,m,i,precedent_letter)) w = p(m(a)[1:]) - for b in w: - yield b + yield from w p = p * m precedent_letter = a diff --git a/src/sage/combinat/words/words.py b/src/sage/combinat/words/words.py index 900ab9c8508..63d6f1f0d05 100644 --- a/src/sage/combinat/words/words.py +++ b/src/sage/combinat/words/words.py @@ -960,8 +960,7 @@ def __iter__(self): word: 444 """ for l in itertools.count(): - for w in self.iterate_by_length(l): - yield w + yield from self.iterate_by_length(l) def __contains__(self, x): """ diff --git a/src/sage/cpython/_py2_random.py b/src/sage/cpython/_py2_random.py index 1cd9532fee4..3ba96ccbbd1 100644 --- a/src/sage/cpython/_py2_random.py +++ b/src/sage/cpython/_py2_random.py @@ -92,19 +92,19 @@ def seed(self, a=None): import time a = int(time.time() * 256) # use fractional seconds - super(Random, self).seed(a) + super().seed(a) self.gauss_next = None def getstate(self): """Return internal state; can be passed to setstate() later.""" - return self.VERSION, super(Random, self).getstate(), self.gauss_next + return self.VERSION, super().getstate(), self.gauss_next def setstate(self, state): """Restore internal state from object returned by getstate().""" version = state[0] if version == 3: version, internalstate, self.gauss_next = state - super(Random, self).setstate(internalstate) + super().setstate(internalstate) elif version == 2: version, internalstate, self.gauss_next = state # In version 2, the state was saved as signed ints, which causes @@ -115,7 +115,7 @@ def setstate(self, state): internalstate = tuple( int(x) % (2**32) for x in internalstate ) except ValueError as e: raise TypeError(e) - super(Random, self).setstate(internalstate) + super().setstate(internalstate) else: raise ValueError("state with version %s passed to " "Random.setstate() of version %s" % @@ -131,7 +131,7 @@ def jumpahead(self, n): # we use hashing to create a large n for the shuffle. s = repr(n) + repr(self.getstate()) n = int(_hashlib.new('sha512', s).hexdigest(), 16) - super(Random, self).jumpahead(n) + super().jumpahead(n) ## ---- Methods below this point do not need to be overridden when ## ---- subclassing for the purpose of using a different core generator. diff --git a/src/sage/cpython/getattr.pxd b/src/sage/cpython/getattr.pxd index e0987cfa4c5..299509a00dc 100644 --- a/src/sage/cpython/getattr.pxd +++ b/src/sage/cpython/getattr.pxd @@ -5,4 +5,4 @@ cdef class AttributeErrorMessage: cdef public cls cdef public name -cpdef getattr_from_other_class(self, cls, name) +cpdef getattr_from_other_class(self, cls, name) noexcept diff --git a/src/sage/cpython/getattr.pyx b/src/sage/cpython/getattr.pyx index 1f49e5230c3..3a06167ea99 100644 --- a/src/sage/cpython/getattr.pyx +++ b/src/sage/cpython/getattr.pyx @@ -111,7 +111,7 @@ cdef class AttributeErrorMessage: cdef AttributeErrorMessage dummy_error_message = AttributeErrorMessage() -cpdef raw_getattr(obj, name): +cpdef raw_getattr(obj, name) noexcept: """ Like ``getattr(obj, name)`` but without invoking the binding behavior of descriptors under normal attribute access. @@ -227,7 +227,7 @@ cpdef raw_getattr(obj, name): raise AttributeError(dummy_error_message) -cpdef getattr_from_other_class(self, cls, name): +cpdef getattr_from_other_class(self, cls, name) noexcept: """ Emulate ``getattr(self, name)``, as if ``self`` was an instance of ``cls``. diff --git a/src/sage/cpython/string.pxd b/src/sage/cpython/string.pxd index 1fde0aec0de..dbf1c91c08b 100644 --- a/src/sage/cpython/string.pxd +++ b/src/sage/cpython/string.pxd @@ -13,7 +13,7 @@ cdef extern from "string_impl.h": bytes _str_to_bytes(s, encoding, errors) -cdef inline str char_to_str(const char* c, encoding=None, errors=None): +cdef inline str char_to_str(const char* c, encoding=None, errors=None) noexcept: r""" Convert a C string to a Python ``str``. """ @@ -23,7 +23,7 @@ cdef inline str char_to_str(const char* c, encoding=None, errors=None): return _cstr_to_str(c, encoding, errors) -cpdef inline str bytes_to_str(b, encoding=None, errors=None): +cpdef inline str bytes_to_str(b, encoding=None, errors=None) noexcept: r""" Convert ``bytes`` to ``str``. @@ -49,7 +49,7 @@ cpdef inline str bytes_to_str(b, encoding=None, errors=None): return _cstr_to_str(b, encoding, errors) -cpdef inline bytes str_to_bytes(s, encoding=None, errors=None): +cpdef inline bytes str_to_bytes(s, encoding=None, errors=None) noexcept: r""" Convert ``str`` or ``unicode`` to ``bytes``. diff --git a/src/sage/cpython/type.pxd b/src/sage/cpython/type.pxd index adb13dce6aa..f3f80c7a6c6 100644 --- a/src/sage/cpython/type.pxd +++ b/src/sage/cpython/type.pxd @@ -1 +1 @@ -cpdef bint can_assign_class(obj) +cpdef bint can_assign_class(obj) noexcept diff --git a/src/sage/cpython/type.pyx b/src/sage/cpython/type.pyx index 8106c99f6ab..f9dcabc5df4 100644 --- a/src/sage/cpython/type.pyx +++ b/src/sage/cpython/type.pyx @@ -12,7 +12,7 @@ except ImportError: pass -cpdef bint can_assign_class(obj): +cpdef bint can_assign_class(obj) noexcept: """ Can we assign ``obj.__class__``? diff --git a/src/sage/cpython/wrapperdescr.pxd b/src/sage/cpython/wrapperdescr.pxd index b6775860710..2260c062f1f 100644 --- a/src/sage/cpython/wrapperdescr.pxd +++ b/src/sage/cpython/wrapperdescr.pxd @@ -24,7 +24,7 @@ cdef extern from *: PyDescr_NewWrapper(PyTypeObject* cls, wrapperbase* wrapper, void* wrapped) -cdef wrapperdescr_fastcall(wrapper_descriptor slotwrapper, self, args, kwds) +cdef wrapperdescr_fastcall(wrapper_descriptor slotwrapper, self, args, kwds) noexcept cdef inline wrapperbase* get_slotdef(wrapper_descriptor slotwrapper) except NULL: diff --git a/src/sage/cpython/wrapperdescr.pyx b/src/sage/cpython/wrapperdescr.pyx index 66c79ca38e2..108ca690b8d 100644 --- a/src/sage/cpython/wrapperdescr.pyx +++ b/src/sage/cpython/wrapperdescr.pyx @@ -87,7 +87,7 @@ def wrapperdescr_call(slotwrapper, self, *args, **kwds): return wrapperdescr_fastcall(slotwrapper, self, args, kwds) -cdef wrapperdescr_fastcall(wrapper_descriptor slotwrapper, self, args, kwds): +cdef wrapperdescr_fastcall(wrapper_descriptor slotwrapper, self, args, kwds) noexcept: # Cython implementation of wrapperdescr_call cdef wrapperbase* slotdef = slotwrapper.d_base diff --git a/src/sage/crypto/boolean_function.pxd b/src/sage/crypto/boolean_function.pxd index 8a97eb875aa..d9fd1017fcd 100644 --- a/src/sage/crypto/boolean_function.pxd +++ b/src/sage/crypto/boolean_function.pxd @@ -1,4 +1,4 @@ -cdef inline unsigned int hamming_weight(unsigned int x): +cdef inline unsigned int hamming_weight(unsigned int x) noexcept: # valid for 32bits x -= (x>>1) & 0x55555555UL # 0-2 in 2 bits x = ((x>>2) & 0x33333333UL) + (x & 0x33333333UL) # 0-4 in 4 bits @@ -6,4 +6,4 @@ cdef inline unsigned int hamming_weight(unsigned int x): x *= 0x01010101UL return x>>24 -cdef walsh_hadamard(long *f, int ldn) +cdef walsh_hadamard(long *f, int ldn) noexcept diff --git a/src/sage/crypto/boolean_function.pyx b/src/sage/crypto/boolean_function.pyx index fa99fab5ea3..6190129278f 100644 --- a/src/sage/crypto/boolean_function.pyx +++ b/src/sage/crypto/boolean_function.pyx @@ -51,7 +51,7 @@ except ImportError: # walsh_hadamard transform, reed_muller transform, and a lot # more, see 'Matters computational' available on www.jjj.de. -cdef walsh_hadamard(long *f, int ldn): +cdef walsh_hadamard(long *f, int ldn) noexcept: r""" The Walsh Hadamard transform is an orthogonal transform equivalent to a multidimensional discrete Fourier transform of size 2x2x...x2. @@ -84,7 +84,7 @@ cdef walsh_hadamard(long *f, int ldn): t1 += 1 t2 += 1 -cdef long yellow_code(unsigned long a): +cdef long yellow_code(unsigned long a) noexcept: """ The yellow-code is just a Reed Muller transform applied to a word. @@ -109,7 +109,7 @@ cdef long yellow_code(unsigned long a): m ^= (m<`. It is a symmetric key cipher so @@ -27,22 +29,21 @@ class of | + VigenereCryptosystem + PublicKeyCryptosystem """ - -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2007 David Kohel # # Distributed under the terms of the GNU General Public License (GPL) # -# http://www.gnu.org/licenses/ -#***************************************************************************** - -import sage.structure.parent_old as parent_old +# https://www.gnu.org/licenses/ +# **************************************************************************** from sage.sets.set import Set_generic -class Cryptosystem(parent_old.Parent, Set_generic): + +class Cryptosystem(Set_generic): r""" A base cryptosystem class. This is meant to be extended by other specialized child classes that implement specific cryptosystems. + A cryptosystem is a pair of maps .. MATH:: @@ -143,7 +144,9 @@ def __init__(self, plaintext_space, ciphertext_space, key_space, def __eq__(self, right): r""" - Comparing ``self`` with ``right``. Two ``Cryptosystem`` objects + Comparing ``self`` with ``right``. + + Two ``Cryptosystem`` objects are the same if they satisfy all of these conditions: - share the same type @@ -323,7 +326,9 @@ def key_space(self): def block_length(self): r""" - Return the block length of this cryptosystem. For some cryptosystems + Return the block length of this cryptosystem. + + For some cryptosystems this is not relevant, in which case the block length defaults to 1. EXAMPLES: @@ -348,6 +353,7 @@ def period(self): raise TypeError("Argument has no associated period.") return self._period + class SymmetricKeyCryptosystem(Cryptosystem): r""" The base class for symmetric key, or secret key, cryptosystems. @@ -373,6 +379,7 @@ def alphabet_size(self): """ return self._cipher_domain.ngens() + class PublicKeyCryptosystem(Cryptosystem): r""" The base class for asymmetric or public-key cryptosystems. diff --git a/src/sage/crypto/sbox.pyx b/src/sage/crypto/sbox.pyx index e66cb52186c..a08eacb4740 100644 --- a/src/sage/crypto/sbox.pyx +++ b/src/sage/crypto/sbox.pyx @@ -25,7 +25,7 @@ from sage.rings.integer cimport Integer from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing -cdef Py_ssize_t _nterms(Py_ssize_t nvars, Py_ssize_t deg): +cdef Py_ssize_t _nterms(Py_ssize_t nvars, Py_ssize_t deg) noexcept: """ Return the number of monomials possible up to a given degree. @@ -268,7 +268,7 @@ cdef class SBox(SageObject): """ return not self.__eq__(other) - cpdef list to_bits(self, x, n=None): + cpdef list to_bits(self, x, n=None) noexcept: """ Return bitstring of length ``n`` for integer ``x``. The returned bitstring is guaranteed to have length ``n``. @@ -333,7 +333,7 @@ cdef class SBox(SageObject): return ZZ(self._rpad(x, n), 2) - cdef list _rpad(self, list x, Py_ssize_t n=-1): + cdef list _rpad(self, list x, Py_ssize_t n=-1) noexcept: """ Right pads ``x`` such that ``len(x) == n``. @@ -1920,7 +1920,7 @@ cdef class SBox(SageObject): return self == self.inverse() -cdef Py_ssize_t feistel_substitute(Py_ssize_t x, Py_ssize_t input_size, list sboxes): +cdef Py_ssize_t feistel_substitute(Py_ssize_t x, Py_ssize_t input_size, list sboxes) noexcept: """ Compute a Feistel output using the given sboxes. @@ -1947,7 +1947,7 @@ cdef Py_ssize_t feistel_substitute(Py_ssize_t x, Py_ssize_t input_size, list sbo return (xl << input_size) | xr -cdef Py_ssize_t misty_substitute(Py_ssize_t x, Py_ssize_t input_size, list sboxes): +cdef Py_ssize_t misty_substitute(Py_ssize_t x, Py_ssize_t input_size, list sboxes) noexcept: """ Compute a Misty output using the given sboxes. @@ -1974,10 +1974,10 @@ cdef Py_ssize_t misty_substitute(Py_ssize_t x, Py_ssize_t input_size, list sboxe return (xl << input_size) | xr -ctypedef Py_ssize_t (*_SBOX_CONSTR) (Py_ssize_t, Py_ssize_t, list) +ctypedef Py_ssize_t (*_SBOX_CONSTR) (Py_ssize_t, Py_ssize_t, list) noexcept -cdef sbox_construction(_SBOX_CONSTR construction, list args): +cdef sbox_construction(_SBOX_CONSTR construction, list args) noexcept: """ Construct an Sbox from the given input sboxes that has a twice as big input size. diff --git a/src/sage/data_structures/binary_matrix.pxd b/src/sage/data_structures/binary_matrix.pxd index b2e4f2fa03f..848489e7697 100644 --- a/src/sage/data_structures/binary_matrix.pxd +++ b/src/sage/data_structures/binary_matrix.pxd @@ -61,7 +61,7 @@ cdef inline int binary_matrix_realloc(binary_matrix_t m, mp_bitcnt_t n_rows, mp_ m.n_cols = n_cols m.n_rows = n_rows -cdef inline void binary_matrix_free(binary_matrix_t m): +cdef inline void binary_matrix_free(binary_matrix_t m) noexcept: r""" Free the memory allocated by the matrix """ @@ -71,7 +71,7 @@ cdef inline void binary_matrix_free(binary_matrix_t m): bitset_free(m.rows[i]) sig_free(m.rows) -cdef inline void binary_matrix_copy(binary_matrix_t dst, binary_matrix_t src): +cdef inline void binary_matrix_copy(binary_matrix_t dst, binary_matrix_t src) noexcept: """ Copy the binary matrix src over to the binary matrix dst, overwriting dst. @@ -81,7 +81,7 @@ cdef inline void binary_matrix_copy(binary_matrix_t dst, binary_matrix_t src): for i in range(dst.n_rows): bitset_copy(dst.rows[i], src.rows[i]) -cdef inline void binary_matrix_fill(binary_matrix_t m, bint bit): +cdef inline void binary_matrix_fill(binary_matrix_t m, bint bit) noexcept: r""" Fill the whole matrix with a bit """ @@ -94,7 +94,7 @@ cdef inline void binary_matrix_fill(binary_matrix_t m, bint bit): for i in range(m.n_rows): bitset_clear(m.rows[i]) -cdef inline void binary_matrix_complement(binary_matrix_t m): +cdef inline void binary_matrix_complement(binary_matrix_t m) noexcept: r""" Complement all of the matrix' bits. """ @@ -102,31 +102,31 @@ cdef inline void binary_matrix_complement(binary_matrix_t m): for i in range(m.n_rows): bitset_complement(m.rows[i], m.rows[i]) -cdef inline void binary_matrix_set1(binary_matrix_t m, mp_bitcnt_t row, mp_bitcnt_t col): +cdef inline void binary_matrix_set1(binary_matrix_t m, mp_bitcnt_t row, mp_bitcnt_t col) noexcept: r""" Set an entry to 1 """ bitset_add(m.rows[row], col) -cdef inline void binary_matrix_set0(binary_matrix_t m, mp_bitcnt_t row, mp_bitcnt_t col): +cdef inline void binary_matrix_set0(binary_matrix_t m, mp_bitcnt_t row, mp_bitcnt_t col) noexcept: r""" Set an entry to 0 """ bitset_discard(m.rows[row], col) -cdef inline void binary_matrix_set(binary_matrix_t m, mp_bitcnt_t row, mp_bitcnt_t col, bint value): +cdef inline void binary_matrix_set(binary_matrix_t m, mp_bitcnt_t row, mp_bitcnt_t col, bint value) noexcept: r""" Set an entry """ bitset_set_to(m.rows[row],col,value) -cdef inline bint binary_matrix_get(binary_matrix_t m, mp_bitcnt_t row, mp_bitcnt_t col): +cdef inline bint binary_matrix_get(binary_matrix_t m, mp_bitcnt_t row, mp_bitcnt_t col) noexcept: r""" Return the value of a given entry """ return bitset_in(m.rows[row], col) -cdef inline binary_matrix_print(binary_matrix_t m): +cdef inline binary_matrix_print(binary_matrix_t m) noexcept: r""" Print the binary matrix """ diff --git a/src/sage/data_structures/binary_search.pxd b/src/sage/data_structures/binary_search.pxd index 640857720ae..5eee088e8b8 100644 --- a/src/sage/data_structures/binary_search.pxd +++ b/src/sage/data_structures/binary_search.pxd @@ -1,2 +1,2 @@ -cdef Py_ssize_t binary_search(Py_ssize_t* v, Py_ssize_t n, Py_ssize_t x, Py_ssize_t* ins) -cdef Py_ssize_t binary_search0(Py_ssize_t* v, Py_ssize_t n, Py_ssize_t x) \ No newline at end of file +cdef Py_ssize_t binary_search(Py_ssize_t* v, Py_ssize_t n, Py_ssize_t x, Py_ssize_t* ins) noexcept +cdef Py_ssize_t binary_search0(Py_ssize_t* v, Py_ssize_t n, Py_ssize_t x) noexcept \ No newline at end of file diff --git a/src/sage/data_structures/binary_search.pyx b/src/sage/data_structures/binary_search.pyx index a53061c3efb..173affa5687 100644 --- a/src/sage/data_structures/binary_search.pyx +++ b/src/sage/data_structures/binary_search.pyx @@ -1,6 +1,6 @@ # We can probably get away with only having the mpz_binary_searches in here. # I'm too scared to get rid of it at 2am though. -cdef Py_ssize_t binary_search(Py_ssize_t* v, Py_ssize_t n, Py_ssize_t x, Py_ssize_t* ins): +cdef Py_ssize_t binary_search(Py_ssize_t* v, Py_ssize_t n, Py_ssize_t x, Py_ssize_t* ins) noexcept: """ Find the position of the integer x in the array v, which has length n. @@ -38,7 +38,7 @@ cdef Py_ssize_t binary_search(Py_ssize_t* v, Py_ssize_t n, Py_ssize_t x, Py_ssiz return -1 -cdef Py_ssize_t binary_search0(Py_ssize_t* v, Py_ssize_t n, Py_ssize_t x): +cdef Py_ssize_t binary_search0(Py_ssize_t* v, Py_ssize_t n, Py_ssize_t x) noexcept: """ Find the position of the int x in the array v, which has length n. diff --git a/src/sage/data_structures/bitset.pxd b/src/sage/data_structures/bitset.pxd index 08394ffcf5f..d8122c05165 100644 --- a/src/sage/data_structures/bitset.pxd +++ b/src/sage/data_structures/bitset.pxd @@ -12,29 +12,29 @@ from .bitset_base cimport bitset_t # Python layer over bitset_t cdef class FrozenBitset: cdef bitset_t _bitset - cdef FrozenBitset _new(self,long int capacity) - cpdef FrozenBitset _larger_capacity_(self, long size) - cpdef long capacity(self) - cpdef bint isempty(self) + cdef FrozenBitset _new(self,long int capacity) noexcept + cpdef FrozenBitset _larger_capacity_(self, long size) noexcept + cpdef long capacity(self) noexcept + cpdef bint isempty(self) noexcept cpdef bint issubset(self, FrozenBitset other) except -1 cpdef bint issuperset(self, FrozenBitset other) except -1 cpdef bint isdisjoint(self, FrozenBitset other) except -1 - cpdef _union(self, FrozenBitset other) - cpdef intersection(self, FrozenBitset other) - cpdef difference(self, FrozenBitset other) - cpdef symmetric_difference(self, FrozenBitset other) - cpdef complement(self) - cpdef __copy__(self) + cpdef _union(self, FrozenBitset other) noexcept + cpdef intersection(self, FrozenBitset other) noexcept + cpdef difference(self, FrozenBitset other) noexcept + cpdef symmetric_difference(self, FrozenBitset other) noexcept + cpdef complement(self) noexcept + cpdef __copy__(self) noexcept cdef class Bitset(FrozenBitset): - cpdef __copy__(self) - cpdef update(self, FrozenBitset other) - cpdef intersection_update(self, FrozenBitset other) - cpdef difference_update(self, FrozenBitset other) - cpdef symmetric_difference_update(self, FrozenBitset other) - cpdef add(self, unsigned long n) - cpdef remove(self, unsigned long n) - cpdef discard(self, unsigned long n) - cpdef pop(self) - cpdef clear(self) + cpdef __copy__(self) noexcept + cpdef update(self, FrozenBitset other) noexcept + cpdef intersection_update(self, FrozenBitset other) noexcept + cpdef difference_update(self, FrozenBitset other) noexcept + cpdef symmetric_difference_update(self, FrozenBitset other) noexcept + cpdef add(self, unsigned long n) noexcept + cpdef remove(self, unsigned long n) noexcept + cpdef discard(self, unsigned long n) noexcept + cpdef pop(self) noexcept + cpdef clear(self) noexcept diff --git a/src/sage/data_structures/bitset.pyx b/src/sage/data_structures/bitset.pyx index d9906b5edd2..0e3f6e3d640 100644 --- a/src/sage/data_structures/bitset.pyx +++ b/src/sage/data_structures/bitset.pyx @@ -404,7 +404,7 @@ cdef class FrozenBitset: for n in iter: bitset_add(self._bitset, n) - cdef FrozenBitset _new(self, long int capacity): + cdef FrozenBitset _new(self, long int capacity) noexcept: r""" Return an object of the same type as ``self``, initialized with a bitset of capacity ``capacity``. @@ -471,7 +471,7 @@ cdef class FrozenBitset: """ return reversed(bitset_list(self._bitset)) - cpdef FrozenBitset _larger_capacity_(self, long capacity): + cpdef FrozenBitset _larger_capacity_(self, long capacity) noexcept: """ Return a copy of ``self`` where the bitset has the maximum of the current capacity and the capacity passed. If no resizing is needed, @@ -518,7 +518,7 @@ cdef class FrozenBitset: bitset_realloc(temp._bitset, capacity) return temp - cpdef long capacity(self): + cpdef long capacity(self) noexcept: """ Return the size of the underlying bitset. @@ -556,7 +556,7 @@ cdef class FrozenBitset: else: return hash - cpdef bint isempty(self): + cpdef bint isempty(self) noexcept: """ Test if the bitset is empty. @@ -872,7 +872,7 @@ cdef class FrozenBitset: """ return str(self) - cpdef _union(self, FrozenBitset other): + cpdef _union(self, FrozenBitset other) noexcept: """ Return the union of ``self`` and ``other``. @@ -971,7 +971,7 @@ cdef class FrozenBitset: """ return self._union(other) - cpdef intersection(self, FrozenBitset other): + cpdef intersection(self, FrozenBitset other) noexcept: """ Return the intersection of ``self`` and ``other``. @@ -1041,7 +1041,7 @@ cdef class FrozenBitset: """ return self.intersection(other) - cpdef difference(self, FrozenBitset other): + cpdef difference(self, FrozenBitset other) noexcept: """ Return the difference of ``self`` and ``other``. @@ -1110,7 +1110,7 @@ cdef class FrozenBitset: """ return self.difference(other) - cpdef symmetric_difference(self, FrozenBitset other): + cpdef symmetric_difference(self, FrozenBitset other) noexcept: """ Return the symmetric difference of ``self`` and ``other``. @@ -1183,7 +1183,7 @@ cdef class FrozenBitset: """ return self.symmetric_difference(other) - cpdef complement(self): + cpdef complement(self) noexcept: """ Return the complement of self. @@ -1229,7 +1229,7 @@ cdef class FrozenBitset: """ return self.complement() - cpdef __copy__(self): + cpdef __copy__(self) noexcept: """ Return ``self`` (since ``self`` is immutable). @@ -1287,7 +1287,7 @@ cdef class Bitset(FrozenBitset): True """ - cpdef __copy__(self): + cpdef __copy__(self) noexcept: """ Return a copy of ``self``. @@ -1427,7 +1427,7 @@ cdef class Bitset(FrozenBitset): elif op == Py_GE: return bitset_issuperset(left._bitset, right._bitset) - cdef FrozenBitset _new(self, long int capacity): + cdef FrozenBitset _new(self, long int capacity) noexcept: """ Return an object of the same type as ``self``, initialized with a bitset of capacity ``capacity``. @@ -1436,7 +1436,7 @@ cdef class Bitset(FrozenBitset): b = Bitset.__new__(Bitset, None, capacity) return b - cpdef update(self, FrozenBitset other): + cpdef update(self, FrozenBitset other) noexcept: """ Update the bitset to include items in ``other``. @@ -1508,7 +1508,7 @@ cdef class Bitset(FrozenBitset): self.update(other) return self - cpdef intersection_update(self, FrozenBitset other): + cpdef intersection_update(self, FrozenBitset other) noexcept: """ Update the bitset to the intersection of ``self`` and ``other``. @@ -1577,7 +1577,7 @@ cdef class Bitset(FrozenBitset): self.intersection_update(other) return self - cpdef difference_update(self, FrozenBitset other): + cpdef difference_update(self, FrozenBitset other) noexcept: """ Update the bitset to the difference of ``self`` and ``other``. @@ -1674,7 +1674,7 @@ cdef class Bitset(FrozenBitset): self.difference_update(other) return self - cpdef symmetric_difference_update(self, FrozenBitset other): + cpdef symmetric_difference_update(self, FrozenBitset other) noexcept: """ Update the bitset to the symmetric difference of ``self`` and ``other``. @@ -1767,7 +1767,7 @@ cdef class Bitset(FrozenBitset): self.symmetric_difference_update(other) return self - cpdef add(self, unsigned long n): + cpdef add(self, unsigned long n) noexcept: """ Update the bitset by adding ``n``. @@ -1796,7 +1796,7 @@ cdef class Bitset(FrozenBitset): bitset_realloc(self._bitset, n + 1) bitset_add(self._bitset, n) - cpdef remove(self, unsigned long n): + cpdef remove(self, unsigned long n) noexcept: """ Update the bitset by removing ``n``. Raises ``KeyError`` if ``n`` is not contained in the bitset. @@ -1836,7 +1836,7 @@ cdef class Bitset(FrozenBitset): else: bitset_remove(self._bitset, n) - cpdef discard(self, unsigned long n): + cpdef discard(self, unsigned long n) noexcept: """ Update the bitset by removing ``n``. @@ -1869,7 +1869,7 @@ cdef class Bitset(FrozenBitset): if n < self._bitset.size: bitset_discard(self._bitset, n) - cpdef pop(self): + cpdef pop(self) noexcept: """ Remove and return an arbitrary element from the set. Raises ``KeyError`` if the set is empty. @@ -1897,7 +1897,7 @@ cdef class Bitset(FrozenBitset): """ return bitset_pop(self._bitset) - cpdef clear(self): + cpdef clear(self) noexcept: """ Removes all elements from the bitset. diff --git a/src/sage/data_structures/bitset_base.pxd b/src/sage/data_structures/bitset_base.pxd index 6c1d69364c9..60082345ccc 100644 --- a/src/sage/data_structures/bitset_base.pxd +++ b/src/sage/data_structures/bitset_base.pxd @@ -132,26 +132,26 @@ cdef extern from "bitset_intrinsics.h": # NOTE: In all functions in this section, the index n is interpreted # modulo GMP_LIMB_BITS, the number of bits in a limb. # -cdef inline mp_limb_t limb_one_set_bit(mp_bitcnt_t n): +cdef inline mp_limb_t limb_one_set_bit(mp_bitcnt_t n) noexcept: """ Return a limb with only bit n set. """ return (1) << (n % GMP_LIMB_BITS) -cdef inline mp_limb_t limb_one_zero_bit(mp_bitcnt_t n): +cdef inline mp_limb_t limb_one_zero_bit(mp_bitcnt_t n) noexcept: """ Return a limb with all bits set, except for bit n. """ return ~((1) << (n % GMP_LIMB_BITS)) -cdef inline mp_limb_t limb_lower_bits_down(mp_bitcnt_t n): +cdef inline mp_limb_t limb_lower_bits_down(mp_bitcnt_t n) noexcept: """ Return a limb with the lower n bits set, where n is interpreted in [0 .. GMP_LIMB_BITS-1]. """ return ((1) << (n % GMP_LIMB_BITS)) - 1 -cdef inline mp_limb_t limb_lower_bits_up(mp_bitcnt_t n): +cdef inline mp_limb_t limb_lower_bits_up(mp_bitcnt_t n) noexcept: """ Return a limb with the lower n bits set, where n is interpreted in [1 .. GMP_LIMB_BITS]. @@ -184,7 +184,7 @@ cdef inline bint bitset_init(fused_bitset_t bits, mp_bitcnt_t size) except -1: bits.non_zero_chunks_are_initialized = False bits.non_zero_chunks = check_allocarray((bits.limbs*LIMB_SIZE) // ALIGNMENT, sizeof(mp_bitcnt_t)) -cdef inline bint bitset_check_alignment(fused_bitset_t bits): +cdef inline bint bitset_check_alignment(fused_bitset_t bits) noexcept: """ Return whether the bitset is aligned correctly. """ @@ -215,7 +215,7 @@ cdef inline int bitset_realloc(bitset_t bits, mp_bitcnt_t size) except -1: # Zero removed bits bitset_fix(bits) -cdef inline void bitset_free(fused_bitset_t bits): +cdef inline void bitset_free(fused_bitset_t bits) noexcept: """ Deallocate the memory in bits. """ @@ -225,7 +225,7 @@ cdef inline void bitset_free(fused_bitset_t bits): sig_free(bits.mem) sig_free(bits.non_zero_chunks) -cdef inline void bitset_clear(fused_bitset_t bits): +cdef inline void bitset_clear(fused_bitset_t bits) noexcept: """ Remove all elements from the set. """ @@ -233,7 +233,7 @@ cdef inline void bitset_clear(fused_bitset_t bits): if fused_bitset_t is sparse_bitset_t: bits.non_zero_chunks_are_initialized = False -cdef inline void bitset_zero(fused_bitset_t bits): +cdef inline void bitset_zero(fused_bitset_t bits) noexcept: """ Remove all elements from the set. @@ -243,7 +243,7 @@ cdef inline void bitset_zero(fused_bitset_t bits): if fused_bitset_t is sparse_bitset_t: bits.non_zero_chunks_are_initialized = False -cdef inline void bitset_copy(fused_bitset_t dst, fused_bitset_t src): +cdef inline void bitset_copy(fused_bitset_t dst, fused_bitset_t src) noexcept: """ Copy the bitset src over to the bitset dst, overwriting dst. @@ -253,7 +253,7 @@ cdef inline void bitset_copy(fused_bitset_t dst, fused_bitset_t src): if fused_bitset_t is sparse_bitset_t: dst.non_zero_chunks_are_initialized = False -cdef inline void bitset_copy_flex(fused_bitset_t dst, fused_bitset_t src): +cdef inline void bitset_copy_flex(fused_bitset_t dst, fused_bitset_t src) noexcept: """ Copy the bitset src over to the bitset dst, overwriting dst. @@ -266,13 +266,13 @@ cdef inline void bitset_copy_flex(fused_bitset_t dst, fused_bitset_t src): if fused_bitset_t is sparse_bitset_t: dst.non_zero_chunks_are_initialized = False -cdef inline void bitset_fix(fused_bitset_t bits): +cdef inline void bitset_fix(fused_bitset_t bits) noexcept: """ Clear upper bits in upper limb which should be zero. """ bits.bits[bits.limbs - 1] &= limb_lower_bits_up(bits.size) -cdef inline void sparse_bitset_set_non_zero(sparse_bitset_t bits) nogil: +cdef inline void sparse_bitset_set_non_zero(sparse_bitset_t bits) noexcept nogil: """ Set the non zero chunks of ``bits``. """ @@ -283,7 +283,7 @@ cdef inline void sparse_bitset_set_non_zero(sparse_bitset_t bits) nogil: # Bitset Comparison ############################################################################# -cdef inline bint mpn_equal_bits(mp_srcptr b1, mp_srcptr b2, mp_bitcnt_t n): +cdef inline bint mpn_equal_bits(mp_srcptr b1, mp_srcptr b2, mp_bitcnt_t n) noexcept: """ Return ``True`` iff the first n bits of *b1 and *b2 agree. """ @@ -298,7 +298,7 @@ cdef inline bint mpn_equal_bits(mp_srcptr b1, mp_srcptr b2, mp_bitcnt_t n): cdef mp_limb_t b2h = b2[nlimbs] return (b1h ^ b2h) & mask == 0 -cdef inline bint mpn_equal_bits_shifted(mp_srcptr b1, mp_srcptr b2, mp_bitcnt_t n, mp_bitcnt_t offset): +cdef inline bint mpn_equal_bits_shifted(mp_srcptr b1, mp_srcptr b2, mp_bitcnt_t n, mp_bitcnt_t offset) noexcept: """ Return ``True`` iff the first n bits of *b1 and the bits ranging from offset to offset+n of *b2 agree. @@ -329,14 +329,14 @@ cdef inline bint mpn_equal_bits_shifted(mp_srcptr b1, mp_srcptr b2, mp_bitcnt_t tmp_limb |= (b2[preinc(i2)] << neg_bit_offset) return (b1h ^ tmp_limb) & mask == 0 -cdef inline bint bitset_isempty(fused_bitset_t bits) nogil: +cdef inline bint bitset_isempty(fused_bitset_t bits) noexcept nogil: """ Test whether bits is empty. Return True (i.e., 1) if the set is empty, False (i.e., 0) otherwise. """ return _bitset_isempty(bits.bits, bits.limbs) -cdef inline bint bitset_is_zero(fused_bitset_t bits): +cdef inline bint bitset_is_zero(fused_bitset_t bits) noexcept: """ Test whether bits is empty (i.e., zero). Return True (1) if the set is empty, False (0) otherwise. @@ -345,7 +345,7 @@ cdef inline bint bitset_is_zero(fused_bitset_t bits): """ return bitset_isempty(bits) -cdef inline bint bitset_eq(fused_bitset_t a, fused_bitset_t b): +cdef inline bint bitset_eq(fused_bitset_t a, fused_bitset_t b) noexcept: """ Compare bitset a and b. Return True (i.e., 1) if the sets are equal, and False (i.e., 0) otherwise. @@ -354,7 +354,7 @@ cdef inline bint bitset_eq(fused_bitset_t a, fused_bitset_t b): """ return _bitset_cmp(a.bits, b.bits, b.limbs, EQUAL) -cdef inline int bitset_cmp(fused_bitset_t a, fused_bitset_t b): +cdef inline int bitset_cmp(fused_bitset_t a, fused_bitset_t b) noexcept: """ Compare bitsets a and b. Return 0 if the two sets are identical, and consistently return -1 or 1 for two sets that are @@ -364,7 +364,7 @@ cdef inline int bitset_cmp(fused_bitset_t a, fused_bitset_t b): """ return mpn_cmp(a.bits, b.bits, b.limbs) -cdef inline int bitset_lex_cmp(fused_bitset_t a, fused_bitset_t b): +cdef inline int bitset_lex_cmp(fused_bitset_t a, fused_bitset_t b) noexcept: """ Compare bitsets ``a`` and ``b`` using lexicographical ordering. @@ -393,7 +393,7 @@ cdef inline int bitset_lex_cmp(fused_bitset_t a, fused_bitset_t b): else: return -1 -cdef inline bint bitset_issubset(fused_bitset_t a, fused_bitset_t b) nogil: +cdef inline bint bitset_issubset(fused_bitset_t a, fused_bitset_t b) noexcept nogil: """ Test whether a is a subset of b (i.e., every element in a is also in b). @@ -405,7 +405,7 @@ cdef inline bint bitset_issubset(fused_bitset_t a, fused_bitset_t b) nogil: else: return _bitset_cmp(a.bits, b.bits, a.limbs, SUBSET) -cdef inline bint bitset_issuperset(fused_bitset_t a, fused_bitset_t b) nogil: +cdef inline bint bitset_issuperset(fused_bitset_t a, fused_bitset_t b) noexcept nogil: """ Test whether a is a superset of b (i.e., every element in b is also in a). @@ -414,7 +414,7 @@ cdef inline bint bitset_issuperset(fused_bitset_t a, fused_bitset_t b) nogil: """ return bitset_issubset(b, a) -cdef inline bint bitset_are_disjoint(fused_bitset_t a, fused_bitset_t b): +cdef inline bint bitset_are_disjoint(fused_bitset_t a, fused_bitset_t b) noexcept: """ Tests whether ``a`` and ``b`` have an empty intersection. @@ -430,14 +430,14 @@ cdef inline bint bitset_are_disjoint(fused_bitset_t a, fused_bitset_t b): # Bitset Bit Manipulation ############################################################################# -cdef inline bint bitset_in(fused_bitset_t bits, mp_bitcnt_t n): +cdef inline bint bitset_in(fused_bitset_t bits, mp_bitcnt_t n) noexcept: """ Check if n is in bits. Return True (i.e., 1) if n is in the set, False (i.e., 0) otherwise. """ return (bits.bits[n >> index_shift] >> (n % GMP_LIMB_BITS)) & 1 -cdef inline bint bitset_check(fused_bitset_t bits, mp_bitcnt_t n): +cdef inline bint bitset_check(fused_bitset_t bits, mp_bitcnt_t n) noexcept: """ Check if n is in bits. Return True (i.e., 1) if n is in the set, False (i.e., 0) otherwise. @@ -446,7 +446,7 @@ cdef inline bint bitset_check(fused_bitset_t bits, mp_bitcnt_t n): """ return bitset_in(bits, n) -cdef inline bint bitset_not_in(fused_bitset_t bits, mp_bitcnt_t n): +cdef inline bint bitset_not_in(fused_bitset_t bits, mp_bitcnt_t n) noexcept: """ Check if n is not in bits. Return True (i.e., 1) if n is not in the set, False (i.e., 0) otherwise. @@ -463,7 +463,7 @@ cdef inline bint bitset_remove(fused_bitset_t bits, mp_bitcnt_t n) except -1: if fused_bitset_t is sparse_bitset_t: bits.non_zero_chunks_are_initialized = False -cdef inline void bitset_discard(fused_bitset_t bits, mp_bitcnt_t n): +cdef inline void bitset_discard(fused_bitset_t bits, mp_bitcnt_t n) noexcept: """ Remove n from bits. """ @@ -471,7 +471,7 @@ cdef inline void bitset_discard(fused_bitset_t bits, mp_bitcnt_t n): if fused_bitset_t is sparse_bitset_t: bits.non_zero_chunks_are_initialized = False -cdef inline void bitset_unset(fused_bitset_t bits, mp_bitcnt_t n): +cdef inline void bitset_unset(fused_bitset_t bits, mp_bitcnt_t n) noexcept: """ Remove n from bits. @@ -479,7 +479,7 @@ cdef inline void bitset_unset(fused_bitset_t bits, mp_bitcnt_t n): """ bitset_discard(bits, n) -cdef inline void bitset_add(fused_bitset_t bits, mp_bitcnt_t n): +cdef inline void bitset_add(fused_bitset_t bits, mp_bitcnt_t n) noexcept: """ Add n to bits. """ @@ -487,7 +487,7 @@ cdef inline void bitset_add(fused_bitset_t bits, mp_bitcnt_t n): if fused_bitset_t is sparse_bitset_t: bits.non_zero_chunks_are_initialized = False -cdef inline void bitset_set(fused_bitset_t bits, mp_bitcnt_t n): +cdef inline void bitset_set(fused_bitset_t bits, mp_bitcnt_t n) noexcept: """ Add n to bits. @@ -495,14 +495,14 @@ cdef inline void bitset_set(fused_bitset_t bits, mp_bitcnt_t n): """ bitset_add(bits, n) -cdef inline void bitset_set_to(bitset_t bits, mp_bitcnt_t n, bint b): +cdef inline void bitset_set_to(bitset_t bits, mp_bitcnt_t n, bint b) noexcept: """ If b is True, add n to bits. If b is False, remove n from bits. """ bitset_unset(bits, n) bits.bits[n >> index_shift] |= (b) << (n % GMP_LIMB_BITS) -cdef inline void bitset_flip(fused_bitset_t bits, mp_bitcnt_t n): +cdef inline void bitset_flip(fused_bitset_t bits, mp_bitcnt_t n) noexcept: """ If n is in bits, remove n from bits. If n is not in bits, add n to bits. @@ -511,7 +511,7 @@ cdef inline void bitset_flip(fused_bitset_t bits, mp_bitcnt_t n): if fused_bitset_t is sparse_bitset_t: bits.non_zero_chunks_are_initialized = False -cdef inline void bitset_set_first_n(fused_bitset_t bits, mp_bitcnt_t n): +cdef inline void bitset_set_first_n(fused_bitset_t bits, mp_bitcnt_t n) noexcept: """ Set exactly the first n bits. """ @@ -530,7 +530,7 @@ cdef inline void bitset_set_first_n(fused_bitset_t bits, mp_bitcnt_t n): # Bitset Searching ############################################################################# -cdef inline long bitset_first(fused_bitset_t a): +cdef inline long bitset_first(fused_bitset_t a) noexcept: """ Calculate the index of the first element in the set. If the set is empty, returns -1. @@ -541,7 +541,7 @@ cdef inline long bitset_first(fused_bitset_t a): return (i << index_shift) | _bitset_first_in_limb_nonzero(a.bits[i]) return -1 -cdef inline long bitset_first_in_complement(fused_bitset_t a): +cdef inline long bitset_first_in_complement(fused_bitset_t a) noexcept: """ Calculate the index of the first element not in the set. If the set is full, returns -1. @@ -567,7 +567,7 @@ cdef inline long bitset_pop(fused_bitset_t a) except -1: bitset_discard(a, i) return i -cdef inline long bitset_first_diff(fused_bitset_t a, fused_bitset_t b): +cdef inline long bitset_first_diff(fused_bitset_t a, fused_bitset_t b) noexcept: """ Calculate the index of the first difference between a and b. If a and b are equal, then return -1. @@ -580,7 +580,7 @@ cdef inline long bitset_first_diff(fused_bitset_t a, fused_bitset_t b): return (i << index_shift) | _bitset_first_in_limb_nonzero(a.bits[i] ^ b.bits[i]) return -1 -cdef inline long bitset_next(fused_bitset_t a, mp_bitcnt_t n): +cdef inline long bitset_next(fused_bitset_t a, mp_bitcnt_t n) noexcept: """ Calculate the index of the next element in the set, starting at (and including) n. Return -1 if there are no elements from n @@ -598,7 +598,7 @@ cdef inline long bitset_next(fused_bitset_t a, mp_bitcnt_t n): return (i << index_shift) | _bitset_first_in_limb_nonzero(a.bits[i]) return -1 -cdef inline long bitset_next_diff(fused_bitset_t a, fused_bitset_t b, mp_bitcnt_t n): +cdef inline long bitset_next_diff(fused_bitset_t a, fused_bitset_t b, mp_bitcnt_t n) noexcept: """ Calculate the index of the next element that differs between a and b, starting at (and including) n. Return -1 if there are no @@ -618,13 +618,13 @@ cdef inline long bitset_next_diff(fused_bitset_t a, fused_bitset_t b, mp_bitcnt_ return (i << index_shift) | _bitset_first_in_limb(a.bits[i] ^ b.bits[i]) return -1 -cdef inline long bitset_len(fused_bitset_t bits) nogil: +cdef inline long bitset_len(fused_bitset_t bits) noexcept nogil: """ Calculate the number of items in the set (i.e., the number of nonzero bits). """ return _bitset_len(bits.bits, bits.limbs) -cdef inline long bitset_hash(fused_bitset_t bits): +cdef inline long bitset_hash(fused_bitset_t bits) noexcept: """ Calculate a (very naive) hash function. @@ -641,7 +641,7 @@ cdef inline long bitset_hash(fused_bitset_t bits): # Bitset Arithmetic ############################################################################# -cdef inline void bitset_complement(fused_bitset_t r, fused_bitset_t a): +cdef inline void bitset_complement(fused_bitset_t r, fused_bitset_t a) noexcept: """ Set r to be the complement of a, overwriting r. @@ -652,7 +652,7 @@ cdef inline void bitset_complement(fused_bitset_t r, fused_bitset_t a): if fused_bitset_t is sparse_bitset_t: r.non_zero_chunks_are_initialized = False -cdef inline void bitset_not(fused_bitset_t r, fused_bitset_t a): +cdef inline void bitset_not(fused_bitset_t r, fused_bitset_t a) noexcept: """ Set r to be the complement of a, overwriting r. @@ -664,7 +664,7 @@ cdef inline void bitset_not(fused_bitset_t r, fused_bitset_t a): if fused_bitset_t is sparse_bitset_t: r.non_zero_chunks_are_initialized = False -cdef inline void bitset_intersection(fused_bitset_t r, fused_bitset_t a, fused_bitset_t b) nogil: +cdef inline void bitset_intersection(fused_bitset_t r, fused_bitset_t a, fused_bitset_t b) noexcept nogil: """ Set r to the intersection of a and b, overwriting r. @@ -674,7 +674,7 @@ cdef inline void bitset_intersection(fused_bitset_t r, fused_bitset_t a, fused_b if fused_bitset_t is sparse_bitset_t: r.non_zero_chunks_are_initialized = False -cdef inline void sparse_bitset_intersection(sparse_bitset_t r, fused_bitset_t a, fused_bitset_t b) nogil: +cdef inline void sparse_bitset_intersection(sparse_bitset_t r, fused_bitset_t a, fused_bitset_t b) noexcept nogil: """ Set r to the intersection of a and b, overwriting r. @@ -685,7 +685,7 @@ cdef inline void sparse_bitset_intersection(sparse_bitset_t r, fused_bitset_t a, r.n_non_zero_chunks = _sparse_bitset_operation(r.bits, r.non_zero_chunks, a.bits, b.bits, b.limbs, AND) r.non_zero_chunks_are_initialized = True -cdef inline void bitset_and(fused_bitset_t r, fused_bitset_t a, fused_bitset_t b): +cdef inline void bitset_and(fused_bitset_t r, fused_bitset_t a, fused_bitset_t b) noexcept: """ Set r to the intersection of a and b, overwriting r. @@ -695,7 +695,7 @@ cdef inline void bitset_and(fused_bitset_t r, fused_bitset_t a, fused_bitset_t b """ bitset_intersection(r, a, b) -cdef inline void bitset_union(fused_bitset_t r, fused_bitset_t a, fused_bitset_t b) nogil: +cdef inline void bitset_union(fused_bitset_t r, fused_bitset_t a, fused_bitset_t b) noexcept nogil: """ Set r to the union of a and b, overwriting r. @@ -706,7 +706,7 @@ cdef inline void bitset_union(fused_bitset_t r, fused_bitset_t a, fused_bitset_t if fused_bitset_t is sparse_bitset_t: r.non_zero_chunks_are_initialized = False -cdef inline void sparse_bitset_union(sparse_bitset_t r, fused_bitset_t a, fused_bitset_t b) nogil: +cdef inline void sparse_bitset_union(sparse_bitset_t r, fused_bitset_t a, fused_bitset_t b) noexcept nogil: """ Set r to the union of a and b, overwriting r. @@ -718,7 +718,7 @@ cdef inline void sparse_bitset_union(sparse_bitset_t r, fused_bitset_t a, fused_ r.n_non_zero_chunks = _sparse_bitset_operation(r.bits, r.non_zero_chunks, a.bits, b.bits, b.limbs, OR) r.non_zero_chunks_are_initialized = True -cdef inline void bitset_or(fused_bitset_t r, fused_bitset_t a, fused_bitset_t b): +cdef inline void bitset_or(fused_bitset_t r, fused_bitset_t a, fused_bitset_t b) noexcept: """ Set r to the union of a and b, overwriting r. @@ -729,7 +729,7 @@ cdef inline void bitset_or(fused_bitset_t r, fused_bitset_t a, fused_bitset_t b) """ bitset_union(r, a, b) -cdef inline void bitset_difference(fused_bitset_t r, fused_bitset_t a, fused_bitset_t b): +cdef inline void bitset_difference(fused_bitset_t r, fused_bitset_t a, fused_bitset_t b) noexcept: """ Set r to the difference of a and b (i.e., things in a that are not in b), overwriting r. @@ -741,7 +741,7 @@ cdef inline void bitset_difference(fused_bitset_t r, fused_bitset_t a, fused_bit if fused_bitset_t is sparse_bitset_t: r.non_zero_chunks_are_initialized = False -cdef inline void sparse_bitset_difference(sparse_bitset_t r, fused_bitset_t a, fused_bitset_t b): +cdef inline void sparse_bitset_difference(sparse_bitset_t r, fused_bitset_t a, fused_bitset_t b) noexcept: """ Set r to the difference of a and b (i.e., things in a that are not in b), overwriting r. @@ -754,7 +754,7 @@ cdef inline void sparse_bitset_difference(sparse_bitset_t r, fused_bitset_t a, f r.n_non_zero_chunks = _sparse_bitset_operation(r.bits, r.non_zero_chunks, a.bits, b.bits, b.limbs, ANDNOT) r.non_zero_chunks_are_initialized = True -cdef inline void bitset_symmetric_difference(fused_bitset_t r, fused_bitset_t a, fused_bitset_t b): +cdef inline void bitset_symmetric_difference(fused_bitset_t r, fused_bitset_t a, fused_bitset_t b) noexcept: """ Set r to the symmetric difference of a and b, overwriting r. @@ -765,7 +765,7 @@ cdef inline void bitset_symmetric_difference(fused_bitset_t r, fused_bitset_t a, if fused_bitset_t is sparse_bitset_t: r.non_zero_chunks_are_initialized = False -cdef inline void sparse_bitset_symmetric_difference(sparse_bitset_t r, fused_bitset_t a, fused_bitset_t b): +cdef inline void sparse_bitset_symmetric_difference(sparse_bitset_t r, fused_bitset_t a, fused_bitset_t b) noexcept: """ Set r to the symmetric difference of a and b, overwriting r. @@ -777,7 +777,7 @@ cdef inline void sparse_bitset_symmetric_difference(sparse_bitset_t r, fused_bit r.n_non_zero_chunks = _sparse_bitset_operation(r.bits, r.non_zero_chunks, a.bits, b.bits, b.limbs, XOR) r.non_zero_chunks_are_initialized = True -cdef inline void bitset_xor(fused_bitset_t r, fused_bitset_t a, fused_bitset_t b): +cdef inline void bitset_xor(fused_bitset_t r, fused_bitset_t a, fused_bitset_t b) noexcept: """ Set r to the symmetric difference of a and b, overwriting r. @@ -788,7 +788,7 @@ cdef inline void bitset_xor(fused_bitset_t r, fused_bitset_t a, fused_bitset_t b """ bitset_symmetric_difference(r, a, b) -cdef inline void bitset_rshift(fused_bitset_t r, fused_bitset_t a, mp_bitcnt_t n): +cdef inline void bitset_rshift(fused_bitset_t r, fused_bitset_t a, mp_bitcnt_t n) noexcept: """ Shift the bitset ``a`` right by ``n`` bits and store the result in ``r``. @@ -831,7 +831,7 @@ cdef inline void bitset_rshift(fused_bitset_t r, fused_bitset_t a, mp_bitcnt_t n if fused_bitset_t is sparse_bitset_t: r.non_zero_chunks_are_initialized = False -cdef inline void bitset_lshift(fused_bitset_t r, fused_bitset_t a, mp_bitcnt_t n): +cdef inline void bitset_lshift(fused_bitset_t r, fused_bitset_t a, mp_bitcnt_t n) noexcept: """ Shift the bitset ``a`` left by ``n`` bits and store the result in ``r``. @@ -898,25 +898,25 @@ cdef inline int bitset_map(fused_bitset_t r, fused_bitset_t a, m) except -1: # Hamming Weights ############################################################################# -cdef inline long bitset_hamming_weight(fused_bitset_t a): +cdef inline long bitset_hamming_weight(fused_bitset_t a) noexcept: return bitset_len(a) ############################################################################# # Bitset Conversion ############################################################################# -cdef char* bitset_chars(char* s, fused_bitset_t bits, char zero=*, char one=*) +cdef char* bitset_chars(char* s, fused_bitset_t bits, char zero=*, char one=*) noexcept cdef int bitset_from_char(bitset_t bits, char* s, char zero=*, char one=*) except -1 cdef int bitset_from_str(bitset_t bits, object s, char zero=*, char one=*) except -1 -cdef bitset_string(fused_bitset_t bits) +cdef bitset_string(fused_bitset_t bits) noexcept -cdef bitset_bytes(fused_bitset_t bits) +cdef bitset_bytes(fused_bitset_t bits) noexcept -cdef list bitset_list(fused_bitset_t bits) +cdef list bitset_list(fused_bitset_t bits) noexcept -cdef bitset_pickle(bitset_t bs) +cdef bitset_pickle(bitset_t bs) noexcept -cdef bitset_unpickle(bitset_t bs, tuple input) +cdef bitset_unpickle(bitset_t bs, tuple input) noexcept diff --git a/src/sage/data_structures/bitset_base.pyx b/src/sage/data_structures/bitset_base.pyx index 6a527a8ebfe..616e3b1ab04 100644 --- a/src/sage/data_structures/bitset_base.pyx +++ b/src/sage/data_structures/bitset_base.pyx @@ -11,7 +11,7 @@ Few functions from ``bitset_base.pxd`` that are not inlined. # http://www.gnu.org/licenses/ #***************************************************************************** -cdef char* bitset_chars(char* s, fused_bitset_t bits, char zero=c'0', char one=c'1'): +cdef char* bitset_chars(char* s, fused_bitset_t bits, char zero=c'0', char one=c'1') noexcept: """ Return a string representation of the bitset in s, using zero for the character representing the items not in the bitset and one for @@ -47,13 +47,13 @@ cdef int bitset_from_str(bitset_t bits, object s, char zero=c'0', char one=c'1') cdef bytes b = str_to_bytes(s) return bitset_from_char(bits, b, zero, one) -cdef bitset_string(fused_bitset_t bits): +cdef bitset_string(fused_bitset_t bits) noexcept: """ Return a python string representing the bitset. """ return bytes_to_str(bitset_bytes(bits)) -cdef bitset_bytes(fused_bitset_t bits): +cdef bitset_bytes(fused_bitset_t bits) noexcept: """ Return a python bytes string representing the bitset. @@ -66,7 +66,7 @@ cdef bitset_bytes(fused_bitset_t bits): sig_free(s) return py_s -cdef list bitset_list(fused_bitset_t bits): +cdef list bitset_list(fused_bitset_t bits) noexcept: """ Return a list of elements in the bitset. """ @@ -77,7 +77,7 @@ cdef list bitset_list(fused_bitset_t bits): elt = bitset_next(bits, elt + 1) return elts -cdef bitset_pickle(bitset_t bs): +cdef bitset_pickle(bitset_t bs) noexcept: """ Convert ``bs`` to a reasonably compact Python structure. @@ -91,7 +91,7 @@ cdef bitset_pickle(bitset_t bs): data.append(bs.bits[i]) return (version, bs.size, bs.limbs, sizeof(unsigned long), tuple(data)) -cdef bitset_unpickle(bitset_t bs, tuple input): +cdef bitset_unpickle(bitset_t bs, tuple input) noexcept: """ Convert the data into a bitset. diff --git a/src/sage/data_structures/blas_dict.pxd b/src/sage/data_structures/blas_dict.pxd index 7464c0daba8..3def4f5a950 100644 --- a/src/sage/data_structures/blas_dict.pxd +++ b/src/sage/data_structures/blas_dict.pxd @@ -1,11 +1,11 @@ cpdef int iaxpy(a, dict X, dict Y, bint remove_zeros=*, bint factor_on_left=*) except -1 -cpdef dict axpy(a, dict X, dict Y, bint factor_on_left=*) -cpdef dict negate(dict D) -cpdef dict scal(a, dict D, bint factor_on_left=*) -cpdef dict add(dict D, dict D2) -cpdef dict sum(dict_iter) -cpdef dict linear_combination(dict_factor_iter, bint factor_on_left=*) -cpdef dict sum_of_monomials(monomials, scalar) -cpdef dict sum_of_terms(index_coeff_pairs) -cdef dict remove_zeros(dict D) -cpdef dict convert_remove_zeroes(dict D, R) +cpdef dict axpy(a, dict X, dict Y, bint factor_on_left=*) noexcept +cpdef dict negate(dict D) noexcept +cpdef dict scal(a, dict D, bint factor_on_left=*) noexcept +cpdef dict add(dict D, dict D2) noexcept +cpdef dict sum(dict_iter) noexcept +cpdef dict linear_combination(dict_factor_iter, bint factor_on_left=*) noexcept +cpdef dict sum_of_monomials(monomials, scalar) noexcept +cpdef dict sum_of_terms(index_coeff_pairs) noexcept +cdef dict remove_zeros(dict D) noexcept +cpdef dict convert_remove_zeroes(dict D, R) noexcept diff --git a/src/sage/data_structures/blas_dict.pyx b/src/sage/data_structures/blas_dict.pyx index c13cab2aab9..c624aa6a2d5 100644 --- a/src/sage/data_structures/blas_dict.pyx +++ b/src/sage/data_structures/blas_dict.pyx @@ -143,7 +143,7 @@ cpdef int iaxpy(a, dict X, dict Y, bint remove_zeros=True, bint factor_on_left=T del Y[key] return 0 -cpdef dict axpy(a, dict X, dict Y, bint factor_on_left=True): +cpdef dict axpy(a, dict X, dict Y, bint factor_on_left=True) noexcept: """ Return `a X + Y`. @@ -203,7 +203,7 @@ cpdef dict axpy(a, dict X, dict Y, bint factor_on_left=True): iaxpy(a, X, Y, True, factor_on_left) return Y -cpdef dict negate(dict D): +cpdef dict negate(dict D) noexcept: r""" Return a dictionary representing the vector `-X`. @@ -220,7 +220,7 @@ cpdef dict negate(dict D): """ return { key: -value for key, value in D.iteritems() } -cpdef dict scal(a, dict D, bint factor_on_left=True): +cpdef dict scal(a, dict D, bint factor_on_left=True) noexcept: r""" Return a dictionary representing the vector `a*X`. @@ -242,7 +242,7 @@ cpdef dict scal(a, dict D, bint factor_on_left=True): # So for now we just delegate to axpy. return axpy(a, D, {}, factor_on_left=factor_on_left) -cpdef dict add(dict D, dict D2): +cpdef dict add(dict D, dict D2) noexcept: r""" Return the pointwise addition of dictionaries ``D`` and ``D2``. @@ -269,7 +269,7 @@ cpdef dict add(dict D, dict D2): D, D2 = D2, D return axpy(1, D2, D) -cpdef dict sum(dict_iter): +cpdef dict sum(dict_iter) noexcept: r""" Return the pointwise addition of dictionaries with coefficients. @@ -310,7 +310,7 @@ cpdef dict sum(dict_iter): return remove_zeros(result) -cpdef dict linear_combination(dict_factor_iter, bint factor_on_left=True): +cpdef dict linear_combination(dict_factor_iter, bint factor_on_left=True) noexcept: r""" Return the pointwise addition of dictionaries with coefficients. @@ -355,7 +355,7 @@ cpdef dict linear_combination(dict_factor_iter, bint factor_on_left=True): return remove_zeros(result) -cpdef dict sum_of_monomials(monomials, scalar): +cpdef dict sum_of_monomials(monomials, scalar) noexcept: r""" Return the pointwise addition of ``monomials``. @@ -383,7 +383,7 @@ cpdef dict sum_of_monomials(monomials, scalar): result[m] = scalar return remove_zeros(result) -cpdef dict sum_of_terms(index_coeff_pairs): +cpdef dict sum_of_terms(index_coeff_pairs) noexcept: r""" Return the linear combination of a monomial scaled by a coefficient. @@ -411,7 +411,7 @@ cpdef dict sum_of_terms(index_coeff_pairs): result[index] = coeff return remove_zeros(result) -cdef dict remove_zeros(dict D): +cdef dict remove_zeros(dict D) noexcept: """ Remove all keys whose value is zero from ``D``. """ @@ -422,7 +422,7 @@ cdef dict remove_zeros(dict D): del D[index] return D -cpdef dict convert_remove_zeroes(dict D, R): +cpdef dict convert_remove_zeroes(dict D, R) noexcept: """ Remove all keys whose value is zero from ``D`` after coercing into the ring ``R``. diff --git a/src/sage/data_structures/bounded_integer_sequences.pxd b/src/sage/data_structures/bounded_integer_sequences.pxd index b4466741034..44267b4fb46 100644 --- a/src/sage/data_structures/bounded_integer_sequences.pxd +++ b/src/sage/data_structures/bounded_integer_sequences.pxd @@ -34,28 +34,28 @@ ctypedef struct biseq_s: ctypedef biseq_s biseq_t[1] cdef bint biseq_init(biseq_t R, mp_size_t l, mp_bitcnt_t itemsize) except -1 -cdef void biseq_dealloc(biseq_t S) +cdef void biseq_dealloc(biseq_t S) noexcept cdef bint biseq_init_copy(biseq_t R, biseq_t S) except -1 -cdef tuple biseq_pickle(biseq_t S) +cdef tuple biseq_pickle(biseq_t S) noexcept cdef bint biseq_unpickle(biseq_t R, tuple bitset_data, mp_bitcnt_t itembitsize, mp_size_t length) except -1 cdef bint biseq_init_list(biseq_t R, list data, size_t bound) except -1 -cdef Py_hash_t biseq_hash(biseq_t S) -cdef bint biseq_richcmp(biseq_t S1, biseq_t S2, int op) +cdef Py_hash_t biseq_hash(biseq_t S) noexcept +cdef bint biseq_richcmp(biseq_t S1, biseq_t S2, int op) noexcept cdef bint biseq_init_concat(biseq_t R, biseq_t S1, biseq_t S2) except -1 cdef bint biseq_startswith(biseq_t S1, biseq_t S2) except -1 cdef mp_size_t biseq_contains(biseq_t S1, biseq_t S2, mp_size_t start) except -2 cdef mp_size_t biseq_startswith_tail(biseq_t S1, biseq_t S2, mp_size_t start) except -2 cdef mp_size_t biseq_index(biseq_t S, size_t item, mp_size_t start) except -2 -cdef size_t biseq_getitem(biseq_t S, mp_size_t index) -cdef biseq_getitem_py(biseq_t S, mp_size_t index) -cdef void biseq_inititem(biseq_t S, mp_size_t index, size_t item) -cdef void biseq_clearitem(biseq_t S, mp_size_t index) +cdef size_t biseq_getitem(biseq_t S, mp_size_t index) noexcept +cdef biseq_getitem_py(biseq_t S, mp_size_t index) noexcept +cdef void biseq_inititem(biseq_t S, mp_size_t index, size_t item) noexcept +cdef void biseq_clearitem(biseq_t S, mp_size_t index) noexcept cdef bint biseq_init_slice(biseq_t R, biseq_t S, mp_size_t start, mp_size_t stop, mp_size_t step) except -1 cdef class BoundedIntegerSequence: cdef biseq_t data - cpdef bint startswith(self, BoundedIntegerSequence other) - cpdef list list(self) - cpdef BoundedIntegerSequence maximal_overlap(self, BoundedIntegerSequence other) + cpdef bint startswith(self, BoundedIntegerSequence other) noexcept + cpdef list list(self) noexcept + cpdef BoundedIntegerSequence maximal_overlap(self, BoundedIntegerSequence other) noexcept -cpdef BoundedIntegerSequence NewBISEQ(tuple bitset_data, mp_bitcnt_t itembitsize, mp_size_t length) +cpdef BoundedIntegerSequence NewBISEQ(tuple bitset_data, mp_bitcnt_t itembitsize, mp_size_t length) noexcept diff --git a/src/sage/data_structures/bounded_integer_sequences.pyx b/src/sage/data_structures/bounded_integer_sequences.pyx index 907f9b4298a..7e6513ec1b0 100644 --- a/src/sage/data_structures/bounded_integer_sequences.pyx +++ b/src/sage/data_structures/bounded_integer_sequences.pyx @@ -142,7 +142,7 @@ cdef bint biseq_init(biseq_t R, mp_size_t l, mp_bitcnt_t itemsize) except -1: R.itembitsize = itemsize R.mask_item = limb_lower_bits_up(itemsize) -cdef inline void biseq_dealloc(biseq_t S): +cdef inline void biseq_dealloc(biseq_t S) noexcept: """ Deallocate the memory used by ``S``. """ @@ -161,7 +161,7 @@ cdef bint biseq_init_copy(biseq_t R, biseq_t S) except -1: # Pickling # -cdef tuple biseq_pickle(biseq_t S): +cdef tuple biseq_pickle(biseq_t S) noexcept: return (bitset_pickle(S.data), S.itembitsize, S.length) cdef bint biseq_unpickle(biseq_t R, tuple bitset_data, mp_bitcnt_t itembitsize, mp_size_t length) except -1: @@ -199,10 +199,10 @@ cdef bint biseq_init_list(biseq_t R, list data, size_t bound) except -1: biseq_inititem(R, index, item_c) index += 1 -cdef inline Py_hash_t biseq_hash(biseq_t S): +cdef inline Py_hash_t biseq_hash(biseq_t S) noexcept: return S.itembitsize*(1073807360)+bitset_hash(S.data) -cdef inline bint biseq_richcmp(biseq_t S1, biseq_t S2, int op): +cdef inline bint biseq_richcmp(biseq_t S1, biseq_t S2, int op) noexcept: if S1.itembitsize != S2.itembitsize: return richcmp_not_equal(S1.itembitsize, S2.itembitsize, op) if S1.length != S2.length: @@ -271,7 +271,7 @@ cdef mp_size_t biseq_index(biseq_t S, size_t item, mp_size_t start) except -2: return -1 -cdef inline size_t biseq_getitem(biseq_t S, mp_size_t index): +cdef inline size_t biseq_getitem(biseq_t S, mp_size_t index) noexcept: """ Get item ``S[index]``, without checking margins. @@ -288,7 +288,7 @@ cdef inline size_t biseq_getitem(biseq_t S, mp_size_t index): out |= (S.data.bits[limb_index+1]) << (GMP_LIMB_BITS - bit_index) return out & S.mask_item -cdef biseq_getitem_py(biseq_t S, mp_size_t index): +cdef biseq_getitem_py(biseq_t S, mp_size_t index) noexcept: """ Get item ``S[index]`` as a Python ``int``, without checking margins. @@ -297,7 +297,7 @@ cdef biseq_getitem_py(biseq_t S, mp_size_t index): cdef size_t out = biseq_getitem(S, index) return PyLong_FromSize_t(out) -cdef inline void biseq_inititem(biseq_t S, mp_size_t index, size_t item): +cdef inline void biseq_inititem(biseq_t S, mp_size_t index, size_t item) noexcept: """ Set ``S[index] = item``, without checking margins. @@ -314,7 +314,7 @@ cdef inline void biseq_inititem(biseq_t S, mp_size_t index, size_t item): # Our item is stored using 2 limbs, add the part from the upper limb S.data.bits[limb_index+1] |= (item >> (GMP_LIMB_BITS - bit_index)) -cdef inline void biseq_clearitem(biseq_t S, mp_size_t index): +cdef inline void biseq_clearitem(biseq_t S, mp_size_t index) noexcept: """ Set ``S[index] = 0``, without checking margins. @@ -1041,7 +1041,7 @@ cdef class BoundedIntegerSequence: return False return biseq_contains(self.data, right.data, 0) >= 0 - cpdef list list(self): + cpdef list list(self) noexcept: """ Converts this bounded integer sequence to a list @@ -1067,7 +1067,7 @@ cdef class BoundedIntegerSequence: cdef mp_size_t i return [biseq_getitem_py(self.data, i) for i in range(self.data.length)] - cpdef bint startswith(self, BoundedIntegerSequence other): + cpdef bint startswith(self, BoundedIntegerSequence other) noexcept: """ Tells whether ``self`` starts with a given bounded integer sequence @@ -1236,7 +1236,7 @@ cdef class BoundedIntegerSequence: biseq_init_concat(out.data, myself.data, right.data) return out - cpdef BoundedIntegerSequence maximal_overlap(self, BoundedIntegerSequence other): + cpdef BoundedIntegerSequence maximal_overlap(self, BoundedIntegerSequence other) noexcept: """ Return ``self``'s maximal trailing sub-sequence that ``other`` starts with. @@ -1355,7 +1355,7 @@ cdef class BoundedIntegerSequence: return 0 return h -cpdef BoundedIntegerSequence NewBISEQ(tuple bitset_data, mp_bitcnt_t itembitsize, mp_size_t length): +cpdef BoundedIntegerSequence NewBISEQ(tuple bitset_data, mp_bitcnt_t itembitsize, mp_size_t length) noexcept: """ Helper function for unpickling of :class:`BoundedIntegerSequence`. diff --git a/src/sage/data_structures/mutable_poset.py b/src/sage/data_structures/mutable_poset.py index 44d086fa920..97bfcf1cd52 100644 --- a/src/sage/data_structures/mutable_poset.py +++ b/src/sage/data_structures/mutable_poset.py @@ -947,9 +947,8 @@ def _iter_depth_first_visit_(self, marked, if key is not None: S = sorted(S, key=key) for shell in S: - for e in shell._iter_depth_first_visit_(marked, reverse, - key, condition): - yield e + yield from shell._iter_depth_first_visit_(marked, reverse, + key, condition) def iter_depth_first(self, reverse=False, key=None, condition=None): r""" @@ -1072,9 +1071,8 @@ def _iter_topological_visit_(self, marked, if key is not None and len(S) > 1: S = sorted(S, key=key) for shell in S: - for e in shell._iter_topological_visit_(marked, reverse, - key, condition): - yield e + yield from shell._iter_topological_visit_(marked, reverse, + key, condition) yield self def iter_topological(self, reverse=False, key=None, condition=None): @@ -1768,8 +1766,7 @@ def shells(self, include_special=False): """ if include_special: yield self.null - for e in self._shells_.values(): - yield e + yield from self._shells_.values() if include_special: yield self.oo diff --git a/src/sage/databases/stein_watkins.py b/src/sage/databases/stein_watkins.py index 167fa3a195b..6abf39426dd 100644 --- a/src/sage/databases/stein_watkins.py +++ b/src/sage/databases/stein_watkins.py @@ -158,8 +158,7 @@ def __len__(self): def __iter__(self): try: - for E in self.curves: - yield E + yield from self.curves except AttributeError: return diff --git a/src/sage/doctest/forker.py b/src/sage/doctest/forker.py index b5521868dd5..6c3b0b225ac 100644 --- a/src/sage/doctest/forker.py +++ b/src/sage/doctest/forker.py @@ -503,7 +503,7 @@ def getvalue(self): TestResults = namedtuple('TestResults', 'failed attempted') -class SageDocTestRunner(doctest.DocTestRunner, object): +class SageDocTestRunner(doctest.DocTestRunner): def __init__(self, *args, **kwds): """ A customized version of DocTestRunner that tracks dependencies diff --git a/src/sage/dynamics/arithmetic_dynamics/affine_ds.py b/src/sage/dynamics/arithmetic_dynamics/affine_ds.py index e672314a9c0..6938068bbc6 100644 --- a/src/sage/dynamics/arithmetic_dynamics/affine_ds.py +++ b/src/sage/dynamics/arithmetic_dynamics/affine_ds.py @@ -162,8 +162,9 @@ class DynamicalSystem_affine(SchemeMorphism_polynomial_affine_space, If you pass in quotient ring elements, they are reduced:: + sage: # needs sage.libs.singular sage: A. = AffineSpace(QQ, 3) - sage: X = A.subscheme([x-y]) + sage: X = A.subscheme([x - y]) sage: u,v,w = X.coordinate_ring().gens() sage: DynamicalSystem_affine([u, v, u+v], domain=X) Dynamical System of Closed subscheme of Affine Space of dimension 3 @@ -174,9 +175,10 @@ class DynamicalSystem_affine(SchemeMorphism_polynomial_affine_space, :: + sage: # needs sage.libs.singular sage: R. = PolynomialRing(QQ) sage: A. = AffineSpace(R, 3) - sage: X = A.subscheme(x^2-y^2) + sage: X = A.subscheme(x^2 - y^2) sage: H = End(X) sage: f = H([x^2/(t*y), t*y^2, x*z]) sage: DynamicalSystem_affine(f) @@ -188,8 +190,8 @@ class DynamicalSystem_affine(SchemeMorphism_polynomial_affine_space, :: - sage: x = var('x') - sage: DynamicalSystem_affine(x^2+1) + sage: x = var('x') # needs sage.symbolic + sage: DynamicalSystem_affine(x^2 + 1) # needs sage.symbolic Traceback (most recent call last): ... TypeError: symbolic ring cannot be the base ring @@ -397,10 +399,11 @@ def homogenize(self, n): :: + sage: # needs sage.rings.number_field sage: R. = PolynomialRing(QQbar) sage: A. = AffineSpace(R, 2) - sage: f = DynamicalSystem_affine([QQbar(sqrt(2))*x*y, a*x^2]) - sage: f.homogenize(2) + sage: f = DynamicalSystem_affine([QQbar(sqrt(2))*x*y, a*x^2]) # needs sage.symbolic + sage: f.homogenize(2) # needs sage.symbolic Dynamical System of Projective Space of dimension 2 over Univariate Polynomial Ring in a over Algebraic Field Defn: Defined on coordinates by sending (x0 : x1 : x2) to @@ -453,7 +456,7 @@ def dynatomic_polynomial(self, period): sage: A. = AffineSpace(ZZ, 1) sage: f = DynamicalSystem_affine([(x^2+1)/x]) - sage: f.dynatomic_polynomial(4) + sage: f.dynatomic_polynomial(4) # needs sage.libs.pari 2*x^12 + 18*x^10 + 57*x^8 + 79*x^6 + 48*x^4 + 12*x^2 + 1 :: @@ -507,8 +510,8 @@ def dynatomic_polynomial(self, period): :: sage: A. = AffineSpace(CC,1) - sage: F = DynamicalSystem_affine([1/2*x^2 + CC(sqrt(3))]) - sage: F.dynatomic_polynomial([1,1]) + sage: F = DynamicalSystem_affine([1/2*x^2 + CC(sqrt(3))]) # needs sage.symbolic + sage: F.dynatomic_polynomial([1,1]) # needs sage.symbolic (0.125000000000000*x^4 + 0.366025403784439*x^2 + 1.50000000000000)/(0.500000000000000*x^2 - x + 1.73205080756888) TESTS:: @@ -770,7 +773,7 @@ def multiplier(self, P, n, check=True): sage: P. = AffineSpace(CC, 1) sage: f = DynamicalSystem_affine([x^2 + 1/2]) - sage: f.multiplier(P([0.5 + 0.5*I]), 1) + sage: f.multiplier(P([0.5 + 0.5*I]), 1) # needs sage.symbolic [1.00000000000000 + 1.00000000000000*I] :: @@ -784,7 +787,7 @@ def multiplier(self, P, n, check=True): :: sage: P. = AffineSpace(QQ, 2) - sage: X = P.subscheme([x^2-y^2]) + sage: X = P.subscheme([x^2 - y^2]) sage: f = DynamicalSystem_affine([x^2, y^2], domain=X) sage: f.multiplier(X([1, 1]), 1) [2 0] @@ -823,7 +826,7 @@ def conjugate(self, M): EXAMPLES:: sage: A. = AffineSpace(QQ, 1) - sage: f = DynamicalSystem_affine([t^2+1]) + sage: f = DynamicalSystem_affine([t^2 + 1]) sage: f.conjugate(matrix([[1,2], [0,1]])) Dynamical System of Affine Space of dimension 1 over Rational Field Defn: Defined on coordinates by sending (t) to @@ -832,18 +835,20 @@ def conjugate(self, M): :: sage: A. = AffineSpace(ZZ,2) - sage: f = DynamicalSystem_affine([x^3+y^3,y^2]) + sage: f = DynamicalSystem_affine([x^3 + y^3, y^2]) sage: f.conjugate(matrix([[1,2,3], [0,1,2], [0,0,1]])) Dynamical System of Affine Space of dimension 2 over Integer Ring Defn: Defined on coordinates by sending (x, y) to - (x^3 + 6*x^2*y + 12*x*y^2 + 9*y^3 + 9*x^2 + 36*x*y + 40*y^2 + 27*x + 58*y + 28, y^2 + 4*y + 2) + (x^3 + 6*x^2*y + 12*x*y^2 + 9*y^3 + + 9*x^2 + 36*x*y + 40*y^2 + 27*x + 58*y + 28, y^2 + 4*y + 2) :: + sage: # needs sage.rings.number_field sage: R. = PolynomialRing(QQ) - sage: K. = NumberField(x^2+1) + sage: K. = NumberField(x^2 + 1) sage: A. = AffineSpace(ZZ,1) - sage: f = DynamicalSystem_affine([x^3+2*x^2+3]) + sage: f = DynamicalSystem_affine([x^3 + 2*x^2 + 3]) sage: f.conjugate(matrix([[i,i], [0,-i]])) Dynamical System of Affine Space of dimension 1 over Integer Ring Defn: Defined on coordinates by sending (x) to @@ -860,6 +865,7 @@ def degree(self): EXAMPLES:: + sage: # needs sage.rings.number_field sage: R. = QuadraticField(7) sage: A. = AffineSpace(R, 3) sage: f = DynamicalSystem_affine([x^2 + y^5 + c, x^11, z^19]) @@ -911,9 +917,10 @@ def weil_restriction(self): EXAMPLES:: + sage: # needs sage.rings.number_field sage: K. = QuadraticField(5) sage: A. = AffineSpace(K, 2) - sage: f = DynamicalSystem_affine([x^2-y^2, y^2]) + sage: f = DynamicalSystem_affine([x^2 - y^2, y^2]) sage: f.weil_restriction() Dynamical System of Affine Space of dimension 4 over Rational Field Defn: Defined on coordinates by sending (z0, z1, z2, z3) to @@ -921,6 +928,7 @@ def weil_restriction(self): :: + sage: # needs sage.rings.number_field sage: K. = QuadraticField(5) sage: PS. = AffineSpace(K, 2) sage: f = DynamicalSystem_affine([x, y]) @@ -940,13 +948,14 @@ def reduce_base_field(self): The base field of the map could be strictly larger than the field where all of the coefficients are defined. This function reduces the base field to the minimal possible. This can be done when - the base ring is a number field, QQbar, a finite field, or algebraic + the base ring is a number field, ``QQbar``, a finite field, or algebraic closure of a finite field. OUTPUT: A dynamical system EXAMPLES:: + sage: # needs sage.rings.finite_rings sage: K. = GF(5^2) sage: A. = AffineSpace(K, 2) sage: f = DynamicalSystem_affine([x^2 + 3*y^2, 3*y^2]) @@ -957,15 +966,20 @@ def reduce_base_field(self): :: + sage: # needs sage.rings.number_field sage.symbolic sage: A. = AffineSpace(QQbar, 2) - sage: f = DynamicalSystem_affine([x^2 + QQbar(sqrt(3))*y^2, QQbar(sqrt(-1))*y^2]) + sage: f = DynamicalSystem_affine([x^2 + QQbar(sqrt(3))*y^2, + ....: QQbar(sqrt(-1))*y^2]) sage: f.reduce_base_field() - Dynamical System of Affine Space of dimension 2 over Number Field in a with defining polynomial y^4 - y^2 + 1 with a = -0.866025403784439? + 0.50000000000000000?*I + Dynamical System of Affine Space of dimension 2 over Number Field in a + with defining polynomial y^4 - y^2 + 1 + with a = -0.866025403784439? + 0.50000000000000000?*I Defn: Defined on coordinates by sending (x, y) to (x^2 + (a^3 - 2*a)*y^2, (a^3)*y^2) :: + sage: # needs sage.rings.number_field sage: K. = CyclotomicField(5) sage: A. = AffineSpace(K, 2) sage: f = DynamicalSystem_affine([(3*x^2 + y) / (5*x), (y^2+1) / (x+y)]) @@ -1001,6 +1015,7 @@ def orbit_structure(self, P): :: + sage: # needs sage.rings.finite_rings sage: A. = AffineSpace(GF(49, 't'), 3) sage: f = DynamicalSystem_affine([x^2 - z, x - y + z, y^2 - x^2]) sage: f.orbit_structure(A(1, 1, 2)) @@ -1028,23 +1043,24 @@ def cyclegraph(self): EXAMPLES:: sage: P. = AffineSpace(GF(5), 2) - sage: f = DynamicalSystem_affine([x^2-y, x*y+1]) - sage: f.cyclegraph() + sage: f = DynamicalSystem_affine([x^2 - y, x*y + 1]) + sage: f.cyclegraph() # needs sage.graphs Looped digraph on 25 vertices :: + sage: # needs sage.rings.finite_rings sage: P. = AffineSpace(GF(3^3, 't'), 1) - sage: f = DynamicalSystem_affine([x^2-1]) - sage: f.cyclegraph() + sage: f = DynamicalSystem_affine([x^2 - 1]) + sage: f.cyclegraph() # needs sage.graphs Looped digraph on 27 vertices :: sage: P. = AffineSpace(GF(7), 2) - sage: X = P.subscheme(x-y) + sage: X = P.subscheme(x - y) sage: f = DynamicalSystem_affine([x^2, y^2], domain=X) - sage: f.cyclegraph() + sage: f.cyclegraph() # needs sage.graphs Looped digraph on 7 vertices """ V = [] diff --git a/src/sage/dynamics/arithmetic_dynamics/berkovich_ds.py b/src/sage/dynamics/arithmetic_dynamics/berkovich_ds.py index 203eb70b563..5559a48ecce 100644 --- a/src/sage/dynamics/arithmetic_dynamics/berkovich_ds.py +++ b/src/sage/dynamics/arithmetic_dynamics/berkovich_ds.py @@ -1,3 +1,4 @@ +# sage.doctest: needs sage.rings.padics r""" Dynamical systems on Berkovich space over `\CC_p`. @@ -22,23 +23,26 @@ # http://www.gnu.org/licenses/ #***************************************************************************** -from sage.structure.element import Element +from sage.categories.number_fields import NumberFields +from sage.dynamics.arithmetic_dynamics.affine_ds import DynamicalSystem_affine from sage.dynamics.arithmetic_dynamics.generic_ds import DynamicalSystem -from sage.misc.inherit_comparison import InheritComparisonClasscallMetaclass +from sage.dynamics.arithmetic_dynamics.projective_ds import DynamicalSystem_projective +from sage.matrix.constructor import Matrix from sage.misc.classcall_metaclass import typecall +from sage.misc.inherit_comparison import InheritComparisonClasscallMetaclass +from sage.misc.lazy_import import lazy_import +from sage.rings.infinity import Infinity +from sage.rings.integer_ring import ZZ +from sage.rings.rational_field import QQ +from sage.schemes.affine.affine_space import is_AffineSpace from sage.schemes.berkovich.berkovich_space import (Berkovich_Cp_Affine, Berkovich_Cp_Projective, is_Berkovich_Cp, Berkovich_Element_Cp_Affine) from sage.schemes.projective.projective_space import is_ProjectiveSpace -from sage.schemes.affine.affine_space import is_AffineSpace -from sage.rings.padics.padic_base_generic import pAdicBaseGeneric -from sage.dynamics.arithmetic_dynamics.projective_ds import DynamicalSystem_projective -from sage.dynamics.arithmetic_dynamics.affine_ds import DynamicalSystem_affine -from sage.categories.number_fields import NumberFields -from sage.rings.integer_ring import ZZ -from sage.rings.rational_field import QQ -from sage.rings.infinity import Infinity -from sage.matrix.constructor import Matrix +from sage.structure.element import Element + +lazy_import('sage.rings.padics.padic_base_generic', 'pAdicBaseGeneric') + class DynamicalSystem_Berkovich(Element, metaclass=InheritComparisonClasscallMetaclass): r""" @@ -71,15 +75,18 @@ class DynamicalSystem_Berkovich(Element, metaclass=InheritComparisonClasscallMet sage: P. = ProjectiveSpace(Qp(3), 1) sage: f = DynamicalSystem_projective([2*x^2 + 4*y^2, 3*x^2 + 9*y^2]) sage: DynamicalSystem_Berkovich(f) - Dynamical system of Projective Berkovich line over Cp(3) of precision 20 induced by the map + Dynamical system of Projective Berkovich line over Cp(3) of precision 20 + induced by the map Defn: Defined on coordinates by sending (x : y) to - ((2 + O(3^20))*x^2 + (1 + 3 + O(3^20))*y^2 : (3 + O(3^21))*x^2 + (3^2 + O(3^22))*y^2) + ((2 + O(3^20))*x^2 + (1 + 3 + O(3^20))*y^2 + : (3 + O(3^21))*x^2 + (3^2 + O(3^22))*y^2) Or directly from polynomials:: sage: P. = ProjectiveSpace(Qp(3),1) sage: DynamicalSystem_Berkovich([x^2 + y^2, y^2]) - Dynamical system of Projective Berkovich line over Cp(3) of precision 20 induced by the map + Dynamical system of Projective Berkovich line over Cp(3) of precision 20 + induced by the map Defn: Defined on coordinates by sending (x : y) to (x^2 + y^2 : y^2) @@ -87,7 +94,8 @@ class DynamicalSystem_Berkovich(Element, metaclass=InheritComparisonClasscallMet sage: R. = Qp(3)[] sage: DynamicalSystem_Berkovich([x^2, y^2]) - Dynamical system of Projective Berkovich line over Cp(3) of precision 20 induced by the map + Dynamical system of Projective Berkovich line over Cp(3) of precision 20 + induced by the map Defn: Defined on coordinates by sending (x : y) to (x^2 : y^2) @@ -112,6 +120,7 @@ class DynamicalSystem_Berkovich(Element, metaclass=InheritComparisonClasscallMet We can create dynamical systems which act on Berkovich spaces backed by number fields:: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: A. = NumberField(z^2 + 1) sage: ideal = A.prime_above(2) @@ -126,6 +135,7 @@ class DynamicalSystem_Berkovich(Element, metaclass=InheritComparisonClasscallMet We can use the optional parameter ``ideal`` to create the same dynamical system more efficiently:: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: A. = NumberField(z^2 + 1) sage: prime_ideal = A.prime_above(2) @@ -196,7 +206,7 @@ class DynamicalSystem_Berkovich(Element, metaclass=InheritComparisonClasscallMet sage: B = Berkovich_Cp_Projective(P, 3) sage: H = DynamicalSystem_Berkovich([x*y^2, x^3 + 20*y^3], B) sage: Q4 = B(1/9, 1.5) - sage: H(Q4) + sage: H(Q4) # needs sage.rings.number_field Type III point centered at (81/14581 : 1) of radius 0.00205761316872428 Alternatively, if checking for poles in the disk has been done already, @@ -358,9 +368,9 @@ def as_scheme_dynamical_system(self): sage: P. = ProjectiveSpace(Qp(3), 1) sage: f = DynamicalSystem_Berkovich([x^2 + y^2, x*y]) sage: f.as_scheme_dynamical_system() - Dynamical System of Projective Space of dimension 1 over 3-adic Field with capped relative precision 20 - Defn: Defined on coordinates by sending (x : y) to - (x^2 + y^2 : x*y) + Dynamical System of Projective Space of dimension 1 over + 3-adic Field with capped relative precision 20 + Defn: Defined on coordinates by sending (x : y) to (x^2 + y^2 : x*y) """ return self._system @@ -399,7 +409,7 @@ def defining_polynomials(self): sage: g = DynamicalSystem_Berkovich(f) sage: g.defining_polynomials() ((2 + O(3^20))*x^2 + (1 + 3 + O(3^20))*y^2, - (3 + O(3^21))*x^2 + (3^2 + O(3^22))*y^2) + (3 + O(3^21))*x^2 + (3^2 + O(3^22))*y^2) """ return self._system._polys @@ -418,6 +428,7 @@ def base_ring(self): :: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: A. = NumberField(z^3 + 20) sage: P. = ProjectiveSpace(A, 1) @@ -488,18 +499,16 @@ class DynamicalSystem_Berkovich_projective(DynamicalSystem_Berkovich): sage: H = End(P1) sage: DynamicalSystem_Berkovich(H([y, x])) Dynamical system of Projective Berkovich line over Cp(3) of precision 20 - induced by the map - Defn: Defined on coordinates by sending (x : y) to - (y : x) + induced by the map + Defn: Defined on coordinates by sending (x : y) to (y : x) Or from polynomials:: sage: P. = ProjectiveSpace(Qp(3), 1) sage: DynamicalSystem_Berkovich([x^2+y^2, y^2]) Dynamical system of Projective Berkovich line over Cp(3) of precision 20 - induced by the map - Defn: Defined on coordinates by sending (x : y) to - (x^2 + y^2 : y^2) + induced by the map + Defn: Defined on coordinates by sending (x : y) to (x^2 + y^2 : y^2) """ @staticmethod def __classcall_private__(cls, dynamical_system, domain=None): @@ -512,9 +521,8 @@ def __classcall_private__(cls, dynamical_system, domain=None): sage: from sage.dynamics.arithmetic_dynamics.berkovich_ds import DynamicalSystem_Berkovich_projective sage: DynamicalSystem_Berkovich_projective([y, x]) Dynamical system of Projective Berkovich line over Cp(3) of precision 20 - induced by the map - Defn: Defined on coordinates by sending (x : y) to - (y : x) + induced by the map + Defn: Defined on coordinates by sending (x : y) to (y : x) """ if not isinstance(dynamical_system, DynamicalSystem): if not isinstance(dynamical_system, DynamicalSystem_projective): @@ -549,7 +557,8 @@ def __init__(self, dynamical_system, domain=None): sage: P. = ProjectiveSpace(Qp(3), 1) sage: DynamicalSystem_Berkovich([x^2 + x*y + 2*y^2, 2*x*y]) - Dynamical system of Projective Berkovich line over Cp(3) of precision 20 induced by the map + Dynamical system of Projective Berkovich line over Cp(3) of precision 20 + induced by the map Defn: Defined on coordinates by sending (x : y) to (x^2 + x*y + (2 + O(3^20))*y^2 : (2 + O(3^20))*x*y) """ @@ -570,12 +579,13 @@ def scale_by(self, t): sage: P. = ProjectiveSpace(Qp(3), 1) sage: f = DynamicalSystem_Berkovich([x^2, y^2]) sage: f.scale_by(x); f - Dynamical system of Projective Berkovich line over Cp(3) of precision 20 induced by the map - Defn: Defined on coordinates by sending (x : y) to - (x^3 : x*y^2) + Dynamical system of Projective Berkovich line over Cp(3) of precision 20 + induced by the map + Defn: Defined on coordinates by sending (x : y) to (x^3 : x*y^2) :: + sage: # needs sage.rings.number_field sage: Q. = QQ[] sage: A. = NumberField(z^3 + 20) sage: ideal = A.prime_above(3) @@ -601,15 +611,15 @@ def normalize_coordinates(self): sage: P. = ProjectiveSpace(Qp(3), 1) sage: f = DynamicalSystem_Berkovich([2*x^2, 2*y^2]) sage: f.normalize_coordinates(); f - Dynamical system of Projective Berkovich line over Cp(3) of precision 20 induced by the map - Defn: Defined on coordinates by sending (x : y) to - (x^2 : y^2) + Dynamical system of Projective Berkovich line over Cp(3) of precision 20 + induced by the map + Defn: Defined on coordinates by sending (x : y) to (x^2 : y^2) Normalize_coordinates may sometimes fail over p-adic fields:: sage: g = DynamicalSystem_Berkovich([2*x^2, x*y]) - sage: g.normalize_coordinates() #not tested + sage: g.normalize_coordinates() # not tested Traceback (most recent call last): ... TypeError: unable to coerce since the denominator is not 1 @@ -621,9 +631,9 @@ def normalize_coordinates(self): sage: B = Berkovich_Cp_Projective(P, 3) sage: g = DynamicalSystem_Berkovich([2*x^2, x*y], B) sage: g.normalize_coordinates(); g - Dynamical system of Projective Berkovich line over Cp(3), with base Rational Field induced by the map - Defn: Defined on coordinates by sending (x : y) to - (2*x : y) + Dynamical system of Projective Berkovich line over Cp(3), with base Rational Field + induced by the map + Defn: Defined on coordinates by sending (x : y) to (2*x : y) """ self._system.normalize_coordinates() @@ -655,12 +665,14 @@ def conjugate(self, M, adjugate=False, new_ideal=None): sage: f = DynamicalSystem_projective([x^2 + y^2, 2*y^2]) sage: g = DynamicalSystem_Berkovich(f) sage: g.conjugate(Matrix([[1, 1], [0, 1]])) - Dynamical system of Projective Berkovich line over Cp(3) of precision 20 induced by the map + Dynamical system of Projective Berkovich line over Cp(3) of precision 20 + induced by the map Defn: Defined on coordinates by sending (x : y) to (x^2 + (2 + O(3^20))*x*y : (2 + O(3^20))*y^2) :: + sage: # needs sage.rings.number_field sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_Berkovich([x^2 + y^2, y^2], ideal=5) sage: R. = QQ[] @@ -676,6 +688,7 @@ def conjugate(self, M, adjugate=False, new_ideal=None): the base ring of ``M`` and of this dynamical system are not the same:: + sage: # needs sage.rings.number_field sage: ideal = A.ideal(5).factor()[1][0]; ideal Fractional ideal (2*a + 1) sage: g = f.conjugate(conj, new_ideal=ideal) @@ -719,6 +732,7 @@ def resultant(self, normalize=False): :: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: A. = NumberField(z^3 + 20) sage: P. = ProjectiveSpace(A, 1) @@ -748,7 +762,8 @@ def dehomogenize(self, n): sage: f = DynamicalSystem_projective([x^2 + y^2, x*y + y^2]) sage: g = DynamicalSystem_Berkovich(f) sage: g.dehomogenize(1) - Dynamical system of Affine Berkovich line over Cp(3) of precision 20 induced by the map + Dynamical system of Affine Berkovich line over Cp(3) of precision 20 + induced by the map Defn: Defined on coordinates by sending (x) to ((x^2 + 1 + O(3^20))/(x + 1 + O(3^20))) """ @@ -766,8 +781,8 @@ def __call__(self, x, type_3_pole_check=True): - ``x`` -- a point of projective Berkovich space over ``Cp``. - - type_3_pole_check -- (default ``True``) A bool. WARNING: - changing the value of type_3_pole_check can lead to mathematically + - ``type_3_pole_check`` -- (default ``True``) A bool. WARNING: + changing the value of ``type_3_pole_check`` can lead to mathematically incorrect answers. Only set to ``False`` if there are NO poles of the dynamical system in the disk corresponding to the type III point ``x``. See Examples. @@ -969,8 +984,7 @@ class DynamicalSystem_Berkovich_affine(DynamicalSystem_Berkovich): sage: f = DynamicalSystem_affine([(x^2 + 1)/x]) sage: DynamicalSystem_Berkovich(f) Dynamical system of Affine Berkovich line over Cp(5) of precision 20 induced by the map - Defn: Defined on coordinates by sending (x) to - ((x^2 + 1 + O(5^20))/x) + Defn: Defined on coordinates by sending (x) to ((x^2 + 1 + O(5^20))/x) Dynamical system can be created from a morphism:: @@ -978,8 +992,7 @@ class DynamicalSystem_Berkovich_affine(DynamicalSystem_Berkovich): sage: phi = H([x + 3]) sage: DynamicalSystem_Berkovich(phi) Dynamical system of Affine Berkovich line over Cp(5) of precision 20 induced by the map - Defn: Defined on coordinates by sending (x) to - (x + 3 + O(5^20)) + Defn: Defined on coordinates by sending (x) to (x + 3 + O(5^20)) """ @staticmethod def __classcall_private__(cls, dynamical_system, domain=None): @@ -991,9 +1004,9 @@ def __classcall_private__(cls, dynamical_system, domain=None): sage: A. = AffineSpace(Qp(3), 1) sage: from sage.dynamics.arithmetic_dynamics.berkovich_ds import DynamicalSystem_Berkovich_affine sage: DynamicalSystem_Berkovich_affine(DynamicalSystem_affine(x^2)) - Dynamical system of Affine Berkovich line over Cp(3) of precision 20 induced by the map - Defn: Defined on coordinates by sending (x) to - (x^2) + Dynamical system of Affine Berkovich line over Cp(3) of precision 20 + induced by the map + Defn: Defined on coordinates by sending (x) to (x^2) """ if not isinstance(dynamical_system, DynamicalSystem): if not isinstance(dynamical_system, DynamicalSystem_affine): @@ -1025,9 +1038,9 @@ def __init__(self, dynamical_system, domain): sage: A. = AffineSpace(Qp(3), 1) sage: from sage.dynamics.arithmetic_dynamics.berkovich_ds import DynamicalSystem_Berkovich_affine sage: DynamicalSystem_Berkovich_affine(DynamicalSystem_affine(x^3)) - Dynamical system of Affine Berkovich line over Cp(3) of precision 20 induced by the map - Defn: Defined on coordinates by sending (x) to - (x^3) + Dynamical system of Affine Berkovich line over Cp(3) of precision 20 + induced by the map + Defn: Defined on coordinates by sending (x) to (x^3) """ DynamicalSystem_Berkovich.__init__(self, dynamical_system, domain) @@ -1052,9 +1065,9 @@ def homogenize(self, n): sage: f = DynamicalSystem_affine(1/x) sage: f = DynamicalSystem_Berkovich(f) sage: f.homogenize(1) - Dynamical system of Projective Berkovich line over Cp(3) of precision 20 induced by the map - Defn: Defined on coordinates by sending (x0 : x1) to - (x1 : x0) + Dynamical system of Projective Berkovich line over Cp(3) of precision 20 + induced by the map + Defn: Defined on coordinates by sending (x0 : x1) to (x1 : x0) """ new_system = self._system.homogenize(n) ideal = self.domain().ideal() diff --git a/src/sage/dynamics/arithmetic_dynamics/dynamical_semigroup.py b/src/sage/dynamics/arithmetic_dynamics/dynamical_semigroup.py index 5b324ddbd9a..ebb8702a7db 100644 --- a/src/sage/dynamics/arithmetic_dynamics/dynamical_semigroup.py +++ b/src/sage/dynamics/arithmetic_dynamics/dynamical_semigroup.py @@ -51,13 +51,12 @@ class DynamicalSemigroup(Parent, metaclass=InheritComparisonClasscallMetaclass): sage: P. = ProjectiveSpace(QQ, 1) sage: DynamicalSemigroup(([x, y], [x^2, y^2])) - Dynamical semigroup over Projective Space of dimension 1 over Rational Field defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (x : y) - Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (x^2 : y^2) + Dynamical semigroup over Projective Space of dimension 1 over Rational Field + defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x : y) to (x : y) + Dynamical System of Projective Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x : y) to (x^2 : y^2) :: @@ -65,23 +64,22 @@ class DynamicalSemigroup(Parent, metaclass=InheritComparisonClasscallMetaclass): sage: f = DynamicalSystem([x, y], P) sage: g = DynamicalSystem([x^2, y^2], P) sage: DynamicalSemigroup((f, g)) - Dynamical semigroup over Projective Space of dimension 1 over Rational Field defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (x : y) - Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (x^2 : y^2) + Dynamical semigroup over Projective Space of dimension 1 over Rational Field + defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x : y) to (x : y) + Dynamical System of Projective Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x : y) to (x^2 : y^2) :: sage: A. = AffineSpace(QQ, 1) sage: f = DynamicalSystem_affine(x, A) sage: DynamicalSemigroup(f) - Dynamical semigroup over Affine Space of dimension 1 over Rational Field defined by 1 dynamical system: - Dynamical System of Affine Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x) to - (x) + Dynamical semigroup over Affine Space of dimension 1 over Rational Field + defined by 1 dynamical system: + Dynamical System of Affine Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x) to (x) :: @@ -89,13 +87,12 @@ class DynamicalSemigroup(Parent, metaclass=InheritComparisonClasscallMetaclass): sage: f = DynamicalSystem(x, A) sage: g = DynamicalSystem(x^2, A) sage: DynamicalSemigroup((f, g)) - Dynamical semigroup over Affine Space of dimension 1 over Rational Field defined by 2 dynamical systems: - Dynamical System of Affine Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x) to - (x) - Dynamical System of Affine Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x) to - (x^2) + Dynamical semigroup over Affine Space of dimension 1 over Rational Field + defined by 2 dynamical systems: + Dynamical System of Affine Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x) to (x) + Dynamical System of Affine Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x) to (x^2) :: @@ -104,32 +101,32 @@ class DynamicalSemigroup(Parent, metaclass=InheritComparisonClasscallMetaclass): sage: f = DynamicalSystem_projective([x, y], X) sage: g = DynamicalSystem_projective([x^2, y^2], X) sage: DynamicalSemigroup_projective([f, g]) - Dynamical semigroup over Closed subscheme of Projective Space of dimension 1 over Rational Field defined by: - x - y defined by 2 dynamical systems: - Dynamical System of Closed subscheme of Projective Space of dimension 1 over Rational Field defined by: - x - y - Defn: Defined on coordinates by sending (x : y) to - (x : y) - Dynamical System of Closed subscheme of Projective Space of dimension 1 over Rational Field defined by: - x - y - Defn: Defined on coordinates by sending (x : y) to - (x^2 : y^2) - - If a dynamical semigroup is built from dynamical systems with different base rings, all systems will be coerced - to the largest base ring:: + Dynamical semigroup over Closed subscheme of Projective Space of dimension 1 + over Rational Field defined by: x - y + defined by 2 dynamical systems: + Dynamical System of Closed subscheme of Projective Space of dimension 1 + over Rational Field defined by: x - y + Defn: Defined on coordinates by sending (x : y) to (x : y) + Dynamical System of Closed subscheme of Projective Space of dimension 1 + over Rational Field defined by: x - y + Defn: Defined on coordinates by sending (x : y) to (x^2 : y^2) + + If a dynamical semigroup is built from dynamical systems with different base rings, + all systems will be coerced to the largest base ring:: sage: P. = ProjectiveSpace(QQ, 1) sage: Q. = ProjectiveSpace(RR, 1) sage: f = DynamicalSystem([x, y], P) sage: g = DynamicalSystem([z^2, w^2], Q) sage: DynamicalSemigroup((f, g)) - Dynamical semigroup over Projective Space of dimension 1 over Real Field with 53 bits of precision defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Real Field with 53 bits of precision - Defn: Defined on coordinates by sending (x : y) to - (x : y) - Dynamical System of Projective Space of dimension 1 over Real Field with 53 bits of precision - Defn: Defined on coordinates by sending (x : y) to - (x^2 : y^2) + Dynamical semigroup over Projective Space of dimension 1 over + Real Field with 53 bits of precision defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 + over Real Field with 53 bits of precision + Defn: Defined on coordinates by sending (x : y) to (x : y) + Dynamical System of Projective Space of dimension 1 + over Real Field with 53 bits of precision + Defn: Defined on coordinates by sending (x : y) to (x^2 : y^2) :: @@ -138,17 +135,19 @@ class DynamicalSemigroup(Parent, metaclass=InheritComparisonClasscallMetaclass): sage: f = DynamicalSystem(x, A) sage: g = DynamicalSystem(y^2, B) sage: DynamicalSemigroup((f, g)) - Dynamical semigroup over Affine Space of dimension 1 over Real Field with 53 bits of precision defined by 2 dynamical systems: - Dynamical System of Affine Space of dimension 1 over Real Field with 53 bits of precision - Defn: Defined on coordinates by sending (x) to - (x) - Dynamical System of Affine Space of dimension 1 over Real Field with 53 bits of precision - Defn: Defined on coordinates by sending (x) to - (x^2) + Dynamical semigroup over Affine Space of dimension 1 over + Real Field with 53 bits of precision defined by 2 dynamical systems: + Dynamical System of Affine Space of dimension 1 over + Real Field with 53 bits of precision + Defn: Defined on coordinates by sending (x) to (x) + Dynamical System of Affine Space of dimension 1 over + Real Field with 53 bits of precision + Defn: Defined on coordinates by sending (x) to (x^2) If a dynamical semigroup is built from dynamical systems over number fields, a composite number field is created and all systems will be coerced to it. This composite number field contains all of the initial number fields:: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = NumberField(r^2 - 2) sage: P. = ProjectiveSpace(QQ, 1) @@ -156,16 +155,18 @@ class DynamicalSemigroup(Parent, metaclass=InheritComparisonClasscallMetaclass): sage: f = DynamicalSystem([x, y], P) sage: g = DynamicalSystem([z^2, w^2], Q) sage: DynamicalSemigroup((f, g)) - Dynamical semigroup over Projective Space of dimension 1 over Number Field in k with defining polynomial r^2 - 2 defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Number Field in k with defining polynomial r^2 - 2 - Defn: Defined on coordinates by sending (x : y) to - (x : y) - Dynamical System of Projective Space of dimension 1 over Number Field in k with defining polynomial r^2 - 2 - Defn: Defined on coordinates by sending (x : y) to - (x^2 : y^2) + Dynamical semigroup over Projective Space of dimension 1 over + Number Field in k with defining polynomial r^2 - 2 defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 over + Number Field in k with defining polynomial r^2 - 2 + Defn: Defined on coordinates by sending (x : y) to (x : y) + Dynamical System of Projective Space of dimension 1 over + Number Field in k with defining polynomial r^2 - 2 + Defn: Defined on coordinates by sending (x : y) to (x^2 : y^2) :: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = NumberField(r^2 - 2) sage: L. = NumberField(r^2 - 3) @@ -174,16 +175,19 @@ class DynamicalSemigroup(Parent, metaclass=InheritComparisonClasscallMetaclass): sage: f = DynamicalSystem([x, y], P) sage: g = DynamicalSystem([z^2, w^2], Q) sage: DynamicalSemigroup((f, g)) - Dynamical semigroup over Projective Space of dimension 1 over Number Field in kl with defining polynomial r^4 - 10*r^2 + 1 defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Number Field in kl with defining polynomial r^4 - 10*r^2 + 1 - Defn: Defined on coordinates by sending (x : y) to - (x : y) - Dynamical System of Projective Space of dimension 1 over Number Field in kl with defining polynomial r^4 - 10*r^2 + 1 - Defn: Defined on coordinates by sending (x : y) to - (x^2 : y^2) + Dynamical semigroup over Projective Space of dimension 1 over + Number Field in kl with defining polynomial r^4 - 10*r^2 + 1 + defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 over + Number Field in kl with defining polynomial r^4 - 10*r^2 + 1 + Defn: Defined on coordinates by sending (x : y) to (x : y) + Dynamical System of Projective Space of dimension 1 over + Number Field in kl with defining polynomial r^4 - 10*r^2 + 1 + Defn: Defined on coordinates by sending (x : y) to (x^2 : y^2) :: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = NumberField(r^2 - 2) sage: L. = NumberField(r^2 - 3) @@ -192,102 +196,107 @@ class DynamicalSemigroup(Parent, metaclass=InheritComparisonClasscallMetaclass): sage: f = DynamicalSystem(x, P) sage: g = DynamicalSystem(y^2, Q) sage: DynamicalSemigroup((f, g)) - Dynamical semigroup over Affine Space of dimension 1 over Number Field in kl with defining polynomial r^4 - 10*r^2 + 1 defined by 2 dynamical systems: - Dynamical System of Affine Space of dimension 1 over Number Field in kl with defining polynomial r^4 - 10*r^2 + 1 - Defn: Defined on coordinates by sending (x) to - (x) - Dynamical System of Affine Space of dimension 1 over Number Field in kl with defining polynomial r^4 - 10*r^2 + 1 - Defn: Defined on coordinates by sending (x) to - (x^2) + Dynamical semigroup over Affine Space of dimension 1 over + Number Field in kl with defining polynomial r^4 - 10*r^2 + 1 + defined by 2 dynamical systems: + Dynamical System of Affine Space of dimension 1 over + Number Field in kl with defining polynomial r^4 - 10*r^2 + 1 + Defn: Defined on coordinates by sending (x) to (x) + Dynamical System of Affine Space of dimension 1 over + Number Field in kl with defining polynomial r^4 - 10*r^2 + 1 + Defn: Defined on coordinates by sending (x) to (x^2) A dynamical semigroup may contain dynamical systems over function fields:: - sage: R. = QQ[] - sage: P. = ProjectiveSpace(R, 1) - sage: f = DynamicalSystem([r * x, y], P) - sage: g = DynamicalSystem([x, r * y], P) - sage: DynamicalSemigroup((f, g)) - Dynamical semigroup over Projective Space of dimension 1 over Univariate Polynomial Ring in r over Rational Field defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Univariate Polynomial Ring in r over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (r*x : y) - Dynamical System of Projective Space of dimension 1 over Univariate Polynomial Ring in r over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (x : r*y) + sage: R. = QQ[] + sage: P. = ProjectiveSpace(R, 1) + sage: f = DynamicalSystem([r * x, y], P) + sage: g = DynamicalSystem([x, r * y], P) + sage: DynamicalSemigroup((f, g)) + Dynamical semigroup over Projective Space of dimension 1 over Univariate + Polynomial Ring in r over Rational Field defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 over + Univariate Polynomial Ring in r over Rational Field + Defn: Defined on coordinates by sending (x : y) to (r*x : y) + Dynamical System of Projective Space of dimension 1 over + Univariate Polynomial Ring in r over Rational Field + Defn: Defined on coordinates by sending (x : y) to (x : r*y) - :: + :: - sage: R. = QQ[] - sage: P. = ProjectiveSpace(R, 1) - sage: f = DynamicalSystem([r * x, y], P) - sage: g = DynamicalSystem([x, y], P) - sage: DynamicalSemigroup((f, g)) - Dynamical semigroup over Projective Space of dimension 1 over Univariate Polynomial Ring in r over Rational Field defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Univariate Polynomial Ring in r over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (r*x : y) - Dynamical System of Projective Space of dimension 1 over Univariate Polynomial Ring in r over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (x : y) + sage: R. = QQ[] + sage: P. = ProjectiveSpace(R, 1) + sage: f = DynamicalSystem([r * x, y], P) + sage: g = DynamicalSystem([x, y], P) + sage: DynamicalSemigroup((f, g)) + Dynamical semigroup over Projective Space of dimension 1 over Univariate + Polynomial Ring in r over Rational Field defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 over + Univariate Polynomial Ring in r over Rational Field + Defn: Defined on coordinates by sending (x : y) to (r*x : y) + Dynamical System of Projective Space of dimension 1 over + Univariate Polynomial Ring in r over Rational Field + Defn: Defined on coordinates by sending (x : y) to (x : y) - :: + :: - sage: R. = QQ[] - sage: P. = ProjectiveSpace(R, 1) - sage: f = DynamicalSystem([r * x, y], P) - sage: g = DynamicalSystem([s * x, y], P) - sage: DynamicalSemigroup((f, g)) - Dynamical semigroup over Projective Space of dimension 1 over Multivariate Polynomial Ring in r, s over Rational Field defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Multivariate Polynomial Ring in r, s over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (r*x : y) - Dynamical System of Projective Space of dimension 1 over Multivariate Polynomial Ring in r, s over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (s*x : y) + sage: R. = QQ[] + sage: P. = ProjectiveSpace(R, 1) + sage: f = DynamicalSystem([r * x, y], P) + sage: g = DynamicalSystem([s * x, y], P) + sage: DynamicalSemigroup((f, g)) + Dynamical semigroup over Projective Space of dimension 1 over Multivariate + Polynomial Ring in r, s over Rational Field defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 over + Multivariate Polynomial Ring in r, s over Rational Field + Defn: Defined on coordinates by sending (x : y) to (r*x : y) + Dynamical System of Projective Space of dimension 1 over + Multivariate Polynomial Ring in r, s over Rational Field + Defn: Defined on coordinates by sending (x : y) to (s*x : y) - :: + :: - sage: R. = QQ[] - sage: P. = ProjectiveSpace(R, 1) - sage: f = DynamicalSystem([r * x, s * y], P) - sage: g = DynamicalSystem([s * x, r * y], P) - sage: DynamicalSemigroup((f, g)) - Dynamical semigroup over Projective Space of dimension 1 over Multivariate Polynomial Ring in r, s over Rational Field defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Multivariate Polynomial Ring in r, s over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (r*x : s*y) - Dynamical System of Projective Space of dimension 1 over Multivariate Polynomial Ring in r, s over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (s*x : r*y) + sage: R. = QQ[] + sage: P. = ProjectiveSpace(R, 1) + sage: f = DynamicalSystem([r * x, s * y], P) + sage: g = DynamicalSystem([s * x, r * y], P) + sage: DynamicalSemigroup((f, g)) + Dynamical semigroup over Projective Space of dimension 1 over + Multivariate Polynomial Ring in r, s over Rational Field + defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 over + Multivariate Polynomial Ring in r, s over Rational Field + Defn: Defined on coordinates by sending (x : y) to (r*x : s*y) + Dynamical System of Projective Space of dimension 1 over + Multivariate Polynomial Ring in r, s over Rational Field + Defn: Defined on coordinates by sending (x : y) to (s*x : r*y) A dynamical semigroup may contain dynamical systems over finite fields:: sage: F = FiniteField(5) sage: P. = ProjectiveSpace(F, 1) sage: DynamicalSemigroup(([x, y], [x^2, y^2])) - Dynamical semigroup over Projective Space of dimension 1 over Finite Field of size 5 defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Finite Field of size 5 - Defn: Defined on coordinates by sending (x : y) to - (x : y) - Dynamical System of Projective Space of dimension 1 over Finite Field of size 5 - Defn: Defined on coordinates by sending (x : y) to - (x^2 : y^2) + Dynamical semigroup over Projective Space of dimension 1 over + Finite Field of size 5 defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 over Finite Field of size 5 + Defn: Defined on coordinates by sending (x : y) to (x : y) + Dynamical System of Projective Space of dimension 1 over Finite Field of size 5 + Defn: Defined on coordinates by sending (x : y) to (x^2 : y^2) - If a dynamical semigroup is built from dynamical systems over both projective and affine spaces, all systems - will be homogenized to dynamical systems over projective space:: + If a dynamical semigroup is built from dynamical systems over both projective and + affine spaces, all systems will be homogenized to dynamical systems over projective space:: sage: P. = ProjectiveSpace(QQ, 1) sage: A. = AffineSpace(QQ, 1) sage: f = DynamicalSystem([x, y], P) sage: g = DynamicalSystem(z^2, A) sage: DynamicalSemigroup((f, g)) - Dynamical semigroup over Projective Space of dimension 1 over Rational Field defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (x : y) - Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (x^2 : y^2) + Dynamical semigroup over Projective Space of dimension 1 over Rational Field + defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x : y) to (x : y) + Dynamical System of Projective Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x : y) to (x^2 : y^2) TESTS:: @@ -299,6 +308,7 @@ class DynamicalSemigroup(Parent, metaclass=InheritComparisonClasscallMetaclass): :: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = NumberField(r^2 - 2) sage: P. = ProjectiveSpace(RR, 1) @@ -443,13 +453,14 @@ def change_ring(self, new_ring): sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSemigroup(([x, y], [x^2, y^2])) sage: f.change_ring(RR) - Dynamical semigroup over Projective Space of dimension 1 over Real Field with 53 bits of precision defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Real Field with 53 bits of precision - Defn: Defined on coordinates by sending (x : y) to - (x : y) - Dynamical System of Projective Space of dimension 1 over Real Field with 53 bits of precision - Defn: Defined on coordinates by sending (x : y) to - (x^2 : y^2) + Dynamical semigroup over Projective Space of dimension 1 over + Real Field with 53 bits of precision defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 over + Real Field with 53 bits of precision + Defn: Defined on coordinates by sending (x : y) to (x : y) + Dynamical System of Projective Space of dimension 1 over + Real Field with 53 bits of precision + Defn: Defined on coordinates by sending (x : y) to (x^2 : y^2) """ new_systems = [] for ds in self.defining_systems(): @@ -516,11 +527,9 @@ def defining_systems(self): sage: f = DynamicalSemigroup(([x, y], [x^2, y^2])) sage: f.defining_systems() (Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (x : y), + Defn: Defined on coordinates by sending (x : y) to (x : y), Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (x^2 : y^2)) + Defn: Defined on coordinates by sending (x : y) to (x^2 : y^2)) """ return tuple(self._dynamical_systems) @@ -760,13 +769,12 @@ def specialization(self, assignments): sage: g = DynamicalSystem([x, r * y], P) sage: d = DynamicalSemigroup((f, g)) sage: d.specialization({r:2}) - Dynamical semigroup over Projective Space of dimension 1 over Rational Field defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (2*x : y) - Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (x : 2*y) + Dynamical semigroup over Projective Space of dimension 1 over Rational Field + defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x : y) to (2*x : y) + Dynamical System of Projective Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x : y) to (x : 2*y) :: @@ -776,13 +784,12 @@ def specialization(self, assignments): sage: g = DynamicalSystem([x, y], P) sage: d = DynamicalSemigroup((f, g)) sage: d.specialization({r:2}) - Dynamical semigroup over Projective Space of dimension 1 over Rational Field defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (2*x : y) - Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (x : y) + Dynamical semigroup over Projective Space of dimension 1 over Rational Field + defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x : y) to (2*x : y) + Dynamical System of Projective Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x : y) to (x : y) :: @@ -792,13 +799,12 @@ def specialization(self, assignments): sage: g = DynamicalSystem([s * x, y], P) sage: d = DynamicalSemigroup((f, g)) sage: d.specialization({r:2, s:3}) - Dynamical semigroup over Projective Space of dimension 1 over Rational Field defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (2*x : y) - Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (3*x : y) + Dynamical semigroup over Projective Space of dimension 1 over Rational Field + defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x : y) to (2*x : y) + Dynamical System of Projective Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x : y) to (3*x : y) :: @@ -808,13 +814,15 @@ def specialization(self, assignments): sage: g = DynamicalSystem([s * x, r * y], P) sage: d = DynamicalSemigroup((f, g)) sage: d.specialization({s:3}) - Dynamical semigroup over Projective Space of dimension 1 over Univariate Polynomial Ring in r over Rational Field defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Univariate Polynomial Ring in r over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (r*x : 3*y) - Dynamical System of Projective Space of dimension 1 over Univariate Polynomial Ring in r over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (3*x : r*y) + Dynamical semigroup over Projective Space of dimension 1 over + Univariate Polynomial Ring in r over Rational Field + defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 over + Univariate Polynomial Ring in r over Rational Field + Defn: Defined on coordinates by sending (x : y) to (r*x : 3*y) + Dynamical System of Projective Space of dimension 1 over + Univariate Polynomial Ring in r over Rational Field + Defn: Defined on coordinates by sending (x : y) to (3*x : r*y) """ specialized_systems = [] for ds in self.defining_systems(): @@ -1222,13 +1230,12 @@ class DynamicalSemigroup_projective(DynamicalSemigroup): sage: P. = ProjectiveSpace(QQ, 1) sage: DynamicalSemigroup_projective(([x, y], [x^2, y^2])) - Dynamical semigroup over Projective Space of dimension 1 over Rational Field defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (x : y) - Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (x^2 : y^2) + Dynamical semigroup over Projective Space of dimension 1 over + Rational Field defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x : y) to (x : y) + Dynamical System of Projective Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x : y) to (x^2 : y^2) """ @staticmethod @@ -1282,13 +1289,12 @@ def dehomogenize(self, n): sage: g = DynamicalSystem([x^2, y^2], P) sage: d = DynamicalSemigroup((f, g)) sage: d.dehomogenize(0) - Dynamical semigroup over Affine Space of dimension 1 over Rational Field defined by 2 dynamical systems: - Dynamical System of Affine Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (y) to - (y) - Dynamical System of Affine Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (y) to - (y^2) + Dynamical semigroup over Affine Space of dimension 1 over + Rational Field defined by 2 dynamical systems: + Dynamical System of Affine Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (y) to (y) + Dynamical System of Affine Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (y) to (y^2) :: @@ -1297,13 +1303,12 @@ def dehomogenize(self, n): sage: g = DynamicalSystem([x^2, y^2], P) sage: d = DynamicalSemigroup((f, g)) sage: d.dehomogenize(1) - Dynamical semigroup over Affine Space of dimension 1 over Rational Field defined by 2 dynamical systems: - Dynamical System of Affine Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x) to - (x) - Dynamical System of Affine Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x) to - (x^2) + Dynamical semigroup over Affine Space of dimension 1 over + Rational Field defined by 2 dynamical systems: + Dynamical System of Affine Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x) to (x) + Dynamical System of Affine Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x) to (x^2) TESTS:: @@ -1317,8 +1322,8 @@ def dehomogenize(self, n): ValueError: Scheme morphism: From: Affine Space of dimension 1 over Rational Field To: Affine Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x) to - (1/x) is not a `DynamicalSystem_affine` object + Defn: Defined on coordinates by sending (x) to (1/x) + is not a `DynamicalSystem_affine` object """ new_systems = [] for ds in self.defining_systems(): @@ -1354,13 +1359,12 @@ class DynamicalSemigroup_affine(DynamicalSemigroup): sage: f = DynamicalSystem(x, A) sage: g = DynamicalSystem(x^2, A) sage: DynamicalSemigroup_affine((f, g)) - Dynamical semigroup over Affine Space of dimension 1 over Rational Field defined by 2 dynamical systems: - Dynamical System of Affine Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x) to - (x) - Dynamical System of Affine Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x) to - (x^2) + Dynamical semigroup over Affine Space of dimension 1 over + Rational Field defined by 2 dynamical systems: + Dynamical System of Affine Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x) to (x) + Dynamical System of Affine Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x) to (x^2) """ @staticmethod @@ -1411,13 +1415,12 @@ def homogenize(self, n): sage: g = DynamicalSystem(x^2, A) sage: d = DynamicalSemigroup((f, g)) sage: d.homogenize(1) - Dynamical semigroup over Projective Space of dimension 1 over Rational Field defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x0 : x1) to - (x0 + x1 : x1) - Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x0 : x1) to - (x0^2 : x1^2) + Dynamical semigroup over Projective Space of dimension 1 over Rational Field + defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x0 : x1) to (x0 + x1 : x1) + Dynamical System of Projective Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x0 : x1) to (x0^2 : x1^2) :: @@ -1426,13 +1429,12 @@ def homogenize(self, n): sage: g = DynamicalSystem(x^2, A) sage: d = DynamicalSemigroup((f, g)) sage: d.homogenize((1, 0)) - Dynamical semigroup over Projective Space of dimension 1 over Rational Field defined by 2 dynamical systems: - Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x0 : x1) to - (x1 : x0 + x1) - Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x0 : x1) to - (x1^2 : x0^2) + Dynamical semigroup over Projective Space of dimension 1 over Rational Field + defined by 2 dynamical systems: + Dynamical System of Projective Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x0 : x1) to (x1 : x0 + x1) + Dynamical System of Projective Space of dimension 1 over Rational Field + Defn: Defined on coordinates by sending (x0 : x1) to (x1^2 : x0^2) """ new_systems = [] for ds in self.defining_systems(): @@ -1466,11 +1468,9 @@ def _standardize_domains_of_(systems): sage: g = DynamicalSystem(x^2, B) sage: sage.dynamics.arithmetic_dynamics.dynamical_semigroup._standardize_domains_of_([f, g]) [Dynamical System of Affine Space of dimension 1 over Real Field with 53 bits of precision - Defn: Defined on coordinates by sending (x) to - (x), + Defn: Defined on coordinates by sending (x) to (x), Dynamical System of Affine Space of dimension 1 over Real Field with 53 bits of precision - Defn: Defined on coordinates by sending (x) to - (x^2)] + Defn: Defined on coordinates by sending (x) to (x^2)] """ identical_domains = True for ds in systems: diff --git a/src/sage/dynamics/arithmetic_dynamics/endPN_automorphism_group.py b/src/sage/dynamics/arithmetic_dynamics/endPN_automorphism_group.py index d42d3ca8b2d..c82f10aed0d 100644 --- a/src/sage/dynamics/arithmetic_dynamics/endPN_automorphism_group.py +++ b/src/sage/dynamics/arithmetic_dynamics/endPN_automorphism_group.py @@ -28,39 +28,40 @@ from sage.combinat.subset import Subsets from sage.matrix.constructor import matrix from sage.misc.functional import sqrt +from sage.misc.lazy_import import lazy_import from sage.misc.misc_c import prod from sage.parallel.use_fork import p_iter_fork from sage.rings.finite_rings.finite_field_constructor import GF from sage.rings.finite_rings.integer_mod_ring import Integers from sage.rings.integer_ring import ZZ -from sage.rings.number_field.number_field import NumberField from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing from sage.rings.rational_field import QQ from sage.sets.primes import Primes from sage.sets.set import Set from sage.structure.element import is_Matrix +lazy_import('sage.rings.number_field.number_field', 'NumberField') + def automorphism_group_QQ_fixedpoints(rational_function, return_functions=False, iso_type=False): r""" - - This function will compute the automorphism group for ``rational_function`` via the method of fixed points + Compute the automorphism group for ``rational_function`` via the method of fixed points ALGORITHM: - See Algorithm 3 in Faber-Manes-Viray [FMV]_. + See Algorithm 3 in Faber-Manes-Viray [FMV]_. INPUT: - - ``rational_function`` - Rational Function defined over `\ZZ` or `\QQ` + - ``rational_function`` -- Rational Function defined over `\ZZ` or `\QQ` - - ``return_functions`` - Boolean Value, True will return elements in the automorphism group - as linear fractional transformations. False will return elements as `PGL2` matrices + - ``return_functions`` -- Boolean value; ``True`` will return elements in the automorphism group + as linear fractional transformations. ``False`` will return elements as `PGL_2` matrices - - ``iso_type`` - Boolean - True will cause the classification of the finite automorphism + - ``iso_type`` -- Boolean; ``True`` will cause the classification of the finite automorphism group to also be returned - OUTPUT: a list of automorphisms that make up the Automorphism Group + OUTPUT: a list of automorphisms that make up the automorphism group of ``rational_function`` EXAMPLES:: @@ -69,7 +70,7 @@ def automorphism_group_QQ_fixedpoints(rational_function, return_functions=False, sage: rational_function = (z^2 - 2*z - 2)/(-2*z^2 - 2*z + 1) sage: from sage.dynamics.arithmetic_dynamics.endPN_automorphism_group import automorphism_group_QQ_fixedpoints sage: automorphism_group_QQ_fixedpoints(rational_function, True) - [z, 1/z, -z - 1, -z/(z + 1), (-z - 1)/z, -1/(z + 1)] + [z, 1/z, -z - 1, -z/(z + 1), (-z - 1)/z, -1/(z + 1)] :: @@ -77,18 +78,18 @@ def automorphism_group_QQ_fixedpoints(rational_function, return_functions=False, sage: rational_function = (z^2 + 2*z)/(-2*z - 1) sage: from sage.dynamics.arithmetic_dynamics.endPN_automorphism_group import automorphism_group_QQ_fixedpoints sage: automorphism_group_QQ_fixedpoints(rational_function) - [ + [ [1 0] [-1 -1] [-2 0] [0 2] [-1 -1] [ 0 -1] [0 1], [ 0 1], [ 2 2], [2 0], [ 1 0], [ 1 1] - ] + ] :: sage: F. = PolynomialRing(QQ) - sage: rational_function = (z^2 - 4*z -3)/(-3*z^2 - 2*z + 2) + sage: rational_function = (z^2 - 4*z - 3)/(-3*z^2 - 2*z + 2) sage: from sage.dynamics.arithmetic_dynamics.endPN_automorphism_group import automorphism_group_QQ_fixedpoints sage: automorphism_group_QQ_fixedpoints(rational_function, True, True) - ([z, (-z - 1)/z, -1/(z + 1)], 'Cyclic of order 3') + ([z, (-z - 1)/z, -1/(z + 1)], 'Cyclic of order 3') """ if rational_function.parent().is_field(): @@ -304,7 +305,7 @@ def height_bound(polynomial): EXAMPLES:: sage: R. = PolynomialRing(QQ) - sage: f = (z^3+2*z+6) + sage: f = z^3 + 2*z + 6 sage: from sage.dynamics.arithmetic_dynamics.endPN_automorphism_group import height_bound sage: height_bound(f) 413526 @@ -345,7 +346,7 @@ def PGL_repn(rational_function): EXAMPLES:: sage: R. = PolynomialRing(QQ) - sage: f = ((2*z-1)/(3-z)) + sage: f = (2*z-1)/(3-z) sage: from sage.dynamics.arithmetic_dynamics.endPN_automorphism_group import PGL_repn sage: PGL_repn(f) [-2 1] @@ -377,7 +378,7 @@ def PGL_order(A): EXAMPLES:: - sage: M = matrix([[0,2],[2,0]]) + sage: M = matrix([[0,2], [2,0]]) sage: from sage.dynamics.arithmetic_dynamics.endPN_automorphism_group import PGL_order sage: PGL_order(M) 2 @@ -418,7 +419,7 @@ def CRT_helper(automorphisms, moduli): EXAMPLES:: sage: from sage.dynamics.arithmetic_dynamics.endPN_automorphism_group import CRT_helper - sage: CRT_helper([[matrix([[4,0],[0,1]]), matrix([[0,1],[1,0]])]],[5]) + sage: CRT_helper([[matrix([[4,0], [0,1]]), matrix([[0,1], [1,0]])]], [5]) ([ [4 0] [0 1] [0 1], [1 0] @@ -452,7 +453,7 @@ def CRT_automorphisms(automorphisms, order_elts, degree, moduli): Given a list of automorphisms over various `Zmod(p^k)`, a list of the elements orders, an integer degree, and a list of the `p^k` values compute - a maximal list of automorphisms over `Zmod(M)`, such that for every `j` in `len(moduli)`, + a maximal list of automorphisms over `Zmod(M)`, such that for every `j` in ``len(moduli)``, each element reduces mod ``moduli[j]`` to one of the elements in ``automorphisms[j]`` that has order = ``degree`` @@ -462,7 +463,7 @@ def CRT_automorphisms(automorphisms, order_elts, degree, moduli): - ``order_elts`` -- a list of lists of the orders of the elements of ``automorphisms`` - - ``degree`` - a positive integer + - ``degree`` -- a positive integer - ``moduli`` -- list of prime powers, i.e., `p^k` @@ -470,7 +471,7 @@ def CRT_automorphisms(automorphisms, order_elts, degree, moduli): EXAMPLES:: - sage: aut = [[matrix([[1,0],[0,1]]), matrix([[0,1],[1,0]])]] + sage: aut = [[matrix([[1,0], [0,1]]), matrix([[0,1], [1,0]])]] sage: ords = [[1,2]] sage: degree = 2 sage: mods = [5] @@ -506,7 +507,7 @@ def valid_automorphisms(automorphisms_CRT, rational_function, ht_bound, M, - ``rational_function`` -- A one variable rational function - - ``ht_bound`` - a positive integer + - ``ht_bound`` -- a positive integer - ``M`` -- a positive integer, a product of prime powers @@ -519,7 +520,7 @@ def valid_automorphisms(automorphisms_CRT, rational_function, ht_bound, M, sage: R. = PolynomialRing(QQ) sage: F = z^2 sage: from sage.dynamics.arithmetic_dynamics.endPN_automorphism_group import valid_automorphisms - sage: valid_automorphisms([matrix(GF(5),[[0,1],[1,0]])], F, 48, 5, True) + sage: valid_automorphisms([matrix(GF(5), [[0,1],[1,0]])], F, 48, 5, True) [1/z] """ z = rational_function.parent().gen(0) @@ -570,8 +571,8 @@ def remove_redundant_automorphisms(automorphisms, order_elts, moduli, integral_a EXAMPLES:: sage: auts = [[matrix([[1,0],[0,1]]), matrix([[6,0],[0,1]]), matrix([[0,1],[1,0]]), - ....: matrix([[6,1],[1,1]]), matrix([[1,1],[1,6]]), matrix([[0,6],[1,0]]), - ....: matrix([[1,6],[1,1]]), matrix([[6,6],[1,6]])]] + ....: matrix([[6,1],[1,1]]), matrix([[1,1],[1,6]]), matrix([[0,6],[1,0]]), + ....: matrix([[1,6],[1,1]]), matrix([[6,6],[1,6]])]] sage: ord_elts = [[1, 2, 2, 2, 2, 2, 4, 4]] sage: mods = [7] sage: R. = PolynomialRing(QQ) @@ -625,15 +626,15 @@ def automorphism_group_QQ_CRT(rational_function, prime_lower_bound=4, return_fun INPUT: - - ``rational_function`` - a rational function of a univariate polynomial ring over `\QQ` + - ``rational_function`` -- a rational function of a univariate polynomial ring over `\QQ` - - ``prime_lower_bound`` -- (default: 4) a positive integer - a lower bound for the primes to use for + - ``prime_lower_bound`` -- (default: 4) a positive integer; a lower bound for the primes to use for the Chinese Remainder Theorem step - - ``return_functions`` -- (default: True) boolean - True returns linear fractional transformations + - ``return_functions`` -- (default: ``True``) boolean; ``True`` returns linear fractional transformations False returns elements of `PGL(2,\QQ)` - - ``iso_type`` -- (default: False) boolean - True returns the isomorphism type of the automorphism group + - ``iso_type`` -- (default: ``False``) boolean; ``True`` returns the isomorphism type of the automorphism group OUTPUT: a complete list of automorphisms of ``rational_function`` @@ -839,11 +840,11 @@ def automorphism_group_FF(rational_function, absolute=False, iso_type=False, ret - ``rational_function`` -- a rational function defined over the fraction field of a polynomial ring in one variable with finite field coefficients - - ``absolute``-- (default: False) boolean - True returns the absolute automorphism group and a field of definition + - ``absolute``-- (default: ``False``) boolean; ``True`` returns the absolute automorphism group and a field of definition - - ``iso_type`` -- (default: False) boolean - True returns the isomorphism type of the automorphism group + - ``iso_type`` -- (default: ``False``) boolean; ``True`` returns the isomorphism type of the automorphism group - - ``return_functions`` -- (default: False) boolean, True returns linear fractional transformations + - ``return_functions`` -- (default: ``False``) boolean; ``True`` returns linear fractional transformations False returns elements of `PGL(2)` OUTPUT: a list of automorphisms of ``rational_function`` @@ -899,9 +900,9 @@ def automorphism_group_FF(rational_function, absolute=False, iso_type=False, ret def field_descent(sigma, y): r""" - Function for descending an element in a field E to a subfield F. + Function for descending an element in a field `E` to a subfield `F`. - Here F, E must be finite fields or number fields. This function determines + Here `F`, `E` must be finite fields or number fields. This function determines the unique image of subfield which is ``y`` by the embedding ``sigma`` if it exists. Otherwise returns ``None``. This functionality is necessary because Sage does not keep track of subfields. @@ -961,7 +962,7 @@ def rational_function_coefficient_descent(rational_function, sigma, poly_ring): Here `F`, `E` must be finite fields or number fields. It determines the unique rational function in fraction field of - ``poly_ring`` which is the image of ``rational_function`` by ``ssigma``, + ``poly_ring`` which is the image of ``rational_function`` by ``sigma``, if it exists, and otherwise returns ``None``. INPUT: @@ -1061,7 +1062,7 @@ def rational_function_reduce(rational_function): - ``rational_function`` -- rational function `= F/G` in univariate polynomial ring - OUTPUT: rational function -- `(F/gcd(F,G) ) / (G/gcd(F,G))` + OUTPUT: rational function -- `(F/\gcd(F,G)) / (G/\gcd(F,G))` EXAMPLES:: @@ -1157,7 +1158,7 @@ def automorphism_group_FF_alg2(rational_function): INPUT: - - ``rational_function``--a rational function defined over a finite field + - ``rational_function`` -- a rational function defined over a finite field OUTPUT: absolute automorphism group of ``rational_function`` and a ring of definition @@ -1272,9 +1273,9 @@ def order_p_automorphisms(rational_function, pre_image): INPUT: - - ``rational_function``--rational function defined over finite field `F` + - ``rational_function`` -- rational function defined over finite field `F` - - ``pre_image``--set of triples `[x, L, f]`, where `x` is an `F`-rational + - ``pre_image`` -- set of triples `[x, L, f]`, where `x` is an `F`-rational fixed point of ``rational_function``, `L` is the list of `F`-rational pre-images of `x` (excluding `x`), and `f` is the polynomial defining the full set of pre-images of `x` (again excluding `x` itself) @@ -1455,11 +1456,11 @@ def automorphisms_fixing_pair(rational_function, pair, quad): INPUT: - - ``rational_function``-- rational function defined over finite field `E` + - ``rational_function`` -- rational function defined over finite field `E` - - ``pair``-- a pair of points of `\mathbb{P}^1(E)` + - ``pair`` -- a pair of points of `\mathbb{P}^1(E)` - - ``quad``-- Boolean: an indicator if this is a quadratic pair of points + - ``quad`` -- Boolean: an indicator if this is a quadratic pair of points OUTPUT: set of automorphisms with order prime to characteristic defined over `E` that fix the pair, excluding the identity @@ -1535,14 +1536,14 @@ def automorphism_group_FF_alg3(rational_function): INPUT: - - ``rational_function``--a rational function defined over a finite field `F` + - ``rational_function`` -- a rational function defined over a finite field `F` OUTPUT: list of `F`-rational automorphisms of ``rational_function`` EXAMPLES:: sage: R. = PolynomialRing(GF(5^3,'t')) - sage: f = (3456*z^4) + sage: f = 3456*z^4 sage: from sage.dynamics.arithmetic_dynamics.endPN_automorphism_group import automorphism_group_FF_alg3 sage: automorphism_group_FF_alg3(f) [z, 1/z] @@ -1694,14 +1695,14 @@ def automorphism_group_FF_alg3(rational_function): def which_group(list_of_elements): r""" - Given a finite subgroup of `PGL2` determine its isomorphism class. + Given a finite subgroup of `PGL_2` determine its isomorphism class. This function makes heavy use of the classification of finite subgroups of `PGL(2,K)`. INPUT: - ``list_of_elements``-- a finite list of elements of `PGL(2,K)` - that we know a priori form a group + that we know a priori form a group OUTPUT: a string -- the isomorphism type of the group @@ -1844,9 +1845,10 @@ def conjugating_set_initializer(f, g): ``possible_targets`` tracks multiplier information:: sage: P. = ProjectiveSpace(QQ, 2) - sage: f = DynamicalSystem([(8*x^7 - 35*x^4*y^3 - 35*x^4*z^3 - 7*x*y^6 - 140*x*y^3*z^3 \ - - 7*x*z^6), (-7*x^6*y - 35*x^3*y^4 - 140*x^3*y*z^3 + 8*y^7 - 35*y^4*z^3 \ - - 7*y*z^6), -7*x^6*z - 140*x^3*y^3*z - 35*x^3*z^4 - 7*y^6*z - 35*y^3*z^4 + 8*z^7]) + sage: f = DynamicalSystem([ + ....: 8*x^7 - 35*x^4*y^3 - 35*x^4*z^3 - 7*x*y^6 - 140*x*y^3*z^3 - 7*x*z^6, + ....: -7*x^6*y - 35*x^3*y^4 - 140*x^3*y*z^3 + 8*y^7 - 35*y^4*z^3 - 7*y*z^6, + ....: -7*x^6*z - 140*x^3*y^3*z - 35*x^3*z^4 - 7*y^6*z - 35*y^3*z^4 + 8*z^7]) sage: from sage.dynamics.arithmetic_dynamics.endPN_automorphism_group import conjugating_set_initializer sage: source, possible_targets = conjugating_set_initializer(f, f) sage: P.is_linearly_independent(source, 3) diff --git a/src/sage/dynamics/arithmetic_dynamics/endPN_minimal_model.py b/src/sage/dynamics/arithmetic_dynamics/endPN_minimal_model.py index 58df10c4a4c..9a2e5fd6e15 100644 --- a/src/sage/dynamics/arithmetic_dynamics/endPN_minimal_model.py +++ b/src/sage/dynamics/arithmetic_dynamics/endPN_minimal_model.py @@ -22,6 +22,9 @@ # https://www.gnu.org/licenses/ # **************************************************************************** +from copy import copy + +from sage.arith.misc import gcd from sage.functions.hyperbolic import cosh from sage.matrix.constructor import matrix from sage.matrix.matrix_space import MatrixSpace @@ -33,9 +36,7 @@ from sage.rings.polynomial.binary_form_reduce import covariant_z0, epsinv from sage.rings.rational_field import QQ from sage.schemes.affine.affine_space import AffineSpace -from sage.symbolic.constants import e -from sage.arith.misc import gcd -from copy import copy + def bCheck(c, v, p, b): r""" @@ -89,7 +90,7 @@ def scale(c, v, p): - ``c`` -- an integer polynomial - - ``v`` -- an integer - the bound on the exponent from blift + - ``v`` -- an integer; the bound on the exponent from :func:`blift` - ``p`` -- a prime @@ -151,8 +152,8 @@ def blift(LF, Li, p, k, S=None, all_orbits=False): sage: R. = PolynomialRing(QQ) sage: from sage.dynamics.arithmetic_dynamics.endPN_minimal_model import blift - sage: blift([8*b^3 + 12*b^2 + 6*b + 1, 48*b^2 + 483*b + 117, 72*b + 1341,\ - ....: -24*b^2 + 411*b + 99, -144*b + 1233, -216*b], 2, 3, 2) + sage: blift([8*b^3 + 12*b^2 + 6*b + 1, 48*b^2 + 483*b + 117, 72*b + 1341, + ....: -24*b^2 + 411*b + 99, -144*b + 1233, -216*b], 2, 3, 2) [[True, 4]] """ @@ -244,8 +245,7 @@ def affine_minimal(vp, return_transformation=False, D=None, quick=False): sage: affine_minimal(vp, True) ( Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (X : Y) to - (X^2 + Y^2 : X*Y) + Defn: Defined on coordinates by sending (X : Y) to (X^2 + Y^2 : X*Y) , [3 0] [0 1] @@ -330,16 +330,16 @@ def affine_minimal(vp, return_transformation=False, D=None, quick=False): def Min(Fun, p, ubRes, conj, all_orbits=False): r""" - Local loop for Affine_minimal, where we check minimality at the prime p. + Local loop for :func:`affine_minimal`, where we check minimality at the prime `p`. - First we bound the possible k in our transformations A = zp^k + b. + First we bound the possible `k` in our transformations `A = zp^k + b`. See Theorems 3.3.2 and 3.3.3 in [Molnar]_. INPUT: - ``Fun`` -- a dynamical system on projective space - - ``p`` - a prime + - ``p`` -- a prime - ``ubRes`` -- integer, the upper bound needed for Th. 3.3.3 in [Molnar]_ @@ -357,7 +357,8 @@ def Min(Fun, p, ubRes, conj, all_orbits=False): EXAMPLES:: sage: P. = ProjectiveSpace(QQ, 1) - sage: f = DynamicalSystem_projective([149*x^2 + 39*x*y + y^2, -8*x^2 + 137*x*y + 33*y^2]) + sage: f = DynamicalSystem_projective([149*x^2 + 39*x*y + y^2, + ....: -8*x^2 + 137*x*y + 33*y^2]) sage: from sage.dynamics.arithmetic_dynamics.endPN_minimal_model import Min sage: Min(f, 3, -27000000, matrix(QQ,[[1, 0],[0, 1]])) [ @@ -941,6 +942,8 @@ def get_bound_dynamical(F, f, m=1, dynatomic=True, prec=53, emb=None): sage: get_bound_dynamical(f.dynatomic_polynomial(1), f) 35.5546923182219 """ + from sage.symbolic.constants import e + def coshdelta(z): #The cosh of the hyperbolic distance from z = t+uj to j return (z.norm() + 1)/(2*z.imag()) @@ -998,7 +1001,7 @@ def smallest_dynamical(f, dynatomic=True, start_n=1, prec=53, emb=None, algorith - ``dynatomic`` -- boolean. whether ``F`` is the periodic points or the formal periodic points of period ``m`` for ``f`` - - ``start_n`` - positive integer. the period used to start trying to + - ``start_n`` -- positive integer. the period used to start trying to create associate binary form ``F`` - ``prec``-- positive integer. precision to use in CC @@ -1010,7 +1013,7 @@ def smallest_dynamical(f, dynatomic=True, start_n=1, prec=53, emb=None, algorith properties of the map are utilized to choose how to compute minimal orbit representatives - - ``check_minimal`` -- (default: True), boolean, whether to check + - ``check_minimal`` -- (default: ``True``), boolean, whether to check if this map is a minimal model OUTPUT: pair [dynamical system, matrix] @@ -1020,7 +1023,7 @@ def smallest_dynamical(f, dynatomic=True, start_n=1, prec=53, emb=None, algorith sage: from sage.dynamics.arithmetic_dynamics.endPN_minimal_model import smallest_dynamical sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem([50*x^2 + 795*x*y + 2120*y^2, 265*x^2 + 106*y^2]) - sage: smallest_dynamical(f) #long time + sage: smallest_dynamical(f) # long time [ Dynamical System of Projective Space of dimension 1 over Rational Field Defn: Defined on coordinates by sending (x : y) to @@ -1030,6 +1033,8 @@ def smallest_dynamical(f, dynatomic=True, start_n=1, prec=53, emb=None, algorith [0 1] ] """ + from sage.symbolic.constants import e + def insert_item(pts, item, index): # binary insertion to maintain list of points left to consider N = len(pts) diff --git a/src/sage/dynamics/arithmetic_dynamics/generic_ds.py b/src/sage/dynamics/arithmetic_dynamics/generic_ds.py index d09b15ab78c..0afff17895c 100644 --- a/src/sage/dynamics/arithmetic_dynamics/generic_ds.py +++ b/src/sage/dynamics/arithmetic_dynamics/generic_ds.py @@ -27,17 +27,21 @@ class initialization directly. # http://www.gnu.org/licenses/ #***************************************************************************** +from copy import copy + from sage.categories.homset import End from sage.misc.inherit_comparison import InheritComparisonClasscallMetaclass -from sage.schemes.generic.morphism import SchemeMorphism_polynomial +from sage.misc.lazy_import import lazy_import +from sage.rings.finite_rings.finite_field_base import FiniteField +from sage.rings.rational_field import QQ from sage.schemes.affine.affine_space import is_AffineSpace from sage.schemes.affine.affine_subscheme import AlgebraicScheme_subscheme_affine -from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField_generic -from sage.rings.finite_rings.finite_field_base import FiniteField -from sage.rings.qqbar import AlgebraicField_common from sage.schemes.berkovich.berkovich_space import is_Berkovich_Cp -from sage.rings.rational_field import QQ -from copy import copy +from sage.schemes.generic.morphism import SchemeMorphism_polynomial + +lazy_import('sage.rings.algebraic_closure_finite_field', 'AlgebraicClosureFiniteField_generic') +lazy_import('sage.rings.qqbar', 'AlgebraicField_common') + class DynamicalSystem(SchemeMorphism_polynomial, metaclass=InheritComparisonClasscallMetaclass): @@ -78,14 +82,14 @@ class DynamicalSystem(SchemeMorphism_polynomial, EXAMPLES:: sage: A. = AffineSpace(QQ,1) - sage: f = DynamicalSystem_affine([x^2+1]) + sage: f = DynamicalSystem_affine([x^2 + 1]) sage: type(f) :: sage: P. = ProjectiveSpace(QQ,1) - sage: f = DynamicalSystem_projective([x^2+y^2, y^2]) + sage: f = DynamicalSystem_projective([x^2 + y^2, y^2]) sage: type(f) @@ -96,8 +100,7 @@ class DynamicalSystem(SchemeMorphism_polynomial, sage: DynamicalSystem(H([y, x])) Dynamical System of Projective Space of dimension 1 over Complex Field with 53 bits of precision - Defn: Defined on coordinates by sending (x : y) to - (y : x) + Defn: Defined on coordinates by sending (x : y) to (y : x) :class:`DynamicalSystem` defaults to projective:: @@ -109,16 +112,14 @@ class DynamicalSystem(SchemeMorphism_polynomial, :: - sage: A. = AffineSpace(QQ, 2) - sage: DynamicalSystem([y, x], domain=A) - Dynamical System of Affine Space of dimension 2 over Rational Field - Defn: Defined on coordinates by sending (x, y) to - (y, x) - sage: H = End(A) - sage: DynamicalSystem(H([y, x])) - Dynamical System of Affine Space of dimension 2 over Rational Field - Defn: Defined on coordinates by sending (x, y) to - (y, x) + sage: A. = AffineSpace(QQ, 2) + sage: DynamicalSystem([y, x], domain=A) + Dynamical System of Affine Space of dimension 2 over Rational Field + Defn: Defined on coordinates by sending (x, y) to (y, x) + sage: H = End(A) + sage: DynamicalSystem(H([y, x])) + Dynamical System of Affine Space of dimension 2 over Rational Field + Defn: Defined on coordinates by sending (x, y) to (y, x) Note that ``domain`` is ignored if an endomorphism is passed in:: @@ -134,9 +135,12 @@ class DynamicalSystem(SchemeMorphism_polynomial, sage: P. = ProjectiveSpace(ZZ, 1) sage: DynamicalSystem([CC.0*x^2, 4/5*y^2]) - Dynamical System of Projective Space of dimension 1 over Complex Field with 53 bits of precision + Dynamical System of + Projective Space of dimension 1 over Complex Field with 53 bits of precision Defn: Defined on coordinates by sending (x : y) to (1.00000000000000*I*x^2 : 0.800000000000000*y^2) + + sage: # needs sage.rings.finite_rings sage: P. = ProjectiveSpace(GF(5), 1) sage: K. = GF(25) sage: DynamicalSystem([GF(5)(3)*x^2, K(t)*y^2]) @@ -179,7 +183,7 @@ def __init__(self, polys_or_rat_fncts, domain): sage: from sage.dynamics.arithmetic_dynamics.generic_ds import DynamicalSystem sage: P. = ProjectiveSpace(QQ,1) - sage: f = DynamicalSystem_projective([x^2+y^2, y^2]) + sage: f = DynamicalSystem_projective([x^2 + y^2, y^2]) sage: isinstance(f, DynamicalSystem) True """ @@ -239,7 +243,7 @@ def as_scheme_morphism(self): :: sage: P. = ProjectiveSpace(QQ, 1) - sage: f = DynamicalSystem_projective([x^2-y^2, y^2]) + sage: f = DynamicalSystem_projective([x^2 - y^2, y^2]) sage: type(f.as_scheme_morphism()) @@ -253,21 +257,21 @@ def as_scheme_morphism(self): :: sage: A. = AffineSpace(ZZ, 2) - sage: f = DynamicalSystem_affine([x^2-2, y^2]) + sage: f = DynamicalSystem_affine([x^2 - 2, y^2]) sage: type(f.as_scheme_morphism()) :: sage: A. = AffineSpace(QQ, 2) - sage: f = DynamicalSystem_affine([x^2-2, y^2]) + sage: f = DynamicalSystem_affine([x^2 - 2, y^2]) sage: type(f.as_scheme_morphism()) :: sage: A. = AffineSpace(GF(3), 2) - sage: f = DynamicalSystem_affine([x^2-2, y^2]) + sage: f = DynamicalSystem_affine([x^2 - 2, y^2]) sage: type(f.as_scheme_morphism()) """ @@ -295,8 +299,7 @@ def change_ring(self, R, check=True): sage: f = DynamicalSystem_projective([3*x^2, y^2]) sage: f.change_ring(GF(5)) Dynamical System of Projective Space of dimension 1 over Finite Field of size 5 - Defn: Defined on coordinates by sending (x : y) to - (-2*x^2 : y^2) + Defn: Defined on coordinates by sending (x : y) to (-2*x^2 : y^2) """ f = self.as_scheme_morphism() F = f.change_ring(R) @@ -325,11 +328,10 @@ def specialization(self, D=None, phi=None, homset=None): sage: R. = PolynomialRing(QQ) sage: P. = ProjectiveSpace(R, 1) - sage: f = DynamicalSystem_projective([x^2 + c*y^2,y^2], domain=P) + sage: f = DynamicalSystem_projective([x^2 + c*y^2, y^2], domain=P) sage: f.specialization({c:1}) Dynamical System of Projective Space of dimension 1 over Rational Field - Defn: Defined on coordinates by sending (x : y) to - (x^2 + y^2 : y^2) + Defn: Defined on coordinates by sending (x : y) to (x^2 + y^2 : y^2) """ F = self.as_scheme_morphism().specialization(D, phi, homset) return F.as_dynamical_system() @@ -362,8 +364,9 @@ def field_of_definition_critical(self, return_embedding=False, simplify_all=Fals EXAMPLES: - Note that the number of critical points is 2d-2, but (1:0) has multiplicity 2 in this case:: + Note that the number of critical points is `2d-2`, but `(1:0)` has multiplicity 2 in this case:: + sage: # needs sage.libs.singular sage.rings.number_field sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem([1/3*x^3 + x*y^2, y^3], domain=P) sage: f.critical_points() @@ -376,6 +379,7 @@ def field_of_definition_critical(self, return_embedding=False, simplify_all=Fals :: + sage: # needs sage.libs.singular sage.rings.number_field sage: A. = AffineSpace(QQ, 1) sage: f = DynamicalSystem([z^4 + 2*z^2 + 2], domain=A) sage: K. = f.field_of_definition_critical(); K @@ -383,6 +387,7 @@ def field_of_definition_critical(self, return_embedding=False, simplify_all=Fals :: + sage: # needs sage.libs.singular sage.rings.finite_rings sage: G. = GF(9) sage: R. = G[] sage: R.irreducible_element(3, algorithm='first_lexicographic') @@ -392,10 +397,11 @@ def field_of_definition_critical(self, return_embedding=False, simplify_all=Fals sage: f[0].derivative(x).univariate_polynomial().is_irreducible() True sage: f.field_of_definition_critical(return_embedding=True, names='b') - (Finite Field in b of size 3^6, Ring morphism: - From: Finite Field in a of size 3^2 - To: Finite Field in b of size 3^6 - Defn: a |--> 2*b^5 + 2*b^3 + b^2 + 2*b + 2) + (Finite Field in b of size 3^6, + Ring morphism: + From: Finite Field in a of size 3^2 + To: Finite Field in b of size 3^6 + Defn: a |--> 2*b^5 + 2*b^3 + b^2 + 2*b + 2) """ ds = copy(self) space = ds.domain().ambient_space() @@ -469,13 +475,14 @@ def field_of_definition_periodic(self, n, formal=False, return_embedding=False, EXAMPLES:: + sage: # needs sage.libs.singular sage.rings.number_field sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem([x^2, y^2], domain=P) sage: f.periodic_points(3, minimal=False) [(0 : 1), (1 : 0), (1 : 1)] sage: N. = f.field_of_definition_periodic(3); N Number Field in a with defining polynomial x^6 + x^5 + x^4 + x^3 + x^2 + x + 1 - sage: sorted(f.periodic_points(3,minimal=False, R=N), key=str) + sage: sorted(f.periodic_points(3, minimal=False, R=N), key=str) [(-a^5 - a^4 - a^3 - a^2 - a - 1 : 1), (0 : 1), (1 : 0), @@ -488,6 +495,7 @@ def field_of_definition_periodic(self, n, formal=False, return_embedding=False, :: + sage: # needs sage.libs.singular sage.rings.number_field sage: A. = AffineSpace(QQ, 1) sage: f = DynamicalSystem([(z^2 + 1)/(2*z + 1)], domain=A) sage: K. = f.field_of_definition_periodic(2); K @@ -497,6 +505,7 @@ def field_of_definition_periodic(self, n, formal=False, return_embedding=False, :: + sage: # needs sage.rings.finite_rings sage: G. = GF(4) sage: A. = AffineSpace(G, 1) sage: f = DynamicalSystem([x^2 + (a+1)*x + 1], domain=A) @@ -504,10 +513,11 @@ def field_of_definition_periodic(self, n, formal=False, return_embedding=False, sage: (g-x).univariate_polynomial().factor() (x + 1) * (x + a + 1) * (x^2 + a*x + 1) sage: f.field_of_definition_periodic(2, return_embedding=True, names='b') - (Finite Field in b of size 2^4, Ring morphism: - From: Finite Field in a of size 2^2 - To: Finite Field in b of size 2^4 - Defn: a |--> b^2 + b) + (Finite Field in b of size 2^4, + Ring morphism: + From: Finite Field in a of size 2^2 + To: Finite Field in b of size 2^4 + Defn: a |--> b^2 + b) """ ds = copy(self) n = int(n) @@ -587,14 +597,16 @@ def field_of_definition_preimage(self, point, n, return_embedding=False, simplif sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem([1/3*x^2 + 2/3*x*y, x^2 - 2*y^2], domain=P) - sage: N. = f.field_of_definition_preimage(P(1,1), 2, simplify_all=True); N - Number Field in a with defining polynomial x^8 - 4*x^7 - 128*x^6 + 398*x^5 + 3913*x^4 - 8494*x^3 - 26250*x^2 + 30564*x - 2916 + sage: N. = f.field_of_definition_preimage(P(1,1), 2, # needs sage.rings.number_field + ....: simplify_all=True); N + Number Field in a with defining polynomial + x^8 - 4*x^7 - 128*x^6 + 398*x^5 + 3913*x^4 - 8494*x^3 - 26250*x^2 + 30564*x - 2916 :: sage: A. = AffineSpace(QQ, 1) sage: f = DynamicalSystem([z^2], domain=A) - sage: K. = f.field_of_definition_preimage(A(1), 3); K + sage: K. = f.field_of_definition_preimage(A(1), 3); K # needs sage.rings.number_field Number Field in a with defining polynomial z^4 + 1 :: @@ -602,11 +614,13 @@ def field_of_definition_preimage(self, point, n, return_embedding=False, simplif sage: G = GF(5) sage: P. = ProjectiveSpace(G, 1) sage: f = DynamicalSystem([x^2 + 2*y^2, y^2], domain=P) - sage: f.field_of_definition_preimage(P(2,1), 2, return_embedding=True, names='a') - (Finite Field in a of size 5^2, Ring morphism: - From: Finite Field of size 5 - To: Finite Field in a of size 5^2 - Defn: 1 |--> 1) + sage: f.field_of_definition_preimage(P(2,1), 2, return_embedding=True, # needs sage.rings.number_field + ....: names='a') + (Finite Field in a of size 5^2, + Ring morphism: + From: Finite Field of size 5 + To: Finite Field in a of size 5^2 + Defn: 1 |--> 1) """ ds = copy(self) n = int(n) diff --git a/src/sage/dynamics/arithmetic_dynamics/product_projective_ds.py b/src/sage/dynamics/arithmetic_dynamics/product_projective_ds.py index 9d6836c1e36..44565197717 100644 --- a/src/sage/dynamics/arithmetic_dynamics/product_projective_ds.py +++ b/src/sage/dynamics/arithmetic_dynamics/product_projective_ds.py @@ -1,7 +1,7 @@ r""" Dynamical systems for products of projective spaces -This class builds on the prouct projective space class. +This class builds on the product projective space class. The main constructor functions are given by ``DynamicalSystem`` and ``DynamicalSystem_projective``. The constructors function can take either polynomials or a morphism from which to construct a dynamical system. @@ -47,19 +47,18 @@ class DynamicalSystem_product_projective(DynamicalSystem, INPUT: - - ``polys`` -- a list of ``n_1 + \cdots + n_r`` multi-homogeneous polynomials, all + - ``polys`` -- a list of `n_1 + \cdots + n_r` multi-homogeneous polynomials, all of which should have the same parent - ``domain`` -- a projective scheme embedded in - ``P^{n_1-1} \times \cdots \times P^{n_r-1}`` + `P^{n_1-1} \times \cdots \times P^{n_r-1}` EXAMPLES:: sage: T. = ProductProjectiveSpaces([2, 1], QQ) sage: DynamicalSystem_projective([x^2, y^2, z^2, w^2, u^2], domain=T) Dynamical System of Product of projective spaces P^2 x P^1 over Rational Field - Defn: Defined by sending (x : y : z , w : u) to - (x^2 : y^2 : z^2 , w^2 : u^2). + Defn: Defined by sending (x : y : z , w : u) to (x^2 : y^2 : z^2 , w^2 : u^2). """ def __init__(self, polys, domain): @@ -86,7 +85,7 @@ def _call_with_args(self, P, check=True): - ``P`` -- a point in the domain - - ``check`` -- Boolean - whether or not to perform the input checks + - ``check`` -- Boolean; whether or not to perform the input checks on the image point (Default: ``True``) OUTPUT: The image point in the codomain @@ -135,7 +134,8 @@ def nth_iterate(self, P, n, normalize=False): EXAMPLES:: sage: Z. = ProductProjectiveSpaces([1, 2], QQ) - sage: f = DynamicalSystem_projective([a^3, b^3 + a*b^2, x^2, y^2 - z^2, z*y], domain=Z) + sage: f = DynamicalSystem_projective([a^3, b^3 + a*b^2, x^2, y^2 - z^2, z*y], + ....: domain=Z) sage: P = Z([1, 1, 1, 1, 1]) sage: f.nth_iterate(P, 3) (1/1872 : 1 , 1 : 1 : 0) @@ -145,7 +145,7 @@ def nth_iterate(self, P, n, normalize=False): sage: Z. = ProductProjectiveSpaces([1, 1], ZZ) sage: f = DynamicalSystem_projective([a*b, b^2, x^3 - y^3, y^2*x], domain=Z) sage: P = Z([2, 6, 2, 4]) - sage: f.nth_iterate(P, 2, normalize = True) + sage: f.nth_iterate(P, 2, normalize=True) (1 : 3 , 407 : 112) """ if P.codomain() != self.domain(): @@ -194,10 +194,12 @@ def orbit(self, P, N, **kwds): EXAMPLES:: sage: Z. = ProductProjectiveSpaces([1, 2], QQ) - sage: f = DynamicalSystem_projective([a^3, b^3 + a*b^2, x^2, y^2 - z^2, z*y], domain=Z) + sage: f = DynamicalSystem_projective([a^3, b^3 + a*b^2, x^2, y^2 - z^2, z*y], + ....: domain=Z) sage: P = Z([1, 1, 1, 1, 1]) sage: f.orbit(P, 3) - [(1 : 1 , 1 : 1 : 1), (1/2 : 1 , 1 : 0 : 1), (1/12 : 1 , -1 : 1 : 0), (1/1872 : 1 , 1 : 1 : 0)] + [(1 : 1 , 1 : 1 : 1), (1/2 : 1 , 1 : 0 : 1), + (1/12 : 1 , -1 : 1 : 0), (1/1872 : 1 , 1 : 1 : 0)] :: @@ -205,7 +207,8 @@ def orbit(self, P, N, **kwds): sage: f = DynamicalSystem_projective([a*b, b^2, x^3 - y^3, y^2*x], domain=Z) sage: P = Z([2, 6, 2, 4]) sage: f.orbit(P, 3, normalize=True) - [(1 : 3 , 1 : 2), (1 : 3 , -7 : 4), (1 : 3 , 407 : 112), (1 : 3 , 66014215 : 5105408)] + [(1 : 3 , 1 : 2), (1 : 3 , -7 : 4), + (1 : 3 , 407 : 112), (1 : 3 , 66014215 : 5105408)] """ if P.codomain() != self.domain(): raise TypeError("point is not defined over domain of function") @@ -241,7 +244,7 @@ def orbit(self, P, N, **kwds): def nth_iterate_map(self, n): r""" - Return the nth iterate of this dynamical system. + Return the ``n``-th iterate of this dynamical system. ALGORITHM: @@ -301,22 +304,22 @@ def cyclegraph(self): EXAMPLES:: sage: P. = ProductProjectiveSpaces(GF(3), [1,1]) - sage: f = DynamicalSystem_projective([a^2,b^2,c^2,d^2], domain=P) - sage: f.cyclegraph() + sage: f = DynamicalSystem_projective([a^2, b^2, c^2, d^2], domain=P) + sage: f.cyclegraph() # needs sage.graphs Looped digraph on 16 vertices :: sage: P. = ProductProjectiveSpaces(GF(5), [1,1]) - sage: f = DynamicalSystem_projective([a^2,b^2,c,d], domain=P) - sage: f.cyclegraph() + sage: f = DynamicalSystem_projective([a^2, b^2, c, d], domain=P) + sage: f.cyclegraph() # needs sage.graphs Looped digraph on 36 vertices :: sage: P. = ProductProjectiveSpaces(GF(2), [1,2]) - sage: f = DynamicalSystem_projective([a^2,b^2,c,d,e], domain=P) - sage: f.cyclegraph() + sage: f = DynamicalSystem_projective([a^2, b^2, c, d, e], domain=P) + sage: f.cyclegraph() # needs sage.graphs Looped digraph on 21 vertices .. TODO:: Dynamical systems for subschemes of product projective spaces needs work. diff --git a/src/sage/dynamics/arithmetic_dynamics/projective_ds.py b/src/sage/dynamics/arithmetic_dynamics/projective_ds.py index ef1e50c78e9..606d991b692 100644 --- a/src/sage/dynamics/arithmetic_dynamics/projective_ds.py +++ b/src/sage/dynamics/arithmetic_dynamics/projective_ds.py @@ -58,7 +58,7 @@ class initialization directly. import sage.rings.abc from sage.arith.functions import lcm -from sage.arith.misc import binomial, gcd, is_prime, moebius, next_prime, primes +from sage.arith.misc import binomial, gcd, integer_ceil as ceil, is_prime, moebius, next_prime, primes from sage.calculus.functions import jacobian from sage.categories.fields import Fields from sage.categories.finite_fields import FiniteFields @@ -76,17 +76,15 @@ class initialization directly. from sage.dynamics.arithmetic_dynamics.projective_ds_helper import ( _fast_possible_periods, _all_periodic_points) -from sage.functions.other import ceil -from sage.libs.pari.all import PariError from sage.matrix.constructor import matrix, identity_matrix from sage.misc.cachefunc import cached_method from sage.misc.classcall_metaclass import typecall from sage.misc.functional import sqrt +from sage.misc.lazy_import import lazy_import from sage.misc.mrange import xmrange from sage.modules.free_module_element import vector from sage.parallel.ncpus import ncpus from sage.parallel.use_fork import p_iter_fork -from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField_generic from sage.rings.complex_mpfr import ComplexField from sage.rings.finite_rings.finite_field_base import FiniteField from sage.rings.finite_rings.finite_field_constructor import GF @@ -98,12 +96,9 @@ class initialization directly. from sage.rings.integer_ring import ZZ from sage.rings.polynomial.flatten import FlatteningMorphism, UnflatteningMorphism from sage.rings.morphism import RingHomomorphism_im_gens -from sage.rings.number_field.number_field_ideal import NumberFieldFractionalIdeal -from sage.rings.padics.factory import Qp from sage.rings.polynomial.multi_polynomial_ring_base import is_MPolynomialRing from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing from sage.rings.polynomial.polynomial_ring import is_PolynomialRing -from sage.rings.qqbar import QQbar, number_field_elements_from_algebraics from sage.rings.quotient_ring import QuotientRing_generic from sage.rings.rational_field import QQ from sage.rings.real_mpfr import RealField @@ -116,7 +111,16 @@ class initialization directly. from sage.schemes.projective.projective_space import ProjectiveSpace, is_ProjectiveSpace from sage.schemes.projective.projective_subscheme import AlgebraicScheme_subscheme_projective from sage.structure.element import get_coercion_model -from sage.symbolic.constants import e + +lazy_import('sage.rings.algebraic_closure_finite_field', 'AlgebraicClosureFiniteField_generic') +lazy_import('sage.rings.number_field.number_field_ideal', 'NumberFieldFractionalIdeal') +lazy_import('sage.rings.padics.factory', 'Qp') +lazy_import('sage.rings.qqbar', 'number_field_elements_from_algebraics') + +try: + from sage.libs.pari.all import PariError +except ImportError: + PariError = () class DynamicalSystem_projective(SchemeMorphism_polynomial_projective_space, @@ -195,8 +199,8 @@ class DynamicalSystem_projective(SchemeMorphism_polynomial_projective_space, Symbolic Ring elements are not allowed:: - sage: x,y = var('x,y') - sage: DynamicalSystem_projective([x^2, y^2]) + sage: x,y = var('x,y') # needs sage.symbolic + sage: DynamicalSystem_projective([x^2, y^2]) # needs sage.symbolic Traceback (most recent call last): ... ValueError: [x^2, y^2] must be elements of a polynomial ring @@ -225,8 +229,8 @@ class DynamicalSystem_projective(SchemeMorphism_polynomial_projective_space, sage: P. = ProjectiveSpace(CC, 2) sage: X = P.subscheme([x - y]) - sage: u,v,w = X.coordinate_ring().gens() - sage: DynamicalSystem_projective([u^2, v^2, w*u], domain=X) + sage: u,v,w = X.coordinate_ring().gens() # needs sage.rings.function_field + sage: DynamicalSystem_projective([u^2, v^2, w*u], domain=X) # needs sage.rings.function_field Dynamical System of Closed subscheme of Projective Space of dimension 2 over Complex Field with 53 bits of precision defined by: x - y @@ -242,7 +246,7 @@ class DynamicalSystem_projective(SchemeMorphism_polynomial_projective_space, sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([(x-2*y)^2, (x-2*z)^2, x^2]) sage: X = P.subscheme(y - z) - sage: f(f(f(X))) + sage: f(f(f(X))) # needs sage.rings.function_field Closed subscheme of Projective Space of dimension 2 over Rational Field defined by: y - z @@ -251,7 +255,7 @@ class DynamicalSystem_projective(SchemeMorphism_polynomial_projective_space, sage: P. = ProjectiveSpace(QQ, 3) sage: f = DynamicalSystem_projective([(x-2*y)^2, (x-2*z)^2, (x-2*w)^2, x^2]) - sage: f(P.subscheme([x, y, z])) + sage: f(P.subscheme([x, y, z])) # needs sage.rings.function_field Closed subscheme of Projective Space of dimension 3 over Rational Field defined by: w, @@ -268,6 +272,7 @@ class DynamicalSystem_projective(SchemeMorphism_polynomial_projective_space, :: + sage: # needs sage.rings.number_field sage: K. = QuadraticField(-7) sage: P. = ProjectiveSpace(K, 1) sage: f = DynamicalSystem([x^3 + v*x*y^2, y^3]) @@ -296,7 +301,7 @@ def __classcall_private__(cls, morphism_or_polys, domain=None, names=None): :: - sage: DynamicalSystem_projective([exp(x), exp(y)]) + sage: DynamicalSystem_projective([exp(x), exp(y)]) # needs sage.symbolic Traceback (most recent call last): ... ValueError: [e^x, e^y] must be elements of a polynomial ring @@ -502,9 +507,9 @@ def _number_field_from_algebraics(self): EXAMPLES:: - sage: P. = ProjectiveSpace(QQbar,1) - sage: f = DynamicalSystem_projective([x^2 + QQbar(sqrt(2)) * y^2, y^2]) - sage: f._number_field_from_algebraics() + sage: P. = ProjectiveSpace(QQbar,1) # needs sage.rings.number_field + sage: f = DynamicalSystem_projective([x^2 + QQbar(sqrt(2)) * y^2, y^2]) # needs sage.rings.number_field sage.symbolic + sage: f._number_field_from_algebraics() # needs sage.rings.number_field sage.symbolic Dynamical System of Projective Space of dimension 1 over Number Field in a with defining polynomial y^2 - 2 with a = 1.414213562373095? Defn: Defined on coordinates by sending (x : y) to @@ -615,21 +620,21 @@ def dynatomic_polynomial(self, period): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^2 + y^2, y^2]) - sage: f.dynatomic_polynomial(2) + sage: f.dynatomic_polynomial(2) # needs sage.libs.pari x^2 + x*y + 2*y^2 :: sage: P. = ProjectiveSpace(ZZ,1) sage: f = DynamicalSystem_projective([x^2 + y^2, x*y]) - sage: f.dynatomic_polynomial(4) + sage: f.dynatomic_polynomial(4) # needs sage.libs.pari 2*x^12 + 18*x^10*y^2 + 57*x^8*y^4 + 79*x^6*y^6 + 48*x^4*y^8 + 12*x^2*y^10 + y^12 :: sage: P. = ProjectiveSpace(CC,1) sage: f = DynamicalSystem_projective([x^2 + y^2, 3*x*y]) - sage: f.dynatomic_polynomial(3) + sage: f.dynatomic_polynomial(3) # needs sage.libs.pari 13.0000000000000*x^6 + 117.000000000000*x^4*y^2 + 78.0000000000000*x^2*y^4 + y^6 @@ -644,7 +649,7 @@ def dynatomic_polynomial(self, period): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^2 - 29/16*y^2, y^2]) - sage: f.dynatomic_polynomial([2,3]) + sage: f.dynatomic_polynomial([2,3]) # needs sage.libs.pari x^12 - 95/8*x^10*y^2 + 13799/256*x^8*y^4 - 119953/1024*x^6*y^6 + 8198847/65536*x^4*y^8 - 31492431/524288*x^2*y^10 + 172692729/16777216*y^12 @@ -653,14 +658,14 @@ def dynatomic_polynomial(self, period): sage: P. = ProjectiveSpace(ZZ,1) sage: f = DynamicalSystem_projective([x^2 - y^2, y^2]) - sage: f.dynatomic_polynomial([1,2]) + sage: f.dynatomic_polynomial([1,2]) # needs sage.libs.pari x^2 - x*y :: sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^3 - y^3, 3*x*y^2]) - sage: f.dynatomic_polynomial([0,4])==f.dynatomic_polynomial(4) + sage: f.dynatomic_polynomial([0,4])==f.dynatomic_polynomial(4) # needs sage.libs.pari True :: @@ -674,9 +679,9 @@ def dynatomic_polynomial(self, period): :: - sage: P. = ProjectiveSpace(Qp(5),1) - sage: f = DynamicalSystem_projective([x^2 + y^2, y^2]) - sage: f.dynatomic_polynomial(2) + sage: P. = ProjectiveSpace(Qp(5),1) # needs sage.rings.padics + sage: f = DynamicalSystem_projective([x^2 + y^2, y^2]) # needs sage.rings.padics + sage: f.dynatomic_polynomial(2) # needs sage.rings.padics (x^4*y + (2 + O(5^20))*x^2*y^3 - x*y^4 + (2 + O(5^20))*y^5)/(x^2*y - x*y^2 + y^3) :: @@ -684,7 +689,7 @@ def dynatomic_polynomial(self, period): sage: L. = PolynomialRing(QQ) sage: P. = ProjectiveSpace(L,1) sage: f = DynamicalSystem_projective([x^2 + t*y^2, y^2]) - sage: f.dynatomic_polynomial(2) + sage: f.dynatomic_polynomial(2) # needs sage.libs.pari x^2 + x*y + (t + 1)*y^2 :: @@ -692,17 +697,17 @@ def dynatomic_polynomial(self, period): sage: K. = PolynomialRing(ZZ) sage: P. = ProjectiveSpace(K,1) sage: f = DynamicalSystem_projective([x^2 + c*y^2, y^2]) - sage: f.dynatomic_polynomial([1, 2]) + sage: f.dynatomic_polynomial([1, 2]) # needs sage.libs.pari x^2 - x*y + (c + 1)*y^2 :: sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^2 + y^2, y^2]) - sage: f.dynatomic_polynomial(2) + sage: f.dynatomic_polynomial(2) # needs sage.libs.pari x^2 + x*y + 2*y^2 sage: R. = PolynomialRing(QQ) - sage: K. = NumberField(X^2 + X + 2) + sage: K. = NumberField(X^2 + X + 2) # needs sage.rings.number_field sage: PP = P.change_ring(K) sage: ff = f.change_ring(K) sage: p = PP((c, 1)) @@ -713,21 +718,21 @@ def dynatomic_polynomial(self, period): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^2 + y^2, x*y]) - sage: f.dynatomic_polynomial([2, 2]) + sage: f.dynatomic_polynomial([2, 2]) # needs sage.libs.pari x^4 + 4*x^2*y^2 + y^4 sage: R. = PolynomialRing(QQ) - sage: K. = NumberField(X^4 + 4*X^2 + 1) + sage: K. = NumberField(X^4 + 4*X^2 + 1) # needs sage.rings.number_field sage: PP = P.change_ring(K) sage: ff = f.change_ring(K) sage: p = PP((c, 1)) - sage: ff.nth_iterate(p, 4) == ff.nth_iterate(p, 2) + sage: ff.nth_iterate(p, 4) == ff.nth_iterate(p, 2) # needs sage.rings.number_field True :: sage: P. = ProjectiveSpace(CC, 1) sage: f = DynamicalSystem_projective([x^2 - CC.0/3*y^2, y^2]) - sage: f.dynatomic_polynomial(2) + sage: f.dynatomic_polynomial(2) # needs sage.libs.pari (x^4*y + (-0.666666666666667*I)*x^2*y^3 - x*y^4 + (-0.111111111111111 - 0.333333333333333*I)*y^5)/(x^2*y - x*y^2 + (-0.333333333333333*I)*y^3) @@ -736,15 +741,15 @@ def dynatomic_polynomial(self, period): sage: P. = ProjectiveSpace(CC, 1) sage: f = DynamicalSystem_projective([x^2 - CC.0/5*y^2, y^2]) - sage: f.dynatomic_polynomial(2) + sage: f.dynatomic_polynomial(2) # needs sage.libs.pari x^2 + x*y + (1.00000000000000 - 0.200000000000000*I)*y^2 :: - sage: L. = PolynomialRing(QuadraticField(2).maximal_order()) + sage: L. = PolynomialRing(QuadraticField(2).maximal_order()) # needs sage.rings.number_field sage: P. = ProjectiveSpace(L.fraction_field(), 1) sage: f = DynamicalSystem_projective([x^2 + (t^2 + 1)*y^2, y^2]) - sage: f.dynatomic_polynomial(2) + sage: f.dynatomic_polynomial(2) # needs sage.libs.pari sage.rings.number_field x^2 + x*y + (t^2 + 2)*y^2 :: @@ -759,18 +764,20 @@ def dynatomic_polynomial(self, period): We check that the dynatomic polynomial has the right parent (see :trac:`18409`):: + sage: # needs sage.rings.number_field sage: P. = ProjectiveSpace(QQbar,1) sage: f = DynamicalSystem_projective([x^2 - 1/3*y^2, y^2]) - sage: f.dynatomic_polynomial(2).parent() + sage: f.dynatomic_polynomial(2).parent() # needs sage.libs.pari Multivariate Polynomial Ring in x, y over Algebraic Field :: + sage: # needs sage.rings.number_field sage: T. = QuadraticField(33) sage: S. = PolynomialRing(T) sage: P. = ProjectiveSpace(FractionField(S),1) sage: f = DynamicalSystem_projective([t*x^2 - 1/t*y^2, y^2]) - sage: f.dynatomic_polynomial([1, 2]).parent() + sage: f.dynatomic_polynomial([1, 2]).parent() # needs sage.libs.pari Multivariate Polynomial Ring in x, y over Fraction Field of Univariate Polynomial Ring in t over Number Field in v with defining polynomial x^2 - 33 with v = 5.744562646538029? @@ -786,7 +793,7 @@ def dynatomic_polynomial(self, period): sage: R. = QQ[] sage: P. = ProjectiveSpace(R,1) sage: f = DynamicalSystem_projective([x^2 + c*y^2, y^2]) - sage: f.dynatomic_polynomial([1,2]).parent() + sage: f.dynatomic_polynomial([1,2]).parent() # needs sage.libs.pari Multivariate Polynomial Ring in x, y over Univariate Polynomial Ring in c over Rational Field @@ -795,7 +802,7 @@ def dynatomic_polynomial(self, period): sage: R. = QQ[] sage: P. = ProjectiveSpace(ZZ,1) sage: f = DynamicalSystem_projective([x^2 + y^2, (1)*y^2 + (1)*x*y]) - sage: f.dynatomic_polynomial([1,2]).parent() + sage: f.dynatomic_polynomial([1,2]).parent() # needs sage.libs.pari Multivariate Polynomial Ring in x, y over Integer Ring :: @@ -816,7 +823,7 @@ def dynatomic_polynomial(self, period): sage: R. = QQ[] sage: P. = ProjectiveSpace(R,1) sage: f = DynamicalSystem_projective([x^2 + c*y^2, y^2]) - sage: f.dynatomic_polynomial([1,2]).parent() + sage: f.dynatomic_polynomial([1,2]).parent() # needs sage.libs.pari Multivariate Polynomial Ring in x, y over Univariate Polynomial Ring in c over Rational Field @@ -825,13 +832,13 @@ def dynatomic_polynomial(self, period): sage: S. = FunctionField(CC) sage: P. = ProjectiveSpace(S,1) sage: f = DynamicalSystem_projective([t*x^2-1*y^2, t*y^2]) - sage: f.dynatomic_polynomial([1, 2]).parent() + sage: f.dynatomic_polynomial([1, 2]).parent() # needs sage.libs.pari Symbolic Ring :: sage: R. = PolynomialRing(QQ) - sage: S = R.quo(R.ideal(y^2-x+1)) + sage: S = R.quo(R.ideal(y^2 - x + 1)) sage: P. = ProjectiveSpace(FractionField(S),1) sage: f = DynamicalSystem_projective([u^2 + S(x^2)*v^2, v^2]) sage: dyn = f.dynatomic_polynomial([1,1]); dyn @@ -936,7 +943,7 @@ def nth_iterate_map(self, n, normalize=False): :: sage: P. = ProjectiveSpace(ZZ,2) - sage: f = DynamicalSystem_projective([x^2-y^2, x*y, z^2+x^2]) + sage: f = DynamicalSystem_projective([x^2 - y^2, x*y, z^2 + x^2]) sage: f.nth_iterate_map(2) Dynamical System of Projective Space of dimension 2 over Integer Ring Defn: Defined on coordinates by sending (x : y : z) to @@ -948,7 +955,7 @@ def nth_iterate_map(self, n, normalize=False): sage: P. = ProjectiveSpace(QQ,2) sage: X = P.subscheme(x*z-y^2) sage: f = DynamicalSystem_projective([x^2, x*z, z^2], domain=X) - sage: f.nth_iterate_map(2) + sage: f.nth_iterate_map(2) # needs sage.rings.function_field Dynamical System of Closed subscheme of Projective Space of dimension 2 over Rational Field defined by: -y^2 + x*z @@ -1179,6 +1186,7 @@ def arakelov_zhang_pairing(self, g, **kwds): EXAMPLES:: + sage: # needs sage.rings.number_field sage: K. = CyclotomicField(3) sage: P. = ProjectiveSpace(K, 1) sage: f = DynamicalSystem_projective([x^2 + (2*k + 2)*y^2, y^2]) @@ -1191,12 +1199,12 @@ def arakelov_zhang_pairing(self, g, **kwds): sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 + 4*y^2, y^2]) sage: g = DynamicalSystem_projective([x^2, y^2]) - sage: pairingval = f.arakelov_zhang_pairing(g, n=6); pairingval + sage: pairingval = f.arakelov_zhang_pairing(g, n=6); pairingval # needs sage.rings.function_field 0.750178391443644 sage: # Compare to the exact value: - sage: dynheight = f.canonical_height(P(0, 1)); dynheight + sage: dynheight = f.canonical_height(P(0, 1)); dynheight # needs sage.libs.pari 0.75017839144364417318023000563 - sage: dynheight - pairingval + sage: dynheight - pairingval # needs sage.libs.pari sage.rings.function_field 0.000000000000000 Notice that if we set the noise_multiplier to 0, the accuracy is diminished:: @@ -1204,12 +1212,12 @@ def arakelov_zhang_pairing(self, g, **kwds): sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 + 4*y^2, y^2]) sage: g = DynamicalSystem_projective([x^2, y^2]) - sage: pairingval = f.arakelov_zhang_pairing(g, n=6, noise_multiplier=0) - sage: pairingval + sage: pairingval = f.arakelov_zhang_pairing(g, n=6, noise_multiplier=0) # needs sage.rings.function_field + sage: pairingval # needs sage.rings.number_field 0.650660018921632 - sage: dynheight = f.canonical_height(P(0, 1)); dynheight + sage: dynheight = f.canonical_height(P(0, 1)); dynheight # needs sage.libs.pari 0.75017839144364417318023000563 - sage: pairingval - dynheight + sage: pairingval - dynheight # needs sage.libs.pari sage.rings.function_field -0.0995183725220122 We compute the example of Prop. 18(d) from Petsche, Szpiro and Tucker:: @@ -1217,16 +1225,17 @@ def arakelov_zhang_pairing(self, g, **kwds): sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([y^2 - (y - x)^2, y^2]) sage: g = DynamicalSystem_projective([x^2, y^2]) - sage: f.arakelov_zhang_pairing(g) + sage: f.arakelov_zhang_pairing(g) # needs sage.rings.function_field 0.326954667248466 sage: # Correct value should be = 0.323067... - sage: f.arakelov_zhang_pairing(g, n=9) # long time + sage: f.arakelov_zhang_pairing(g, n=9) # long time # needs sage.rings.function_field 0.323091061918965 - sage: _ - 0.323067 # long time + sage: _ - 0.323067 # long time # needs sage.rings.function_field 0.0000240619189654789 Also from Prop. 18 of Petsche, Szpiro and Tucker, includes places of bad reduction:: + sage: # needs sage.rings.number_field sage: R. = PolynomialRing(ZZ) sage: K. = NumberField(z^3 - 11) sage: P. = ProjectiveSpace(K,1) @@ -1237,9 +1246,9 @@ def arakelov_zhang_pairing(self, g, **kwds): If all archimedean absolute values of a have modulus > 2, then the pairing should be h(a).:: - sage: f.arakelov_zhang_pairing(g, n=6) # long time + sage: f.arakelov_zhang_pairing(g, n=6) # long time # needs sage.rings.number_field 1.93846423207664 - sage: _ - a.global_height() # long time + sage: _ - a.global_height() # long time # needs sage.rings.number_field -0.00744591697867292 """ n = kwds.pop('n', 5) @@ -1268,7 +1277,7 @@ def arakelov_zhang_pairing(self, g, **kwds): if not self.is_endomorphism(): raise TypeError("Self must be an endomorphism.") - if R not in NumberFields() and R is not QQbar: + if R not in NumberFields() and not isinstance(R, sage.rings.abc.AlgebraicField): raise NotImplementedError("Only implemented for number fields.") f_iterate_map = self.nth_iterate_map(n) @@ -1421,7 +1430,7 @@ def degree_sequence(self, iterates=2): sage: P2. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([Z^2, X*Y, Y^2]) - sage: f.degree_sequence(15) + sage: f.degree_sequence(15) # needs sage.rings.function_field [2, 3, 5, 8, 11, 17, 24, 31, 45, 56, 68, 91, 93, 184, 275] :: @@ -1429,21 +1438,21 @@ def degree_sequence(self, iterates=2): sage: F. = PolynomialRing(QQ) sage: P2. = ProjectiveSpace(F, 2) sage: f = DynamicalSystem_projective([Y*Z, X*Y, Y^2 + t*X*Z]) - sage: f.degree_sequence(5) + sage: f.degree_sequence(5) # needs sage.rings.function_field [2, 3, 5, 8, 13] :: sage: P2. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([X^2, Y^2, Z^2]) - sage: f.degree_sequence(10) + sage: f.degree_sequence(10) # needs sage.rings.function_field [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] :: sage: P2. = ProjectiveSpace(ZZ, 2) sage: f = DynamicalSystem_projective([X*Y, Y*Z+Z^2, Z^2]) - sage: f.degree_sequence(10) + sage: f.degree_sequence(10) # needs sage.rings.function_field [2, 3, 4, 5, 6, 7, 8, 9, 10, 11] """ if int(iterates) < 1: @@ -1482,14 +1491,14 @@ def dynamical_degree(self, N=3, prec=53): sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 + x*y, y^2]) - sage: f.dynamical_degree() + sage: f.dynamical_degree() # needs sage.rings.function_field 2.00000000000000 :: sage: P2. = ProjectiveSpace(ZZ, 2) sage: f = DynamicalSystem_projective([X*Y, Y*Z + Z^2, Z^2]) - sage: f.dynamical_degree(N=5, prec=100) + sage: f.dynamical_degree(N=5, prec=100) # needs sage.rings.function_field 1.4309690811052555010452244131 """ if int(N) < 1: @@ -1674,7 +1683,7 @@ def resultant(self, normalize=False): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^2 + y^2, 6*y^2]) - sage: f.resultant() + sage: f.resultant() # needs sage.libs.pari 36 :: @@ -1682,7 +1691,7 @@ def resultant(self, normalize=False): sage: R. = PolynomialRing(GF(17)) sage: P. = ProjectiveSpace(R,1) sage: f = DynamicalSystem_projective([t*x^2 + t*y^2, 6*y^2]) - sage: f.resultant() + sage: f.resultant() # needs sage.libs.pari 2*t^2 :: @@ -1702,6 +1711,7 @@ def resultant(self, normalize=False): :: + sage: # needs sage.rings.number_field sage: R. = PolynomialRing(QQ) sage: s = (t^3 + t + 1).roots(QQbar)[0][0] sage: P. = ProjectiveSpace(QQbar, 1) @@ -1767,7 +1777,7 @@ def primes_of_bad_reduction(self, check=True): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([1/3*x^2 + 1/2*y^2, y^2]) - sage: f.primes_of_bad_reduction() + sage: f.primes_of_bad_reduction() # needs sage.rings.function_field [2, 3] :: @@ -1775,16 +1785,17 @@ def primes_of_bad_reduction(self, check=True): sage: P. = ProjectiveSpace(QQ,3) sage: f = DynamicalSystem_projective([12*x*z - 7*y^2, 31*x^2 - y^2, ....: 26*z^2, 3*w^2 - z*w]) - sage: f.primes_of_bad_reduction() + sage: f.primes_of_bad_reduction() # needs sage.rings.function_field [2, 3, 7, 13, 31] A number field example:: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = NumberField(z^2 - 2) sage: P. = ProjectiveSpace(K,1) sage: f = DynamicalSystem_projective([1/3*x^2+1/a*y^2, y^2]) - sage: f.primes_of_bad_reduction() + sage: f.primes_of_bad_reduction() # needs sage.rings.function_field [Fractional ideal (a), Fractional ideal (3)] This is an example where ``check=False`` returns extra primes:: @@ -1793,9 +1804,9 @@ def primes_of_bad_reduction(self, check=True): sage: f = DynamicalSystem_projective([3*x*y^2 + 7*y^3 - 4*y^2*z + 5*z^3, ....: -5*x^3 + x^2*y + y^3 + 2*x^2*z, ....: -2*x^2*y + x*y^2 + y^3 - 4*y^2*z + x*z^2]) - sage: f.primes_of_bad_reduction(False) + sage: f.primes_of_bad_reduction(False) # needs sage.rings.function_field [2, 5, 37, 2239, 304432717] - sage: f.primes_of_bad_reduction() + sage: f.primes_of_bad_reduction() # needs sage.rings.function_field [5, 37, 2239, 304432717] """ if (not is_ProjectiveSpace(self.domain())) or (not is_ProjectiveSpace(self.codomain())): @@ -1891,10 +1902,10 @@ def conjugate(self, M, adjugate=False, normalize=False): :: sage: R. = PolynomialRing(QQ) - sage: K. = NumberField(x^2 + 1) + sage: K. = NumberField(x^2 + 1) # needs sage.rings.number_field sage: P. = ProjectiveSpace(ZZ,1) sage: f = DynamicalSystem_projective([x^3 + y^3, y^3]) - sage: f.conjugate(matrix([[i,0], [0,-i]])) + sage: f.conjugate(matrix([[i,0], [0,-i]])) # needs sage.rings.number_field Dynamical System of Projective Space of dimension 1 over Integer Ring Defn: Defined on coordinates by sending (x : y) to (-x^3 + y^3 : -y^3) @@ -1920,10 +1931,10 @@ def conjugate(self, M, adjugate=False, normalize=False): :: sage: R. = PolynomialRing(QQ) - sage: K. = NumberField(x^2 + 1) + sage: K. = NumberField(x^2 + 1) # needs sage.rings.number_field sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([1/3*x^2 + 1/2*y^2, y^2]) - sage: f.conjugate(matrix([[i,0], [0,-i]])) + sage: f.conjugate(matrix([[i,0], [0,-i]])) # needs sage.rings.number_field Dynamical System of Projective Space of dimension 1 over Number Field in i with defining polynomial x^2 + 1 Defn: Defined on coordinates by sending (x : y) to @@ -2028,6 +2039,7 @@ def green_function(self, P, v, **kwds): :: + sage: # needs sage.rings.number_field sage: K. = QuadraticField(3) sage: P. = ProjectiveSpace(K,1) sage: f = DynamicalSystem_projective([17*x^2 + 1/7*y^2, 17*w*x*y]) @@ -2205,13 +2217,14 @@ def canonical_height(self, P, **kwds): sage: P. = ProjectiveSpace(ZZ,1) sage: f = DynamicalSystem_projective([x^2 + y^2, 2*x*y]); - sage: f.canonical_height(P.point([5,4]), error_bound=0.001) + sage: f.canonical_height(P.point([5,4]), error_bound=0.001) # needs sage.libs.pari 2.1970553519503404898926835324 - sage: f.canonical_height(P.point([2,1]), error_bound=0.001) + sage: f.canonical_height(P.point([2,1]), error_bound=0.001) # needs sage.libs.pari 1.0984430632822307984974382955 Notice that preperiodic points may not return exactly 0:: + sage: # needs sage.rings.number_field sage: R. = PolynomialRing(QQ) sage: K. = NumberField(X^2 + X - 1) sage: P. = ProjectiveSpace(K,1) @@ -2228,7 +2241,7 @@ def canonical_height(self, P, **kwds): sage: X = P.subscheme(x^2 - y^2); sage: f = DynamicalSystem_projective([x^2, y^2, 4*z^2], domain=X); sage: Q = X([4,4,1]) - sage: f.canonical_height(Q, badprimes=[2]) + sage: f.canonical_height(Q, badprimes=[2]) # needs sage.rings.function_field 0.0013538030870311431824555314882 :: @@ -2237,7 +2250,7 @@ def canonical_height(self, P, **kwds): sage: X = P.subscheme(x^2 - y^2); sage: f = DynamicalSystem_projective([x^2, y^2, 30*z^2], domain=X) sage: Q = X([4, 4, 1]) - sage: f.canonical_height(Q, badprimes=[2,3,5], prec=200) + sage: f.canonical_height(Q, badprimes=[2,3,5], prec=200) # needs sage.rings.function_field 2.7054056208276961889784303469356774912979228770208655455481 :: @@ -2245,7 +2258,7 @@ def canonical_height(self, P, **kwds): sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([1000*x^2 - 29*y^2, 1000*y^2]) sage: Q = P(-1/4, 1) - sage: f.canonical_height(Q, error_bound=0.01) + sage: f.canonical_height(Q, error_bound=0.01) # needs sage.libs.pari 3.7996079979254623065837411853 :: @@ -2257,14 +2270,14 @@ def canonical_height(self, P, **kwds): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([RSA768*x^2 + y^2, x*y]) sage: Q = P(RSA768,1) - sage: f.canonical_height(Q, error_bound=0.00000000000000001) + sage: f.canonical_height(Q, error_bound=0.00000000000000001) # needs sage.libs.pari 931.18256422718241278672729195 :: - sage: P.=ProjectiveSpace(QQ, 1) + sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem([2*(-2*x^3 + 3*(x^2*y)) + 3*y^3, 3*y^3]) - sage: f.canonical_height(P(1,0)) + sage: f.canonical_height(P(1,0)) # needs sage.libs.pari 0.00000000000000000000000000000 """ bad_primes = kwds.get("badprimes", None) @@ -2273,7 +2286,7 @@ def canonical_height(self, P, **kwds): K = FractionField(self.codomain().base_ring()) if K not in NumberFields(): - if K is not QQbar: + if not isinstance(K, sage.rings.abc.AlgebraicField): raise NotImplementedError("must be over a number field or a number field order or QQbar") else: #since this an absolute height, we can compute the height of a QQbar point @@ -2418,25 +2431,27 @@ def height_difference_bound(self, prec=None): sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 + y^2, x*y]) - sage: f.height_difference_bound() + sage: f.height_difference_bound() # needs sage.symbolic 1.38629436111989 sage: P. = ProjectiveSpace(ZZ, 2) sage: f = DynamicalSystem_projective([4*x^2 + 100*y^2, 210*x*y, 10000*z^2]) - sage: f.height_difference_bound() + sage: f.height_difference_bound() # needs sage.symbolic 10.3089526606443 A number field example:: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = NumberField(x^3 - 2) sage: P. = ProjectiveSpace(K, 2) sage: f = DynamicalSystem_projective([1/(c+1)*x^2 + c*y^2, 210*x*y, 10000*z^2]) - sage: f.height_difference_bound() + sage: f.height_difference_bound() # needs sage.symbolic 11.3683039374269 :: + sage: # needs sage.rings.number_field sage.symbolic sage: P. = ProjectiveSpace(QQbar, 2) sage: f = DynamicalSystem_projective([x^2, QQbar(sqrt(-1))*y^2, ....: QQbar(sqrt(3))*z^2]) @@ -2447,12 +2462,12 @@ def height_difference_bound(self, prec=None): sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem([5*x^2 + 3*x*y , y^2 + 3*x^2]) - sage: f.height_difference_bound(prec=100) + sage: f.height_difference_bound(prec=100) # needs sage.symbolic 5.3375380797013179737224159274 """ FF = FractionField(self.domain().base_ring()) #lift will only work over fields, so coercing into FF if FF not in NumberFields(): - if FF == QQbar: + if isinstance(FF, sage.rings.abc.AlgebraicField): #since this is absolute height, we can choose any number field over which the #function is defined. f = self._number_field_from_algebraics() @@ -2532,9 +2547,9 @@ def multiplier(self, P, n, check=True): :: - sage: P. = ProjectiveSpace(Qp(13),1) + sage: P. = ProjectiveSpace(Qp(13),1) # needs sage.rings.padics sage: f = DynamicalSystem_projective([x^2 - 29/16*y^2, y^2]) - sage: f.multiplier(P(5,4), 3) + sage: f.multiplier(P(5,4), 3) # needs sage.rings.padics [6 + 8*13 + 13^2 + 8*13^3 + 13^4 + 8*13^5 + 13^6 + 8*13^7 + 13^8 + 8*13^9 + 13^10 + 8*13^11 + 13^12 + 8*13^13 + 13^14 + 8*13^15 + 13^16 + 8*13^17 + 13^18 + 8*13^19 + O(13^20)] @@ -2765,7 +2780,7 @@ def nth_preimage_tree(self, Q, n, **kwds): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^2 + y^2, y^2]) sage: Q = P(0,1) - sage: f.nth_preimage_tree(Q, 2) + sage: f.nth_preimage_tree(Q, 2) # needs sage.plot GraphPlot object for Digraph on 7 vertices :: @@ -2773,7 +2788,7 @@ def nth_preimage_tree(self, Q, n, **kwds): sage: P. = ProjectiveSpace(GF(3), 1) sage: f = DynamicalSystem_projective([x^2 + x*y + y^2, y^2]) sage: Q = P(0,1) - sage: f.nth_preimage_tree(Q, 2, return_points=True) + sage: f.nth_preimage_tree(Q, 2, return_points=True) # needs sage.plot (GraphPlot object for Digraph on 4 vertices, [[(0 : 1)], [(1 : 1)], [(0 : 1), (2 : 1)]]) """ @@ -2787,7 +2802,7 @@ def nth_preimage_tree(self, Q, n, **kwds): if self.domain().dimension_relative() > 1: raise NotImplementedError("only implemented for dimension 1") base_ring = self.base_ring() - if base_ring is QQbar: + if isinstance(base_ring, sage.rings.abc.AlgebraicField): if numerical: raise ValueError("can't solve numerically over QQbar, no embedding into CC") fbar = self @@ -2874,20 +2889,20 @@ def possible_periods(self, **kwds): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^2 - 29/16*y^2, y^2]) - sage: f.possible_periods(ncpus=1) + sage: f.possible_periods(ncpus=1) # needs sage.rings.function_field [1, 3] :: sage: PS. = ProjectiveSpace(1,QQ) sage: f = DynamicalSystem_projective([5*x^3 - 53*x*y^2 + 24*y^3, 24*y^3]) - sage: f.possible_periods(prime_bound=[1,5]) + sage: f.possible_periods(prime_bound=[1,5]) # needs sage.rings.function_field Traceback (most recent call last): ... ValueError: no primes of good reduction in that range - sage: f.possible_periods(prime_bound=[1,10]) + sage: f.possible_periods(prime_bound=[1,10]) # needs sage.rings.function_field [1, 4, 12] - sage: f.possible_periods(prime_bound=[1,20]) + sage: f.possible_periods(prime_bound=[1,20]) # needs sage.rings.function_field [1, 4] :: @@ -2895,7 +2910,7 @@ def possible_periods(self, **kwds): sage: P. = ProjectiveSpace(ZZ,2) sage: f = DynamicalSystem_projective([2*x^3 - 50*x*z^2 + 24*z^3, ....: 5*y^3 - 53*y*z^2 + 24*z^3, 24*z^3]) - sage: f.possible_periods(prime_bound=10) + sage: f.possible_periods(prime_bound=10) # needs sage.rings.function_field [1, 2, 6, 20, 42, 60, 140, 420] sage: f.possible_periods(prime_bound=20) # long time [1, 20] @@ -2974,7 +2989,7 @@ def _preperiodic_points_to_cyclegraph(self, preper): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^2 - 2*y^2, y^2]) sage: preper = [P(-2, 1), P(1, 0), P(0, 1), P(1, 1), P(2, 1), P(-1, 1)] - sage: f._preperiodic_points_to_cyclegraph(preper) + sage: f._preperiodic_points_to_cyclegraph(preper) # needs sage.graphs Looped digraph on 6 vertices """ V = [] @@ -3018,21 +3033,21 @@ def is_PGL_minimal(self, prime_list=None): sage: PS. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([X^2 + 3*Y^2, X*Y]) - sage: f.is_PGL_minimal() + sage: f.is_PGL_minimal() # needs sage.rings.function_field True :: sage: PS. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([6*x^2 + 12*x*y + 7*y^2, 12*x*y]) - sage: f.is_PGL_minimal() + sage: f.is_PGL_minimal() # needs sage.rings.function_field False :: sage: PS. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([6*x^2 + 12*x*y + 7*y^2, y^2]) - sage: f.is_PGL_minimal() + sage: f.is_PGL_minimal() # needs sage.rings.function_field False """ if self.base_ring() != QQ and self.base_ring() != ZZ: @@ -3093,7 +3108,7 @@ def minimal_model(self, return_transformation=False, prime_list=None, algorithm= sage: PS. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([X^2 + 3*Y^2, X*Y]) - sage: f.minimal_model(return_transformation=True) + sage: f.minimal_model(return_transformation=True) # needs sage.rings.function_field ( Dynamical System of Projective Space of dimension 1 over Rational Field @@ -3111,7 +3126,7 @@ def minimal_model(self, return_transformation=False, prime_list=None, algorithm= ....: + 1146*X*Y^3 + 245/2*Y^4, ....: -12329/2*X^4 - 10506*X^3*Y - 6723*X^2*Y^2 ....: - 1914*X*Y^3 - 409/2*Y^4]) - sage: f.minimal_model(return_transformation=True) + sage: f.minimal_model(return_transformation=True) # needs sage.rings.function_field ( Dynamical System of Projective Space of dimension 1 over Rational Field Defn: Defined on coordinates by sending (X : Y) to @@ -3126,7 +3141,7 @@ def minimal_model(self, return_transformation=False, prime_list=None, algorithm= sage: PS. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([6*x^2 + 12*x*y + 7*y^2, 12*x*y]) - sage: f.minimal_model() + sage: f.minimal_model() # needs sage.rings.function_field Dynamical System of Projective Space of dimension 1 over Rational Field Defn: Defined on coordinates by sending (x : y) to (x^2 + 12*x*y + 42*y^2 : 2*x*y) @@ -3135,15 +3150,15 @@ def minimal_model(self, return_transformation=False, prime_list=None, algorithm= sage: PS. = ProjectiveSpace(ZZ,1) sage: f = DynamicalSystem_projective([6*x^2 + 12*x*y + 7*y^2, 12*x*y + 42*y^2]) - sage: g,M = f.minimal_model(return_transformation=True, algorithm='BM') - sage: f.conjugate(M) == g + sage: g,M = f.minimal_model(return_transformation=True, algorithm='BM') # needs sage.rings.function_field + sage: f.conjugate(M) == g # needs sage.rings.function_field True :: sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem([2*x^2, y^2]) - sage: f.minimal_model(return_transformation=True) + sage: f.minimal_model(return_transformation=True) # needs sage.rings.function_field ( Dynamical System of Projective Space of dimension 1 over Rational Field Defn: Defined on coordinates by sending (x : y) to @@ -3151,7 +3166,7 @@ def minimal_model(self, return_transformation=False, prime_list=None, algorithm= [1 0] [0 2] ) - sage: f.minimal_model(prime_list=[3]) + sage: f.minimal_model(prime_list=[3]) # needs sage.rings.function_field Dynamical System of Projective Space of dimension 1 over Rational Field Defn: Defined on coordinates by sending (x : y) to (2*x^2 : y^2) @@ -3160,7 +3175,7 @@ def minimal_model(self, return_transformation=False, prime_list=None, algorithm= sage: PS. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([X + Y, X - 3*Y]) - sage: f.minimal_model() + sage: f.minimal_model() # needs sage.rings.function_field Traceback (most recent call last): ... NotImplementedError: minimality is only for degree 2 or higher @@ -3169,7 +3184,7 @@ def minimal_model(self, return_transformation=False, prime_list=None, algorithm= sage: PS. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([X^2 - Y^2, X^2 + X*Y]) - sage: f.minimal_model() + sage: f.minimal_model() # needs sage.rings.function_field Traceback (most recent call last): ... TypeError: the function is not a morphism @@ -3178,7 +3193,7 @@ def minimal_model(self, return_transformation=False, prime_list=None, algorithm= sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem([2*x^2, y^2]) - sage: f.minimal_model(algorithm='BM') + sage: f.minimal_model(algorithm='BM') # needs sage.rings.function_field Traceback (most recent call last): ... TypeError: affine minimality is only considered for @@ -3188,7 +3203,7 @@ def minimal_model(self, return_transformation=False, prime_list=None, algorithm= sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem([2*x^2, y^2]) - sage: f.minimal_model(prime_list=[0]) + sage: f.minimal_model(prime_list=[0]) # needs sage.rings.function_field Traceback (most recent call last): ... ValueError: prime_list contains 0 which is not prime @@ -3279,7 +3294,7 @@ def all_minimal_models(self, return_transformation=False, prime_list=None, sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem([2*x^2, 3*y^2]) - sage: f.all_minimal_models() + sage: f.all_minimal_models() # needs sage.rings.function_field [Dynamical System of Projective Space of dimension 1 over Rational Field Defn: Defined on coordinates by sending (x : y) to (x^2 : y^2)] @@ -3289,9 +3304,9 @@ def all_minimal_models(self, return_transformation=False, prime_list=None, sage: P. = ProjectiveSpace(QQ, 1) sage: c = 2*3^6 sage: f = DynamicalSystem([x^3 - c^2*y^3, x*y^2]) - sage: len(f.all_minimal_models(algorithm='HS')) + sage: len(f.all_minimal_models(algorithm='HS')) # needs sage.rings.function_field 14 - sage: len(f.all_minimal_models(prime_list=[2], algorithm='HS')) + sage: len(f.all_minimal_models(prime_list=[2], algorithm='HS')) # needs sage.rings.function_field 2 :: @@ -3300,11 +3315,12 @@ def all_minimal_models(self, return_transformation=False, prime_list=None, sage: f = DynamicalSystem([237568*x^3 + 1204224*x^2*y + 2032560*x*y^2 ....: + 1142289*y^3, -131072*x^3 - 663552*x^2*y - 1118464*x*y^2 ....: - 627664*y^3]) - sage: len(f.all_minimal_models(algorithm='BM')) + sage: len(f.all_minimal_models(algorithm='BM')) # needs sage.rings.function_field 2 TESTS:: + sage: # needs sage.rings.function_field sage: P. = ProjectiveSpace(QQ, 1) sage: c = 2^2*5^2*11^3 sage: f = DynamicalSystem([x^3 - c^2*y^3, x*y^2]) @@ -3392,14 +3408,14 @@ def affine_preperiodic_model(self, m, n, return_conjugation=False): sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2, y^2, z^2]) - sage: g = f.affine_preperiodic_model(0, 1); g + sage: g = f.affine_preperiodic_model(0, 1); g # needs sage.rings.function_field Dynamical System of Projective Space of dimension 2 over Rational Field Defn: Defined on coordinates by sending (x : y : z) to (-x^2 : -2*x^2 + 2*x*y - y^2 : 2*x^2 - 2*x*y + 2*y^2 + 2*y*z + z^2) We can check that ``g`` has affine fixed points:: - sage: g.periodic_points(1) + sage: g.periodic_points(1) # needs sage.rings.function_field [(-1 : -1 : 1), (-1/2 : -1 : 1), (-1/2 : -1/2 : 1), @@ -3410,9 +3426,10 @@ def affine_preperiodic_model(self, m, n, return_conjugation=False): :: + sage: # needs sage.rings.finite_rings sage: P. = ProjectiveSpace(GF(9), 2) sage: f = DynamicalSystem_projective([x^2, y^2, z^2]) - sage: f.affine_preperiodic_model(0, 1) + sage: f.affine_preperiodic_model(0, 1) # needs sage.rings.function_field Dynamical System of Projective Space of dimension 2 over Finite Field in z2 of size 3^2 Defn: Defined on coordinates by sending (x : y : z) to @@ -3433,10 +3450,11 @@ def affine_preperiodic_model(self, m, n, return_conjugation=False): :: + sage: # needs sage.rings.number_field sage: K. = CyclotomicField(3) sage: P. = ProjectiveSpace(K, 2) sage: f = DynamicalSystem_projective([x^2 + k*x*y + y^2, z^2, y^2]) - sage: f.affine_preperiodic_model(1, 1) + sage: f.affine_preperiodic_model(1, 1) # needs sage.rings.function_field Dynamical System of Projective Space of dimension 2 over Cyclotomic Field of order 3 and degree 2 Defn: Defined on coordinates by sending (x : y : z) to @@ -3446,8 +3464,8 @@ def affine_preperiodic_model(self, m, n, return_conjugation=False): sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 + y^2, y^2]) - sage: g, mat = f.affine_preperiodic_model(0, 1, return_conjugation=True) - sage: g == f.conjugate(mat) + sage: g, mat = f.affine_preperiodic_model(0, 1, return_conjugation=True) # needs sage.rings.function_field + sage: g == f.conjugate(mat) # needs sage.rings.function_field True :: @@ -3455,7 +3473,7 @@ def affine_preperiodic_model(self, m, n, return_conjugation=False): sage: P. = ProjectiveSpace(QQ, 2) sage: X = P.subscheme(2*y - z) sage: f = DynamicalSystem_projective([x^2 + y^2, z^2 + y^2, z^2], domain=X) - sage: f.affine_preperiodic_model(0, 1) + sage: f.affine_preperiodic_model(0, 1) # needs sage.rings.function_field Dynamical System of Closed subscheme of Projective Space of dimension 2 over Rational Field defined by: 2*y - z Defn: Defined on coordinates by sending (x : y : z) to @@ -3465,8 +3483,8 @@ def affine_preperiodic_model(self, m, n, return_conjugation=False): sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 + 2*y^2, x^2]) - sage: g, mat = f.affine_preperiodic_model(0, 1, return_conjugation=True) - sage: f.conjugate(mat) == g + sage: g, mat = f.affine_preperiodic_model(0, 1, return_conjugation=True) # needs sage.rings.function_field + sage: f.conjugate(mat) == g # needs sage.rings.function_field True """ n = ZZ(n) @@ -3604,14 +3622,14 @@ def automorphism_group(self, **kwds): sage: R. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 - y^2, x*y]) - sage: f.automorphism_group(return_functions=True) + sage: f.automorphism_group(return_functions=True) # needs sage.libs.pari [x, -x] :: sage: R. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 + 5*x*y + 5*y^2, 5*x^2 + 5*x*y + y^2]) - sage: f.automorphism_group() + sage: f.automorphism_group() # needs sage.libs.pari [ [1 0] [0 2] [0 1], [2 0] @@ -3621,23 +3639,24 @@ def automorphism_group(self, **kwds): sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem([x^3, y^3, z^3]) - sage: len(f.automorphism_group()) + sage: len(f.automorphism_group()) # needs sage.rings.function_field 24 :: sage: R. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 - 2*x*y - 2*y^2, -2*x^2 - 2*x*y + y^2]) - sage: f.automorphism_group(return_functions=True) + sage: f.automorphism_group(return_functions=True) # needs sage.libs.pari [x, 1/x, -x - 1, -x/(x + 1), (-x - 1)/x, -1/(x + 1)] :: sage: R. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([3*x^2*y - y^3, x^3 - 3*x*y^2]) - sage: lst, label = f.automorphism_group(algorithm='CRT', return_functions=True, + sage: lst, label = f.automorphism_group(algorithm='CRT', # needs sage.libs.pari + ....: return_functions=True, ....: iso_type=True) - sage: sorted(lst), label + sage: sorted(lst), label # needs sage.libs.pari ([-1/x, 1/x, (-x - 1)/(x - 1), (-x + 1)/(x + 1), (x - 1)/(x + 1), (x + 1)/(x - 1), -x, x], 'Dihedral of order 8') @@ -3647,7 +3666,7 @@ def automorphism_group(self, **kwds): sage: A. = AffineSpace(QQ, 1) sage: f = DynamicalSystem_affine([1/z^3]) sage: F = f.homogenize(1) - sage: F.automorphism_group() + sage: F.automorphism_group() # needs sage.libs.pari [ [1 0] [0 2] [-1 0] [ 0 -2] [0 1], [2 0], [ 0 1], [ 2 0] @@ -3657,7 +3676,7 @@ def automorphism_group(self, **kwds): sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x**2 + x*z, y**2, z**2]) - sage: f.automorphism_group() + sage: f.automorphism_group() # needs sage.rings.function_field [ [1 0 0] [0 1 0] @@ -3666,6 +3685,7 @@ def automorphism_group(self, **kwds): :: + sage: # needs sage.rings.number_field sage: K. = CyclotomicField(3) sage: P. = ProjectiveSpace(K, 1) sage: D6 = DynamicalSystem_projective([y^2, x^2]) @@ -3712,7 +3732,7 @@ def critical_subscheme(self): sage: set_verbose(None) sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^3 - 2*x*y^2 + 2*y^3, y^3]) - sage: f.critical_subscheme() + sage: f.critical_subscheme() # needs sage.rings.function_field Closed subscheme of Projective Space of dimension 1 over Rational Field defined by: 9*x^2*y^2 - 6*y^4 @@ -3722,7 +3742,7 @@ def critical_subscheme(self): sage: set_verbose(None) sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([2*x^2 - y^2, x*y]) - sage: f.critical_subscheme() + sage: f.critical_subscheme() # needs sage.rings.function_field Closed subscheme of Projective Space of dimension 1 over Rational Field defined by: 4*x^2 + 2*y^2 @@ -3731,13 +3751,14 @@ def critical_subscheme(self): sage: P. = ProjectiveSpace(QQ,2) sage: f = DynamicalSystem_projective([2*x^2 - y^2, x*y, z^2]) - sage: f.critical_subscheme() + sage: f.critical_subscheme() # needs sage.rings.function_field Closed subscheme of Projective Space of dimension 2 over Rational Field defined by: 8*x^2*z + 4*y^2*z :: + sage: # needs sage.rings.finite_rings sage: P. = ProjectiveSpace(GF(81), 3) sage: g = DynamicalSystem_projective([x^3 + y^3, y^3 + z^3, z^3 + x^3, w^3]) sage: g.critical_subscheme() @@ -3749,7 +3770,7 @@ def critical_subscheme(self): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^2, x*y]) - sage: f.critical_subscheme() + sage: f.critical_subscheme() # needs sage.rings.function_field Traceback (most recent call last): ... TypeError: the function is not a morphism @@ -3781,10 +3802,10 @@ def critical_points(self, R=None): sage: set_verbose(None) sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^3 - 2*x*y^2 + 2*y^3, y^3]) - sage: f.critical_points() + sage: f.critical_points() # needs sage.rings.function_field [(1 : 0)] - sage: K. = QuadraticField(6) - sage: f.critical_points(K) + sage: K. = QuadraticField(6) # needs sage.rings.number_field + sage: f.critical_points(K) # needs sage.rings.number_field [(-1/3*w : 1), (1/3*w : 1), (1 : 0)] :: @@ -3792,7 +3813,7 @@ def critical_points(self, R=None): sage: set_verbose(None) sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([2*x^2 - y^2, x*y]) - sage: f.critical_points(QQbar) + sage: f.critical_points(QQbar) # needs sage.rings.number_field [(-0.7071067811865475?*I : 1), (0.7071067811865475?*I : 1)] """ PS = self.domain() @@ -3838,28 +3859,28 @@ def ramification_type(self, R=None, stable=True): sage: P. = ProjectiveSpace(QQ, 1) sage: F = DynamicalSystem_projective([x^4, y^4]) - sage: F.ramification_type() + sage: F.ramification_type() # needs sage.rings.number_field [[4], [4]] sage: P. = ProjectiveSpace(QQ, 1) sage: F = DynamicalSystem_projective([x^3, 4*y^3 - 3*x^2*y]) - sage: F.ramification_type() + sage: F.ramification_type() # needs sage.rings.number_field [[2], [2], [3]] sage: P. = ProjectiveSpace(QQ, 1) sage: F = DynamicalSystem_projective([(x + y)^4, 16*x*y*(x-y)^2]) - sage: F.ramification_type() + sage: F.ramification_type() # needs sage.rings.number_field [[2], [2, 2], [4]] sage: P. = ProjectiveSpace(QQ, 1) sage: F = DynamicalSystem_projective([(x + y)*(x - y)^3, y*(2*x+y)^3]) - sage: F.ramification_type() + sage: F.ramification_type() # needs sage.rings.number_field [[3], [3], [3]] sage: F = DynamicalSystem_projective([x^3 - 2*x*y^2 + 2*y^3, y^3]) - sage: F.ramification_type() + sage: F.ramification_type() # needs sage.rings.number_field [[2], [2], [3]] - sage: F.ramification_type(R=F.base_ring()) + sage: F.ramification_type(R=F.base_ring()) # needs sage.rings.function_field [[2], [3]] """ @@ -3910,23 +3931,24 @@ def is_postcritically_finite(self, err=0.01, use_algebraic_closure=True): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^2 - y^2, y^2]) - sage: f.is_postcritically_finite() + sage: f.is_postcritically_finite() # needs sage.rings.number_field True :: sage: P. = ProjectiveSpace(QQ,1) - sage: f = DynamicalSystem_projective([x^3- y^3, y^3]) - sage: f.is_postcritically_finite() + sage: f = DynamicalSystem_projective([x^3 - y^3, y^3]) + sage: f.is_postcritically_finite() # needs sage.rings.number_field False :: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = NumberField(z^8 + 3*z^6 + 3*z^4 + z^2 + 1) sage: PS. = ProjectiveSpace(K,1) sage: f = DynamicalSystem_projective([x^3 + v*y^3, y^3]) - sage: f.is_postcritically_finite() # long time + sage: f.is_postcritically_finite() # long time True :: @@ -3934,11 +3956,12 @@ def is_postcritically_finite(self, err=0.01, use_algebraic_closure=True): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([6*x^2 + 16*x*y + 16*y^2, ....: -3*x^2 - 4*x*y - 4*y^2]) - sage: f.is_postcritically_finite() + sage: f.is_postcritically_finite() # needs sage.rings.number_field True :: + sage: # needs sage.libs.gap sage.rings.number_field sage: K = UniversalCyclotomicField() sage: P. = ProjectiveSpace(K,1) sage: F = DynamicalSystem_projective([x^2 - y^2, y^2], domain=P) @@ -3956,11 +3979,12 @@ def is_postcritically_finite(self, err=0.01, use_algebraic_closure=True): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^4 - x^2*y^2 + y^4, y^4]) - sage: f.is_postcritically_finite(use_algebraic_closure=False) + sage: f.is_postcritically_finite(use_algebraic_closure=False) # needs sage.rings.number_field False :: + sage: # needs sage.rings.number_field sage: P. = ProjectiveSpace(QQbar,1) sage: f = DynamicalSystem_projective([x^4 - x^2*y^2, y^4]) sage: f.is_postcritically_finite() @@ -4007,27 +4031,28 @@ def is_dynamical_belyi_map(self): EXAMPLES:: - sage: P.=ProjectiveSpace(QQ, 1) + sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([-2*x^3 - 9*x^2*y - 12*x*y^2 - 6*y^3, y^3]) - sage: f.is_dynamical_belyi_map() + sage: f.is_dynamical_belyi_map() # needs sage.rings.number_field True :: sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([5*x^7 - 7*x^6*y, -7*x*y^6 + 5*y^7]) - sage: f.is_dynamical_belyi_map() + sage: f.is_dynamical_belyi_map() # needs sage.rings.number_field True :: sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 + y^2, y^2]) - sage: f.is_dynamical_belyi_map() + sage: f.is_dynamical_belyi_map() # needs sage.rings.number_field False :: + sage: # needs sage.rings.number_field sage: F = QuadraticField(-7) sage: P. = ProjectiveSpace(F, 1) sage: f = DynamicalSystem_projective([5*x^7 - 7*x^6*y, -7*x*y^6 + 5*y^7]) @@ -4037,12 +4062,14 @@ def is_dynamical_belyi_map(self): :: sage: P. = ProjectiveSpace(QQ, 1) - sage: f = DynamicalSystem_projective([2*x^3 + 3*x^2*y - 3*x*y^2 + 2*y^3, x^3 + y^3]) - sage: f.is_dynamical_belyi_map() + sage: f = DynamicalSystem_projective([2*x^3 + 3*x^2*y - 3*x*y^2 + 2*y^3, + ....: x^3 + y^3]) + sage: f.is_dynamical_belyi_map() # needs sage.rings.number_field False :: + sage: # needs sage.rings.number_field sage: R. = PolynomialRing(QQ) sage: N. = NumberField(t^3 - 2) sage: P. = ProjectiveSpace(N, 1) @@ -4054,7 +4081,7 @@ def is_dynamical_belyi_map(self): sage: P. = ProjectiveSpace(GF(7), 1) sage: f = DynamicalSystem_projective([x^3 + 6*y^3, y^3]) - sage: f.is_dynamical_belyi_map() + sage: f.is_dynamical_belyi_map() # needs sage.libs.pari False """ P = self.codomain() @@ -4097,37 +4124,39 @@ def critical_point_portrait(self, check=True, use_algebraic_closure=True): EXAMPLES:: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = NumberField(z^6 + 2*z^5 + 2*z^4 + 2*z^3 + z^2 + 1) sage: PS. = ProjectiveSpace(K,1) sage: f = DynamicalSystem_projective([x^2 + v*y^2, y^2]) - sage: f.critical_point_portrait(check=False) # long time + sage: f.critical_point_portrait(check=False) # long time # needs sage.graphs Looped digraph on 6 vertices :: sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^5 + 5/4*x*y^4, y^5]) - sage: f.critical_point_portrait(check=False) + sage: f.critical_point_portrait(check=False) # needs sage.graphs sage.rings.number_field Looped digraph on 5 vertices :: sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^2 + 2*y^2, y^2]) - sage: f.critical_point_portrait() + sage: f.critical_point_portrait() # needs sage.rings.number_field Traceback (most recent call last): ... TypeError: map must be post-critically finite :: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = NumberField(t^3 + 2*t^2 + t + 1) sage: phi = K.embeddings(QQbar)[0] sage: P. = ProjectiveSpace(K, 1) sage: f = DynamicalSystem_projective([x^2 + v*y^2, y^2]) - sage: f.change_ring(phi).critical_point_portrait() + sage: f.change_ring(phi).critical_point_portrait() # needs sage.graphs Looped digraph on 4 vertices :: @@ -4139,16 +4168,17 @@ def critical_point_portrait(self, check=True, use_algebraic_closure=True): :: + sage: # needs sage.rings.number_field sage: P. = ProjectiveSpace(QQbar,1) sage: f = DynamicalSystem_projective([8*x^4 - 8*x^2*y^2 + y^4, y^4]) - sage: f.critical_point_portrait() #long time + sage: f.critical_point_portrait() # long time # needs sage.graphs Looped digraph on 6 vertices :: sage: P. = ProjectiveSpace(GF(3),1) sage: f = DynamicalSystem_projective([x^2 + x*y - y^2, x*y]) - sage: f.critical_point_portrait(use_algebraic_closure=False) + sage: f.critical_point_portrait(use_algebraic_closure=False) # needs sage.libs.pari Looped digraph on 6 vertices sage: f.critical_point_portrait() #long time Looped digraph on 6 vertices @@ -4222,11 +4252,12 @@ def critical_height(self, **kwds): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^3 + 7*y^3, 11*y^3]) - sage: f.critical_height() + sage: f.critical_height() # needs sage.rings.number_field 1.1989273321156851418802151128 :: + sage: # needs sage.rings.number_field sage: K. = QuadraticField(2) sage: P. = ProjectiveSpace(K,1) sage: f = DynamicalSystem_projective([x^2 + w*y^2, y^2]) @@ -4237,16 +4268,16 @@ def critical_height(self, **kwds): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^3 - 3/4*x*y^2 + 3/4*y^3, y^3]) - sage: f.critical_height(error_bound=0.0001) + sage: f.critical_height(error_bound=0.0001) # needs sage.rings.number_field 0.00000000000000000000000000000 :: sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^3 + 3*x*y^2, y^3]) - sage: f.critical_height(use_algebraic_closure=False) + sage: f.critical_height(use_algebraic_closure=False) # needs sage.rings.number_field 0.000023477016733897112886491967991 - sage: f.critical_height() + sage: f.critical_height() # needs sage.rings.number_field 0.000023477016733897112886491967991 """ PS = self.codomain() @@ -4321,30 +4352,31 @@ def preperiodic_points(self, m, n, **kwds): EXAMPLES:: - sage: P. = ProjectiveSpace(QQbar, 1) - sage: f = DynamicalSystem_projective([x^2 - y^2, y^2]) - sage: f.preperiodic_points(0, 1) + sage: P. = ProjectiveSpace(QQbar, 1) # needs sage.rings.number_field + sage: f = DynamicalSystem_projective([x^2 - y^2, y^2]) # needs sage.rings.number_field + sage: f.preperiodic_points(0, 1) # needs sage.rings.number_field [(-0.618033988749895? : 1), (1 : 0), (1.618033988749895? : 1)] :: sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 - 29/16*y^2, y^2]) - sage: f.preperiodic_points(1, 3) + sage: f.preperiodic_points(1, 3) # needs sage.rings.function_field [(-5/4 : 1), (1/4 : 1), (7/4 : 1)] :: sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2 - 3/4*y^2, y^2 , z^2]) - sage: f.preperiodic_points(0, 2, formal=True) + sage: f.preperiodic_points(0, 2, formal=True) # needs sage.rings.function_field [(-1/2 : 1 : 0), (-1/2 : 1 : 1)] :: + sage: # needs sage.rings.number_field sage: P. = ProjectiveSpace(QQbar, 1) sage: f = DynamicalSystem_projective([x^2 - x*y + 2*y^2, x^2 - y^2]) - sage: f.preperiodic_points(1, 2, minimal=False) + sage: f.preperiodic_points(1, 2, minimal=False) # needs sage.rings.function_field [(-3.133185666641252? : 1), (-1 : 1), (-0.3478103847799310? - 1.028852254136693?*I : 1), @@ -4358,11 +4390,12 @@ def preperiodic_points(self, m, n, **kwds): :: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = NumberField(w^6 - 3*w^5 + 5*w^4 - 5*w^3 + 5*w^2 - 3*w + 1) sage: P. = ProjectiveSpace(K, 2) sage: f = DynamicalSystem_projective([x^2 + z^2, y^2 + x^2, z^2 + y^2]) - sage: sorted(f.preperiodic_points(0, 1), key=str) + sage: sorted(f.preperiodic_points(0, 1), key=str) # needs sage.rings.function_field [(-2*s^5 + 4*s^4 - 5*s^3 + 3*s^2 - 4*s : -2*s^5 + 5*s^4 - 7*s^3 + 6*s^2 - 7*s + 3 : 1), (-s^5 + 3*s^4 - 4*s^3 + 4*s^2 - 4*s + 2 : -s^5 + 2*s^4 - 2*s^3 + s^2 - s : 1), (-s^5 + 3*s^4 - 5*s^3 + 4*s^2 - 3*s + 1 : s^5 - 2*s^4 + 3*s^3 - 3*s^2 + 4*s - 1 : 1), @@ -4382,11 +4415,12 @@ def preperiodic_points(self, m, n, **kwds): sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 - 3/4*y^2, y^2]) - sage: f.preperiodic_points(0, 2, formal=True) + sage: f.preperiodic_points(0, 2, formal=True) # needs sage.libs.pari [(-1/2 : 1)] :: + sage: # needs sage.rings.number_field sage: P. = ProjectiveSpace(QQ, 1) sage: K. = QuadraticField(5) sage: phi = QQ.embeddings(K)[0] @@ -4400,14 +4434,14 @@ def preperiodic_points(self, m, n, **kwds): sage: X = P.subscheme(2*x - y) sage: f = DynamicalSystem_projective([x^2 - y^2, 2*(x^2 - y^2), y^2 - z^2], ....: domain=X) - sage: f.preperiodic_points(1, 1) + sage: f.preperiodic_points(1, 1) # needs sage.rings.function_field [(-1/4 : -1/2 : 1), (1 : 2 : 1)] :: sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2 - 3/4*y^2, z^2, y^2]) - sage: f.preperiodic_points(1, 1) + sage: f.preperiodic_points(1, 1) # needs sage.rings.function_field [(-3/2 : -1 : 1), (-3/2 : 1 : 1), (-1/2 : -1 : 1), (1/2 : -1 : 1), (1/2 : 1 : 1), (3/2 : -1 : 1)] @@ -4415,7 +4449,7 @@ def preperiodic_points(self, m, n, **kwds): sage: P. = ProjectiveSpace(GF(5), 2) sage: f = DynamicalSystem_projective([x^2, y^2, z^2]) - sage: sorted(f.preperiodic_points(2, 1)) + sage: sorted(f.preperiodic_points(2, 1)) # needs sage.rings.function_field [(0 : 2 : 1), (0 : 3 : 1), (1 : 2 : 1), (1 : 3 : 1), (2 : 0 : 1), (2 : 1 : 0), (2 : 1 : 1), (2 : 2 : 1), (2 : 3 : 1), (2 : 4 : 1), (3 : 0 : 1), (3 : 1 : 0), (3 : 1 : 1), (3 : 2 : 1), (3 : 3 : 1), (3 : 4 : 1), (4 : 2 : 1), (4 : 3 : 1)] @@ -4437,16 +4471,16 @@ def preperiodic_points(self, m, n, **kwds): sage: P. = ProjectiveSpace(QQ, 1) sage: R. = QQ[] - sage: K. = NumberField(z^4 - z^2 - 1) + sage: K. = NumberField(z^4 - z^2 - 1) # needs sage.rings.number_field sage: f = DynamicalSystem_projective([x^2 - y^2, y^2]) - sage: sorted(f.preperiodic_points(2, 1, R=K), key=str) + sage: sorted(f.preperiodic_points(2, 1, R=K), key=str) # needs sage.rings.number_field [(-v : 1), (v : 1)] :: sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2 - 3/4*y^2, y^2, z^2]) - sage: f.preperiodic_points(0, 2, formal=True) + sage: f.preperiodic_points(0, 2, formal=True) # needs sage.rings.function_field [(-1/2 : 1 : 0), (-1/2 : 1 : 1)] :: @@ -4455,7 +4489,7 @@ def preperiodic_points(self, m, n, **kwds): sage: R. = PolynomialRing(S, 2) sage: P = ProjectiveSpace(R) sage: f = DynamicalSystem_projective([x^2 + c*y^2, y^2]) - sage: f.preperiodic_points(1, 2, return_scheme=True) + sage: f.preperiodic_points(1, 2, return_scheme=True) # needs sage.rings.function_field Closed subscheme of Projective Space of dimension 1 over Univariate Polynomial Ring in c over Rational Field defined by: x^2 - x*y + (c + 1)*y^2 @@ -4464,7 +4498,7 @@ def preperiodic_points(self, m, n, **kwds): sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2, x*y, z^2]) - sage: f.preperiodic_points(2, 1, minimal=False) + sage: f.preperiodic_points(2, 1, minimal=False) # needs sage.rings.function_field Traceback (most recent call last): ... TypeError: use return_scheme=True @@ -4486,14 +4520,14 @@ def preperiodic_points(self, m, n, **kwds): sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem([x^2 - z^2, y^2 - 21/16*z^2, z^2]) - sage: len(f.preperiodic_points(1, 2, minimal=True, formal=False)) == 16 + sage: len(f.preperiodic_points(1, 2, minimal=True, formal=False)) == 16 # needs sage.rings.function_field True :: sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2 - y^2, 2*(x^2 - y^2), y^2 - z^2]) - sage: f.preperiodic_points(2, 2) + sage: f.preperiodic_points(2, 2) # needs sage.rings.function_field Traceback (most recent call last): ... ValueError: dynamical system is not a morphism, @@ -4595,7 +4629,7 @@ def preperiodic_points(self, m, n, **kwds): if return_scheme: # this includes the indeterminacy locus points! return X if X.dimension() <= 0: - if R in NumberFields() or R is QQbar or R in FiniteFields(): + if R in NumberFields() or isinstance(R, sage.rings.abc.AlgebraicField) or R in FiniteFields(): Z = f.base_indeterminacy_locus() points = [dom(Q) for Q in X.rational_points()] good_points = [] @@ -4661,6 +4695,7 @@ def periodic_points(self, n, minimal=True, formal=False, R=None, algorithm='vari EXAMPLES:: + sage: # needs sage.rings.number_field sage: set_verbose(None) sage: P. = ProjectiveSpace(QQbar, 1) sage: f = DynamicalSystem_projective([x^2 - x*y + y^2, x^2 - y^2 + x*y]) @@ -4671,6 +4706,7 @@ def periodic_points(self, n, minimal=True, formal=False, R=None, algorithm='vari :: + sage: # needs sage.rings.number_field sage: P. = ProjectiveSpace(QuadraticField(5,'t'), 2) sage: f = DynamicalSystem_projective([x^2 - 21/16*z^2, y^2 - z^2, z^2]) sage: f.periodic_points(2) @@ -4683,16 +4719,17 @@ def periodic_points(self, n, minimal=True, formal=False, R=None, algorithm='vari sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2 - 3/4*y^2, y^2 , z^2]) - sage: f.periodic_points(2, formal=True) + sage: f.periodic_points(2, formal=True) # needs sage.rings.function_field [(-1/2 : 1 : 0), (-1/2 : 1 : 1)] :: + sage: # needs sage.rings.number_field sage: w = QQ['w'].0 sage: K = NumberField(w^6 - 3*w^5 + 5*w^4 - 5*w^3 + 5*w^2 - 3*w + 1,'s') sage: P. = ProjectiveSpace(K, 2) sage: f = DynamicalSystem_projective([x^2 + z^2, y^2 + x^2, z^2 + y^2]) - sage: sorted(f.periodic_points(1), key=str) + sage: sorted(f.periodic_points(1), key=str) # needs sage.rings.function_field [(-2*s^5 + 4*s^4 - 5*s^3 + 3*s^2 - 4*s : -2*s^5 + 5*s^4 - 7*s^3 + 6*s^2 - 7*s + 3 : 1), (-s^5 + 3*s^4 - 4*s^3 + 4*s^2 - 4*s + 2 : -s^5 + 2*s^4 - 2*s^3 + s^2 - s : 1), (-s^5 + 3*s^4 - 5*s^3 + 4*s^2 - 3*s + 1 : s^5 - 2*s^4 + 3*s^3 - 3*s^2 + 4*s - 1 : 1), @@ -4705,7 +4742,7 @@ def periodic_points(self, n, minimal=True, formal=False, R=None, algorithm='vari sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2 - 21/16*z^2, y^2 - 2*z^2, z^2]) - sage: f.periodic_points(2, False) + sage: f.periodic_points(2, False) # needs sage.rings.function_field [(-5/4 : -1 : 1), (-5/4 : 2 : 1), (-3/4 : -1 : 1), (-3/4 : 2 : 1), (0 : 1 : 0), (1/4 : -1 : 1), (1/4 : 2 : 1), (1 : 0 : 0), (1 : 1 : 0), (7/4 : -1 : 1), (7/4 : 2 : 1)] @@ -4714,7 +4751,7 @@ def periodic_points(self, n, minimal=True, formal=False, R=None, algorithm='vari sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2 - 21/16*z^2, y^2 - 2*z^2, z^2]) - sage: f.periodic_points(2) + sage: f.periodic_points(2) # needs sage.rings.function_field [(-5/4 : -1 : 1), (-5/4 : 2 : 1), (1/4 : -1 : 1), (1/4 : 2 : 1)] :: @@ -4722,7 +4759,7 @@ def periodic_points(self, n, minimal=True, formal=False, R=None, algorithm='vari sage: set_verbose(None) sage: P. = ProjectiveSpace(ZZ, 1) sage: f = DynamicalSystem_projective([x^2 + y^2, y^2]) - sage: f.periodic_points(2, R=QQbar, minimal=False) + sage: f.periodic_points(2, R=QQbar, minimal=False) # needs sage.rings.number_field [(-0.50000000000000000? - 1.322875655532296?*I : 1), (-0.50000000000000000? + 1.322875655532296?*I : 1), (0.50000000000000000? - 0.866025403784439?*I : 1), @@ -4733,23 +4770,24 @@ def periodic_points(self, n, minimal=True, formal=False, R=None, algorithm='vari sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2 - 3/4*z^2, y^2 - 3/4*z^2, z^2]) - sage: f.periodic_points(2, formal=True) + sage: f.periodic_points(2, formal=True) # needs sage.rings.function_field [(-1/2 : -1/2 : 1), (-1/2 : 3/2 : 1), (3/2 : -1/2 : 1)] :: sage: P. = ProjectiveSpace(GF(307), 1) sage: f = DynamicalSystem_projective([x^10 + y^10, y^10]) - sage: f.periodic_points(16, minimal=True, algorithm='cyclegraph') + sage: f.periodic_points(16, minimal=True, algorithm='cyclegraph') # needs sage.graphs [(69 : 1), (185 : 1), (120 : 1), (136 : 1), (97 : 1), (183 : 1), (170 : 1), (105 : 1), (274 : 1), (275 : 1), (154 : 1), (156 : 1), (87 : 1), (95 : 1), (161 : 1), (128 : 1)] :: + sage: # needs sage.rings.finite_rings sage: P. = ProjectiveSpace(GF(13^2, 't'), 1) sage: f = DynamicalSystem_projective([x^3 + 3*y^3, x^2*y]) - sage: f.periodic_points(30, minimal=True, algorithm='cyclegraph') + sage: f.periodic_points(30, minimal=True, algorithm='cyclegraph') # needs sage.graphs [(t + 3 : 1), (6*t + 6 : 1), (7*t + 1 : 1), (2*t + 8 : 1), (3*t + 4 : 1), (10*t + 12 : 1), (8*t + 10 : 1), (5*t + 11 : 1), (7*t + 4 : 1), (4*t + 8 : 1), (9*t + 1 : 1), (2*t + 2 : 1), @@ -4763,36 +4801,37 @@ def periodic_points(self, n, minimal=True, formal=False, R=None, algorithm='vari sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([3*x^2 + 5*y^2, y^2]) - sage: f.periodic_points(2, R=GF(3), minimal=False) + sage: f.periodic_points(2, R=GF(3), minimal=False) # needs sage.rings.function_field [(2 : 1)] - sage: f.periodic_points(2, R=GF(7)) + sage: f.periodic_points(2, R=GF(7)) # needs sage.rings.function_field [] :: sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2, x*y, z^2]) - sage: f.periodic_points(1) + sage: f.periodic_points(1) # needs sage.rings.function_field Traceback (most recent call last): ... TypeError: use return_scheme=True :: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = NumberField(x^2 - x + 3) sage: P. = ProjectiveSpace(K, 2) sage: X = P.subscheme(2*x - y) sage: f = DynamicalSystem_projective([x^2 - y^2, 2*(x^2 - y^2), y^2 - z^2], ....: domain=X) - sage: f.periodic_points(2) + sage: f.periodic_points(2) # needs sage.rings.function_field [(-1/5*u - 1/5 : -2/5*u - 2/5 : 1), (1/5*u - 2/5 : 2/5*u - 4/5 : 1)] :: sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2 - y^2, x^2 - z^2, y^2 - z^2]) - sage: f.periodic_points(1) + sage: f.periodic_points(1) # needs sage.rings.function_field [(-1 : 0 : 1)] sage: f.periodic_points(1, return_scheme=True) Closed subscheme of Projective Space of dimension 2 over Rational Field @@ -4805,7 +4844,7 @@ def periodic_points(self, n, minimal=True, formal=False, R=None, algorithm='vari sage: P.=ProjectiveSpace(GF(3), 1) sage: f = DynamicalSystem_projective([x^2 - 2*y^2, y^2]) - sage: f.periodic_points(2, R=GF(3^2,'t')) + sage: f.periodic_points(2, R=GF(3^2,'t')) # needs sage.rings.finite_rings [(t + 2 : 1), (2*t : 1)] :: @@ -4814,7 +4853,7 @@ def periodic_points(self, n, minimal=True, formal=False, R=None, algorithm='vari sage: R. = PolynomialRing(S, 2) sage: P = ProjectiveSpace(R) sage: f = DynamicalSystem_projective([x^2 + c*y^2, y^2]) - sage: f.periodic_points(2, return_scheme=True) + sage: f.periodic_points(2, return_scheme=True) # needs sage.rings.function_field Closed subscheme of Projective Space of dimension 1 over Univariate Polynomial Ring in c over Rational Field defined by: x^2 + x*y + (c + 1)*y^2 @@ -4823,15 +4862,16 @@ def periodic_points(self, n, minimal=True, formal=False, R=None, algorithm='vari sage: P. = ProjectiveSpace(ZZ, 2) sage: f = DynamicalSystem([x^2 - 2*y^2, y^2, z^2]) - sage: X = f.periodic_points(2, minimal=False, formal=True, return_scheme=True) # long time - sage: len(X.defining_polynomials()) # long time + sage: X = f.periodic_points(2, minimal=False, formal=True, # long time + ....: return_scheme=True) + sage: len(X.defining_polynomials()) # long time 19 TESTS:: sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2 - y^2, 2*(x^2 - y^2), y^2 - z^2]) - sage: f.periodic_points(2, minimal=True) + sage: f.periodic_points(2, minimal=True) # needs sage.rings.function_field Traceback (most recent call last): ... ValueError: dynamical system is not a morphism, cannot calculate minimal or formal periodic points @@ -4941,7 +4981,7 @@ def periodic_points(self, n, minimal=True, formal=False, R=None, algorithm='vari if return_scheme: # this includes the indeterminacy locus points! return X if X.change_ring(FF).dimension() <= 0: - if R in NumberFields() or R is QQbar or R in FiniteFields(): + if R in NumberFields() or isinstance(R, sage.rings.abc.AlgebraicField) or R in FiniteFields(): Z = f.base_indeterminacy_locus() points = [dom(Q) for Q in X.rational_points()] good_points = [] @@ -5012,16 +5052,16 @@ def multiplier_spectra(self, n, formal=False, type='point', use_algebraic_closur sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 - 3/4*y^2, y^2]) - sage: sorted(f.multiplier_spectra(2, type='point')) + sage: sorted(f.multiplier_spectra(2, type='point')) # needs sage.rings.number_field [0, 1, 1, 1, 9] - sage: sorted(f.multiplier_spectra(2, type='cycle')) + sage: sorted(f.multiplier_spectra(2, type='cycle')) # needs sage.rings.number_field [0, 1, 1, 9] :: sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2, z^2, y^2]) - sage: f.multiplier_spectra(1) + sage: f.multiplier_spectra(1) # needs sage.rings.number_field [ [ 2 1 - 1.732050807568878?*I] [ 0 -2], @@ -5045,6 +5085,7 @@ def multiplier_spectra(self, n, formal=False, type='point', use_algebraic_closur :: + sage: # needs sage.rings.number_field sage: set_verbose(None) sage: z = QQ['z'].0 sage: K. = NumberField(z^4 - 4*z^2 + 1,'z') @@ -5064,7 +5105,7 @@ def multiplier_spectra(self, n, formal=False, type='point', use_algebraic_closur ....: + 2317935971590902*x^4*y^6 - 15344764859590852*x^3*y^7 ....: + 2561851642765275*x^2*y^8 + 113578270285012470*x*y^9 ....: - 150049940203963800*y^10, 4608*y^10]) - sage: sorted(f.multiplier_spectra(1)) + sage: sorted(f.multiplier_spectra(1)) # needs sage.rings.number_field [-119820502365680843999, -7198147681176255644585/256, -3086380435599991/9, @@ -5081,22 +5122,22 @@ def multiplier_spectra(self, n, formal=False, type='point', use_algebraic_closur sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 - 7/4*y^2, y^2]) - sage: f.multiplier_spectra(3, formal=True, type='cycle') + sage: f.multiplier_spectra(3, formal=True, type='cycle') # needs sage.rings.number_field [1, 1] - sage: f.multiplier_spectra(3, formal=True, type='point') + sage: f.multiplier_spectra(3, formal=True, type='point') # needs sage.rings.number_field [1, 1, 1, 1, 1, 1] :: sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^4 + 3*y^4, 4*x^2*y^2]) - sage: f.multiplier_spectra(1, use_algebraic_closure=False) + sage: f.multiplier_spectra(1, use_algebraic_closure=False) # needs sage.rings.number_field [0, -1, 1/128*a^5 - 13/384*a^4 + 5/96*a^3 + 1/16*a^2 + 43/128*a + 303/128, -1/288*a^5 + 1/96*a^4 + 1/24*a^3 - 1/3*a^2 + 5/32*a - 115/32, -5/1152*a^5 + 3/128*a^4 - 3/32*a^3 + 13/48*a^2 - 63/128*a - 227/128] - sage: f.multiplier_spectra(1) + sage: f.multiplier_spectra(1) # needs sage.rings.number_field [0, -1, 1.951373035591442?, @@ -5107,13 +5148,14 @@ def multiplier_spectra(self, n, formal=False, type='point', use_algebraic_closur sage: P. = ProjectiveSpace(GF(5), 1) sage: f = DynamicalSystem_projective([x^4 + 2*y^4, 4*x^2*y^2]) - sage: f.multiplier_spectra(1, use_algebraic_closure=False) + sage: f.multiplier_spectra(1, use_algebraic_closure=False) # needs sage.rings.finite_rings [0, 3*a + 3, 2*a + 1, 1, 1] sage: f.multiplier_spectra(1) [0, 2*z2 + 1, 3*z2 + 3, 1, 1] :: + sage: # needs sage.rings.number_field sage: P. = ProjectiveSpace(QQbar, 1) sage: f = DynamicalSystem_projective([x^5 + 3*y^5, 4*x^3*y^2]) sage: f.multiplier_spectra(1) @@ -5136,7 +5178,7 @@ def multiplier_spectra(self, n, formal=False, type='point', use_algebraic_closur sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 + y^2, x*y]) - sage: f.multiplier_spectra(1) + sage: f.multiplier_spectra(1) # needs sage.rings.number_field [1, 1, 1] :: @@ -5144,7 +5186,7 @@ def multiplier_spectra(self, n, formal=False, type='point', use_algebraic_closur sage: K = GF(3).algebraic_closure() sage: P. = ProjectiveSpace(K, 2) sage: f = DynamicalSystem_projective([x^2 + 2*y^2, 4*x*y, z^2]) - sage: f.multiplier_spectra(1) + sage: f.multiplier_spectra(1) # needs sage.rings.number_field [ [0 0] [1 0] [1 0] [1 0] [2 0] [2 0] [2 0] [0 0], [0 0], [0 0], [0 0], [0 1], [0 1], [0 1] @@ -5153,7 +5195,7 @@ def multiplier_spectra(self, n, formal=False, type='point', use_algebraic_closur :: sage: F. = GF(7) - sage: P.=ProjectiveSpace(F, 1) + sage: P. = ProjectiveSpace(F, 1) sage: f = DynamicalSystem_projective([x^2 + y^2, y^2]) sage: sorted(f.multiplier_spectra(1)) [0, 3, 6] @@ -5162,12 +5204,13 @@ def multiplier_spectra(self, n, formal=False, type='point', use_algebraic_closur sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2, z^2, y^2]) - sage: g = f.change_ring(QQbar) - sage: f.multiplier_spectra(1) == g.multiplier_spectra(1) # long time + sage: g = f.change_ring(QQbar) # needs sage.rings.number_field + sage: f.multiplier_spectra(1) == g.multiplier_spectra(1) # long time, needs sage.rings.number_field True :: + sage: # needs sage.rings.number_field sage: K. = QuadraticField(5) sage: P. = ProjectiveSpace(K, 2) sage: f = DynamicalSystem_projective([x^2 + w*x*y + y^2, y^2, z^2]) @@ -5189,7 +5232,7 @@ def multiplier_spectra(self, n, formal=False, type='point', use_algebraic_closur sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2, z^2, y^2]) - sage: f.multiplier_spectra(1, use_algebraic_closure=False) + sage: f.multiplier_spectra(1, use_algebraic_closure=False) # needs sage.rings.function_field Traceback (most recent call last): ... ValueError: failed to compute the full multiplier spectra. Try use_algebraic_closure=True @@ -5209,7 +5252,7 @@ def multiplier_spectra(self, n, formal=False, type='point', use_algebraic_closur # if we are already using an algebraic closure, we move the # map into a finite extension and set use_algebraic_closure to True # in order to get a scheme defined over a finite extension - if K is QQbar or isinstance(K, AlgebraicClosureFiniteField_generic): + if isinstance(K, sage.rings.abc.AlgebraicField) or isinstance(K, AlgebraicClosureFiniteField_generic): f = self.reduce_base_field() K = f.base_ring() use_algebraic_closure = True @@ -5496,7 +5539,7 @@ def sigma_invariants(self, n, formal=False, embedding=None, type='point', sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 + x*y + y^2, y^2 + x*y]) - sage: f.sigma_invariants(1) + sage: f.sigma_invariants(1) # needs sage.rings.number_field [3, 3, 1] If ``return_polynomial`` is ``True``, then following [Hutz2019]_ @@ -5513,7 +5556,7 @@ def sigma_invariants(self, n, formal=False, embedding=None, type='point', sage: w, t = poly.variables() sage: poly.specialization({w:0}).monic() t^3 - 2*t^2 + 8*t - sage: f.sigma_invariants(1) + sage: f.sigma_invariants(1) # needs sage.rings.number_field [2, 8, 0] For dynamical systems on `\mathbb{P}^N`, where `N > 1`, the full polynomial @@ -5554,6 +5597,7 @@ def sigma_invariants(self, n, formal=False, embedding=None, type='point', :: + sage: # needs sage.rings.number_field sage: set_verbose(None) sage: z = QQ['z'].0 sage: K = NumberField(z^4 - 4*z^2 + 1, 'z') @@ -5566,6 +5610,7 @@ def sigma_invariants(self, n, formal=False, embedding=None, type='point', check that infinity as part of a longer cycle is handled correctly:: + sage: # needs sage.rings.number_field sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([y^2, x^2]) sage: f.sigma_invariants(2, type='cycle') @@ -5579,6 +5624,7 @@ def sigma_invariants(self, n, formal=False, embedding=None, type='point', :: + sage: # needs sage.rings.number_field sage: K. = QuadraticField(3) sage: P. = ProjectiveSpace(K, 1) sage: f = DynamicalSystem_projective([x^2 - w*y^2, (1-w)*x*y]) @@ -5592,7 +5638,7 @@ def sigma_invariants(self, n, formal=False, embedding=None, type='point', sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([512*x^5 - 378128*x^4*y + 76594292*x^3*y^2 ....: - 4570550136*x^2*y^3 - 2630045017*x*y^4 + 28193217129*y^5, 512*y^5]) - sage: f.sigma_invariants(1) + sage: f.sigma_invariants(1) # needs sage.rings.number_field [19575526074450617/1048576, -9078122048145044298567432325/2147483648, -2622661114909099878224381377917540931367/1099511627776, -2622661107937102104196133701280271632423/549755813888, @@ -5609,6 +5655,7 @@ def sigma_invariants(self, n, formal=False, embedding=None, type='point', :: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: Pc. = ProjectiveSpace(R, 1) sage: f = DynamicalSystem_projective([x^2 + c*y^2, y^2]) @@ -5626,7 +5673,8 @@ def sigma_invariants(self, n, formal=False, embedding=None, type='point', sage: f = DynamicalSystem([x^2 + c*y^2, y^2]) sage: f.sigma_invariants(1, return_polynomial=True) w^3 + (-3)*w^2*t + 2*w^2 + 3*w*t^2 + (-4)*w*t + 4*c*w - t^3 + 2*t^2 + (-4*c)*t - sage: f.sigma_invariants(2, chow=True, formal=True, return_polynomial=True) + sage: f.sigma_invariants(2, chow=True, formal=True, # needs sage.libs.pari + ....: return_polynomial=True) w^2 + (-2)*w*t + (8*c + 8)*w + t^2 + (-8*c - 8)*t + 16*c^2 + 32*c + 16 :: @@ -5641,21 +5689,21 @@ def sigma_invariants(self, n, formal=False, embedding=None, type='point', sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem([x^2 + 3*y^2, x*y]) - sage: f.sigma_invariants(1, deform = True, return_polynomial=True) + sage: f.sigma_invariants(1, deform=True, return_polynomial=True) # needs sage.rings.function_field w^3 - 3*w^2*t + 3*w^2 + 3*w*t^2 - 6*w*t + 3*w - t^3 + 3*t^2 - 3*t + 1 doubled fixed point:: sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 - 3/4*y^2, y^2]) - sage: f.sigma_invariants(2, formal=True) + sage: f.sigma_invariants(2, formal=True) # needs sage.rings.number_field [2, 1] doubled 2 cycle:: sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 - 5/4*y^2, y^2]) - sage: f.sigma_invariants(4, formal=False, type='cycle') + sage: f.sigma_invariants(4, formal=False, type='cycle') # needs sage.rings.number_field [170, 5195, 172700, 968615, 1439066, 638125, 0] TESTS:: @@ -5663,11 +5711,12 @@ def sigma_invariants(self, n, formal=False, embedding=None, type='point', sage: F. = FunctionField(GF(5)) sage: P. = ProjectiveSpace(F,1) sage: f = DynamicalSystem_projective([x^2 + (t/(t^2+1))*y^2, y^2], P) - sage: f.sigma_invariants(1) + sage: f.sigma_invariants(1) # needs sage.rings.number_field [2, 4*t/(t^2 + 1), 0] :: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: N. = NumberField(w^2 + 1) sage: P. = ProjectiveSpace(N, 2) @@ -6077,6 +6126,7 @@ def reduced_form(self, **kwds): :: + sage: # needs sage.rings.real_mpfr sage.symbolic sage: P. = ProjectiveSpace(RR, 1) sage: f = DynamicalSystem_projective([x^4, RR(sqrt(2))*y^4]) sage: m = matrix(RR, 2, 2, [1,12,0,1]) @@ -6087,6 +6137,7 @@ def reduced_form(self, **kwds): :: + sage: # needs sage.rings.real_mpfr sage.symbolic sage: P. = ProjectiveSpace(CC, 1) sage: f = DynamicalSystem_projective([x^4, CC(sqrt(-2))*y^4]) sage: m = matrix(CC, 2, 2, [1,12,0,1]) @@ -6097,6 +6148,7 @@ def reduced_form(self, **kwds): :: + sage: # needs sage.rings.number_field sage: K. = QuadraticField(2) sage: P. = ProjectiveSpace(K, 1) sage: f = DynamicalSystem_projective([x^3, w*y^3]) @@ -6106,7 +6158,7 @@ def reduced_form(self, **kwds): ( Dynamical System of Projective Space of dimension 1 over Number Field in w with defining polynomial x^2 - 2 with w = 1.414213562373095? - Defn: Defined on coordinates by sending (x : y) to (x^3 : w*y^3) , + Defn: Defined on coordinates by sending (x : y) to (x^3 : w*y^3) , [ 1 -12] [ 0 1] @@ -6114,6 +6166,7 @@ def reduced_form(self, **kwds): :: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = NumberField(x^5 + x - 3, ....: embedding=(x^5 + x - 3).roots(ring=CC)[0][0]) @@ -6303,17 +6356,18 @@ def _is_preperiodic(self, P, err=0.1, return_period=False): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^3 - 3*x*y^2, y^3], domain=P) sage: Q = P(-1, 1) - sage: f._is_preperiodic(Q) + sage: f._is_preperiodic(Q) # needs sage.rings.function_field True Check that :trac:`23814` is fixed (works even if domain is not specified):: + sage: # needs sage.rings.number_field sage: R. = PolynomialRing(QQ) sage: K. = NumberField(X^2 + X - 1) sage: P. = ProjectiveSpace(K,1) sage: f = DynamicalSystem_projective([x^2 - 2*y^2, y^2]) sage: Q = P.point([a,1]) - sage: Q.is_preperiodic(f) + sage: Q.is_preperiodic(f) # needs sage.rings.function_field True :: @@ -6322,7 +6376,7 @@ def _is_preperiodic(self, P, err=0.1, return_period=False): sage: X = P.subscheme(z) sage: f = DynamicalSystem([x^2 - y^2, y^2, z^2], domain=X) sage: p = X((-1, 1, 0)) - sage: f._is_preperiodic(p, return_period=True) + sage: f._is_preperiodic(p, return_period=True) # needs sage.rings.function_field (0, 2) :: @@ -6331,20 +6385,21 @@ def _is_preperiodic(self, P, err=0.1, return_period=False): sage: X = P.subscheme(x) sage: f = DynamicalSystem([x^2 - y^2, y^2, z^2], domain=X) sage: p = X((0, 1, 0)) - sage: f._is_preperiodic(p, return_period=True) + sage: f._is_preperiodic(p, return_period=True) # needs sage.rings.function_field Traceback (most recent call last): ... ValueError: orbit of point leaves domain :: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = NumberField(t^2 - t - 1) sage: P. = ProjectiveSpace(K, 2) sage: X = P.subscheme(z) sage: f = DynamicalSystem([x^2 - y^2, y^2, z^2], domain=X) sage: p = X((-a + 1, 1, 0)) - sage: f._is_preperiodic(p) + sage: f._is_preperiodic(p) # needs sage.rings.function_field True """ codomain = self.codomain() @@ -6428,25 +6483,26 @@ def postcritical_set(self, check=True): sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem([x^3 - 3/2* x*y^2, y^3]) - sage: f.postcritical_set() + sage: f.postcritical_set() # needs sage.rings.number_field [(1/2*a : 1), (-1/2*a : 1), (1 : 0)] :: sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem([3*x^3 - 9/2* x^2*y+y^3, y^3]) - sage: f.postcritical_set(check=False) + sage: f.postcritical_set(check=False) # needs sage.rings.number_field [(1 : 1), (-1/2 : 1), (1 : 0)] :: sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem([-4*y^2, 9*x^2 - 12*x*y]) - sage: f.postcritical_set() + sage: f.postcritical_set() # needs sage.rings.number_field [(1 : 1), (4/3 : 1), (1 : 0), (0 : 1)] :: + sage: # needs sage.rings.number_field sage: K. = QuadraticField(2) sage: P. = ProjectiveSpace(K,1) sage: f = DynamicalSystem([x^2 + (-2)*y^2, y^2]) @@ -6457,6 +6513,7 @@ def postcritical_set(self, check=True): :: + sage: # needs sage.rings.finite_rings sage: F. = FiniteField(9) sage: P. = ProjectiveSpace(F, 1) sage: f = DynamicalSystem([x^2 + (-2)*y^2, y^2]) @@ -6524,7 +6581,8 @@ def is_chebyshev(self): sage: L. = CyclotomicField(4) sage: M = Matrix([[0,i],[-i,0]]) sage: F.conjugate(M) - Dynamical System of Projective Space of dimension 1 over Cyclotomic Field of order 4 and degree 2 + Dynamical System of Projective Space of dimension 1 over + Cyclotomic Field of order 4 and degree 2 Defn: Defined on coordinates by sending (x : y) to ((-i)*x^2 : (-i)*x^2 + (2*i)*y^2) sage: F.is_chebyshev() @@ -6635,7 +6693,7 @@ def is_Lattes(self): r""" Check if ``self`` is a Lattes map - OUTPUT: True if ``self`` is Lattes, False otherwise + OUTPUT: ``True`` if ``self`` is Lattes, ``False`` otherwise EXAMPLES:: @@ -6684,7 +6742,8 @@ def is_Lattes(self): sage: L. = CyclotomicField(4) sage: M = Matrix([[i, 0], [0, -i]]) sage: f.conjugate(M) - Dynamical System of Projective Space of dimension 1 over Cyclotomic Field of order 4 and degree 2 + Dynamical System of Projective Space of dimension 1 over + Cyclotomic Field of order 4 and degree 2 Defn: Defined on coordinates by sending (x : y) to ((-1/4*i)*x^4 + (-4*i)*x*y^3 : (-i)*x^3*y + (2*i)*y^4) sage: f.is_Lattes() @@ -6822,12 +6881,11 @@ def lift_to_rational_periodic(self, points_modp, B=None): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^2 - y^2, y^2]) - sage: f.lift_to_rational_periodic([[P(0,1).change_ring(GF(7)), 4]]) + sage: f.lift_to_rational_periodic([[P(0,1).change_ring(GF(7)), 4]]) # needs sage.symbolic [[(0 : 1), 2]] - :: + There may be multiple points in the lift. :: - There may be multiple points in the lift. sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([-5*x^2 + 4*y^2, 4*x*y]) sage: f.lift_to_rational_periodic([[P(1,0).change_ring(GF(3)), 1]]) # long time @@ -6837,7 +6895,7 @@ def lift_to_rational_periodic(self, points_modp, B=None): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([16*x^2 - 29*y^2, 16*y^2]) - sage: f.lift_to_rational_periodic([[P(3,1).change_ring(GF(13)), 3]]) + sage: f.lift_to_rational_periodic([[P(3,1).change_ring(GF(13)), 3]]) # needs sage.symbolic [[(-1/4 : 1), 3]] :: @@ -6847,13 +6905,14 @@ def lift_to_rational_periodic(self, points_modp, B=None): ....: + 14*x*z + 45*y*z - 90*z^2, ....: 67*x^2 - 180*x*y - 157*x*z + 90*y*z, ....: -90*z^2]) - sage: f.lift_to_rational_periodic([[P(14,19,1).change_ring(GF(23)), 9]]) # long time + sage: f.lift_to_rational_periodic([[P(14,19,1).change_ring(GF(23)), 9]]) # long time [[(-9 : -4 : 1), 9]] """ if not points_modp: return [] if B is None: + from sage.symbolic.constants import e B = e ** self.height_difference_bound() p = points_modp[0][0].codomain().base_ring().characteristic() @@ -7085,20 +7144,22 @@ def all_periodic_points(self, **kwds): :: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = NumberField(x^2 - x + 1) sage: P. = ProjectiveSpace(K,1) sage: f = DynamicalSystem_projective([u^2 + v^2, v^2]) - sage: sorted(f.all_periodic_points()) + sage: sorted(f.all_periodic_points()) # needs sage.rings.function_field [(-w + 1 : 1), (w : 1), (1 : 0)] :: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = NumberField(x^2 - x + 1) sage: P. = ProjectiveSpace(K,1) sage: f = DynamicalSystem_projective([u^2 + v^2, u*v]) - sage: f.all_periodic_points() + sage: f.all_periodic_points() # needs sage.rings.function_field Traceback (most recent call last): ... NotImplementedError: rational periodic points for number fields @@ -7106,6 +7167,7 @@ def all_periodic_points(self, **kwds): :: + sage: # needs sage.rings.number_field sage: P. = ProjectiveSpace(QQ, 1) sage: K. = QuadraticField(5) sage: phi = QQ.embeddings(K)[0] @@ -7118,7 +7180,7 @@ def all_periodic_points(self, **kwds): sage: P. = ProjectiveSpace(QQ, 3) sage: f = DynamicalSystem_projective([x^2 - (3/4)*w^2, y^2 - 3/4*w^2, ....: z^2 - 3/4*w^2, w^2]) - sage: sorted(f.all_periodic_points(algorithm="dynatomic")) + sage: sorted(f.all_periodic_points(algorithm="dynatomic")) # needs sage.rings.function_field [(-1/2 : -1/2 : -1/2 : 1), (-1/2 : -1/2 : 3/2 : 1), (-1/2 : 3/2 : -1/2 : 1), @@ -7139,7 +7201,7 @@ def all_periodic_points(self, **kwds): sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 - 3/4*y^2, y^2]) - sage: sorted(f.all_periodic_points(period_degree_bounds=[2,2])) + sage: sorted(f.all_periodic_points(period_degree_bounds=[2,2])) # needs sage.rings.function_field [(-1/2 : 1), (1 : 0), (3/2 : 1)] TESTS:: @@ -7250,6 +7312,9 @@ def all_periodic_points(self, **kwds): return list(periodic) while p in badprimes: p = next_prime(p + 1) + + from sage.symbolic.constants import e + B = e ** DS.height_difference_bound() f = DS.change_ring(GF(p)) all_points = f.possible_periods(True) # return the list of points and their periods. @@ -7289,7 +7354,7 @@ def all_rational_preimages(self, points): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([16*x^2 - 29*y^2, 16*y^2]) - sage: sorted(f.all_rational_preimages([P(-1,4)])) + sage: sorted(f.all_rational_preimages([P(-1,4)])) # needs sage.rings.function_field [(-7/4 : 1), (-5/4 : 1), (-3/4 : 1), (-1/4 : 1), (1/4 : 1), (3/4 : 1), (5/4 : 1), (7/4 : 1)] @@ -7300,7 +7365,7 @@ def all_rational_preimages(self, points): ....: + 45*y*z - 90*z^2, ....: 67*x^2 - 180*x*y - 157*x*z + 90*y*z, ....: -90*z^2]) - sage: sorted(f.all_rational_preimages([P(-9,-4,1)])) + sage: sorted(f.all_rational_preimages([P(-9,-4,1)])) # needs sage.rings.function_field [(-9 : -4 : 1), (0 : -1 : 1), (0 : 0 : 1), (0 : 1 : 1), (0 : 4 : 1), (1 : 0 : 1), (1 : 1 : 1), (1 : 2 : 1), (1 : 3 : 1)] @@ -7308,11 +7373,12 @@ def all_rational_preimages(self, points): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^2 + y^2, 2*x*y]) - sage: sorted(f.all_rational_preimages([P(17,15)])) + sage: sorted(f.all_rational_preimages([P(17,15)])) # needs sage.rings.function_field [(1/3 : 1), (3/5 : 1), (5/3 : 1), (3 : 1)] A number field example:: + sage: # needs sage.rings.number_field sage: z = QQ['z'].0 sage: K. = NumberField(z^3 + (z^2)/4 - (41/16)*z + 23/64) sage: P. = ProjectiveSpace(K,1) @@ -7333,10 +7399,11 @@ def all_rational_preimages(self, points): :: + sage: # needs sage.rings.number_field sage: K. = QuadraticField(3) sage: P. = ProjectiveSpace(K,1) sage: f = DynamicalSystem_projective([u^2 + v^2, v^2]) - sage: f.all_rational_preimages(P(4)) + sage: f.all_rational_preimages(P(4)) # needs sage.rings.function_field [(-w : 1), (w : 1)] """ if self.domain().base_ring() not in NumberFields(): @@ -7415,14 +7482,14 @@ def all_preperiodic_points(self, **kwds): sage: PS. = ProjectiveSpace(1,QQ) sage: f = DynamicalSystem_projective([x^2 - y^2, 3*x*y]) - sage: sorted(f.all_preperiodic_points()) + sage: sorted(f.all_preperiodic_points()) # needs sage.rings.function_field [(-2 : 1), (-1 : 1), (-1/2 : 1), (0 : 1), (1/2 : 1), (1 : 0), (1 : 1), (2 : 1)] :: sage: PS. = ProjectiveSpace(1,QQ) sage: f = DynamicalSystem_projective([5*x^3 - 53*x*y^2 + 24*y^3, 24*y^3]) - sage: sorted(f.all_preperiodic_points(prime_bound=10)) + sage: sorted(f.all_preperiodic_points(prime_bound=10)) # needs sage.rings.function_field [(-1 : 1), (0 : 1), (1 : 0), (1 : 1), (3 : 1)] :: @@ -7438,10 +7505,11 @@ def all_preperiodic_points(self, **kwds): :: + sage: # needs sage.rings.number_field sage: K. = QuadraticField(33) sage: PS. = ProjectiveSpace(K,1) sage: f = DynamicalSystem_projective([x^2 - 71/48*y^2, y^2]) - sage: sorted(f.all_preperiodic_points()) # long time + sage: sorted(f.all_preperiodic_points()) # long time [(-1/12*w - 1 : 1), (-1/6*w - 1/4 : 1), (-1/12*w - 1/2 : 1), @@ -7576,14 +7644,14 @@ def rational_preperiodic_graph(self, **kwds): sage: PS. = ProjectiveSpace(1,QQ) sage: f = DynamicalSystem_projective([7*x^2 - 28*y^2, 24*x*y]) - sage: f.rational_preperiodic_graph() + sage: f.rational_preperiodic_graph() # needs sage.rings.function_field Looped digraph on 12 vertices :: sage: PS. = ProjectiveSpace(1,QQ) sage: f = DynamicalSystem_projective([-3/2*x^3 + 19/6*x*y^2, y^3]) - sage: f.rational_preperiodic_graph(prime_bound=[1,8]) + sage: f.rational_preperiodic_graph(prime_bound=[1,8]) # needs sage.rings.function_field Looped digraph on 12 vertices :: @@ -7597,10 +7665,11 @@ def rational_preperiodic_graph(self, **kwds): :: + sage: # needs sage.rings.number_field sage: K. = QuadraticField(-3) sage: P. = ProjectiveSpace(K,1) sage: f = DynamicalSystem_projective([x^2 + y^2, y^2]) - sage: f.rational_preperiodic_graph() # long time + sage: f.rational_preperiodic_graph() # long time Looped digraph on 5 vertices """ #input checking done in .rational_preperiodic_points() @@ -7629,6 +7698,7 @@ def connected_rational_component(self, P, n=0): EXAMPLES:: + sage: # needs sage.rings.number_field sage: R. = PolynomialRing(QQ) sage: K. = NumberField(x^3 + 1/4*x^2 - 41/16*x + 23/64) sage: PS. = ProjectiveSpace(1,K) @@ -7653,7 +7723,7 @@ def connected_rational_component(self, P, n=0): sage: PS. = ProjectiveSpace(2,QQ) sage: f = DynamicalSystem_projective([x^2 - 21/16*z^2, y^2 - 2*z^2, z^2]) sage: P = PS([17/16, 7/4, 1]) - sage: f.connected_rational_component(P, 3) + sage: f.connected_rational_component(P, 3) # needs sage.rings.function_field [(17/16 : 7/4 : 1), (-47/256 : 17/16 : 1), (-83807/65536 : -223/256 : 1), @@ -7759,6 +7829,7 @@ def conjugating_set(self, other, R=None, num_cpus=2): EXAMPLES:: + sage: # needs sage.rings.number_field sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 - 2*y^2, y^2]) sage: m = matrix(QQbar, 2, 2, [-1, 3, 2, 1]) @@ -7773,11 +7844,12 @@ def conjugating_set(self, other, R=None, num_cpus=2): sage: P. = ProjectiveSpace(QQ, 3) sage: f = DynamicalSystem_projective([x^2, y^2, z^2, w^2]) - sage: len(f.conjugating_set(f, num_cpus=3)) + sage: len(f.conjugating_set(f, num_cpus=3)) # needs sage.rings.function_field 24 :: + sage: # needs sage.rings.number_field sage: K. = QuadraticField(-1) sage: P. = ProjectiveSpace(K, 1) sage: f = DynamicalSystem_projective([x^2 + y^2, x*y]) @@ -7791,6 +7863,7 @@ def conjugating_set(self, other, R=None, num_cpus=2): :: + sage: # needs sage.rings.number_field sage: K. = QuadraticField(-1) sage: P. = ProjectiveSpace(K, 1) sage: D8 = DynamicalSystem_projective([y^3, x^3]) @@ -7804,7 +7877,7 @@ def conjugating_set(self, other, R=None, num_cpus=2): sage: P. = ProjectiveSpace(QQ, 1) sage: D8 = DynamicalSystem_projective([y^2, x^2]) - sage: D8.conjugating_set(D8) + sage: D8.conjugating_set(D8) # needs sage.rings.function_field Traceback (most recent call last): ... ValueError: no more rational preimages; @@ -7814,7 +7887,7 @@ def conjugating_set(self, other, R=None, num_cpus=2): sage: P. = ProjectiveSpace(GF(7), 1) sage: D6 = DynamicalSystem_projective([y^2, x^2]) - sage: sorted(D6.conjugating_set(D6)) + sage: sorted(D6.conjugating_set(D6)) # needs sage.rings.function_field [ [0 1] [0 2] [0 4] [1 0] [2 0] [4 0] [1 0], [1 0], [1 0], [0 1], [0 1], [0 1] @@ -7824,7 +7897,7 @@ def conjugating_set(self, other, R=None, num_cpus=2): sage: P. = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2 + x*z, y^2, z^2]) - sage: f.conjugating_set(f) + sage: f.conjugating_set(f) # needs sage.rings.function_field [ [1 0 0] [0 1 0] @@ -7843,6 +7916,7 @@ def conjugating_set(self, other, R=None, num_cpus=2): :: + sage: # needs sage.rings.number_field sage: P. = ProjectiveSpace(QQbar, 1) sage: f = DynamicalSystem_projective([7*x + 12*y, 8*x]) sage: g = DynamicalSystem_projective([1645*x - 318*y, 8473*x - 1638*y]) @@ -7865,6 +7939,7 @@ def conjugating_set(self, other, R=None, num_cpus=2): :: + sage: # needs sage.rings.number_field sage: L. = CyclotomicField(8) sage: P. = ProjectiveSpace(L, 2) sage: f = DynamicalSystem_projective([2*x + 12*y, 11*y + 2*z, x + z]) @@ -7878,19 +7953,20 @@ def conjugating_set(self, other, R=None, num_cpus=2): Make sure the caching problem is fixed, see #28070 :: + sage: # needs sage.rings.number_field sage: K. = QuadraticField(-1) sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 - 2*y^2, y^2]) sage: m = matrix(QQ, 2, 2, [-1, 3, 2, 1]) sage: g = f.conjugate(m) - sage: f.conjugating_set(g) + sage: f.conjugating_set(g) # needs sage.rings.function_field [ [-1 3] [ 2 1] ] sage: f = f.change_ring(K) sage: g = g.change_ring(K) - sage: f.conjugating_set(g) + sage: f.conjugating_set(g) # needs sage.rings.function_field [ [-1 3] [ 2 1] @@ -8006,6 +8082,7 @@ def is_conjugate(self, other, R=None, num_cpus=2): EXAMPLES:: + sage: # needs sage.rings.number_field sage: K. = CyclotomicField(3) sage: P. = ProjectiveSpace(K, 1) sage: D8 = DynamicalSystem_projective([y^2, x^2]) @@ -8016,11 +8093,12 @@ def is_conjugate(self, other, R=None, num_cpus=2): sage: P. = ProjectiveSpace(QQ,3) sage: f = DynamicalSystem_projective([x^2, y^2, z^2, w^2]) - sage: f.is_conjugate(f, num_cpus=2) + sage: f.is_conjugate(f, num_cpus=2) # needs sage.rings.function_field True :: + sage: # needs sage.rings.number_field sage: set_verbose(None) sage: P. = ProjectiveSpace(QQbar, 1) sage: f = DynamicalSystem_projective([x^2 + x*y, y^2]) @@ -8035,7 +8113,7 @@ def is_conjugate(self, other, R=None, num_cpus=2): sage: f = DynamicalSystem_projective([x^3 + x*y^2, y^3]) sage: m = matrix(GF(5), 2, 2, [1, 3, 2, 9]) sage: g = f.conjugate(m) - sage: f.is_conjugate(g) + sage: f.is_conjugate(g) # needs sage.rings.number_field True :: @@ -8051,11 +8129,12 @@ def is_conjugate(self, other, R=None, num_cpus=2): sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 + x*y, y^2]) sage: g = DynamicalSystem_projective([x^2 - 2*y^2, y^2]) - sage: f.is_conjugate(g) + sage: f.is_conjugate(g) # needs sage.rings.number_field False :: + sage: # needs sage.rings.number_field sage: P. = ProjectiveSpace(QQbar, 1) sage: f = DynamicalSystem_projective([7*x + 12*y, 8*x]) sage: g = DynamicalSystem_projective([1645*x - 318*y, 8473*x - 1638*y]) @@ -8067,7 +8146,7 @@ def is_conjugate(self, other, R=None, num_cpus=2): sage: P. = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([-3*y^2, 3*x^2]) sage: g = DynamicalSystem_projective([-x^2 - 2*x*y, 2*x*y + y^2]) - sage: f.is_conjugate(g), f.is_conjugate(g, R=QQbar) + sage: f.is_conjugate(g), f.is_conjugate(g, R=QQbar) # needs sage.rings.number_field (False, True) :: @@ -8101,6 +8180,7 @@ def is_conjugate(self, other, R=None, num_cpus=2): Make sure the caching problem is fixed, see #28070 :: + sage: # needs sage.rings.number_field sage: K. = QuadraticField(5) sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([x^2 - 2*y^2, y^2]) @@ -8120,7 +8200,7 @@ def is_conjugate(self, other, R=None, num_cpus=2): else: f = self.change_ring(R) g = other.change_ring(R) - if not (R in NumberFields() or R is QQbar or R in FiniteFields()): + if not (R in NumberFields() or isinstance(R, sage.rings.abc.AlgebraicField) or R in FiniteFields()): raise NotImplementedError("ring must be a number field or finite field") try: f.normalize_coordinates() @@ -8171,6 +8251,7 @@ def is_polynomial(self): EXAMPLES:: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = QuadraticField(7) sage: P. = ProjectiveSpace(K, 1) @@ -8180,6 +8261,7 @@ def is_polynomial(self): :: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = QuadraticField(7) sage: P. = ProjectiveSpace(K, 1) @@ -8191,6 +8273,7 @@ def is_polynomial(self): :: + sage: # needs sage.rings.number_field sage: K. = QuadraticField(4/27) sage: P. = ProjectiveSpace(K,1) sage: f = DynamicalSystem_projective([x**3 + w*y^3, x*y**2]) @@ -8199,6 +8282,7 @@ def is_polynomial(self): :: + sage: # needs sage.rings.finite_rings sage: K = GF(3**2, prefix='w') sage: P. = ProjectiveSpace(K,1) sage: f = DynamicalSystem_projective([x**2 + K.gen()*y**2, x*y]) @@ -8219,7 +8303,7 @@ def is_polynomial(self): sage: P. = ProjectiveSpace(QQ, 1) sage: F = DynamicalSystem([x^2 + y^2, x*y]) sage: F2 = F.conjugate(matrix(QQ,2,2, [1,2,3,5])) - sage: F2.is_polynomial() + sage: F2.is_polynomial() # needs sage.libs.pari False """ if self.codomain().dimension_relative() != 1: @@ -8320,11 +8404,12 @@ def normal_form(self, return_conjugation=False): :: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = NumberField(x^2 - 5) sage: P. = ProjectiveSpace(K,1) sage: f = DynamicalSystem_projective([x^2 + w*x*y, y^2]) - sage: g,m,psi = f.normal_form(return_conjugation = True);m + sage: g,m,psi = f.normal_form(return_conjugation=True); m [ 1 -1/2*w] [ 0 1] sage: f.change_ring(psi).conjugate(m) == g @@ -8334,13 +8419,14 @@ def normal_form(self, return_conjugation=False): sage: P. = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([13*x^2 + 4*x*y + 3*y^2, 5*y^2]) - sage: f.normal_form() + sage: f.normal_form() # needs sage.libs.pari Dynamical System of Projective Space of dimension 1 over Rational Field Defn: Defined on coordinates by sending (x : y) to (5*x^2 + 9*y^2 : 5*y^2) :: + sage: # needs sage.rings.finite_rings sage: K = GF(3^3, prefix='w') sage: P. = ProjectiveSpace(K,1) sage: f = DynamicalSystem_projective([x^3 + 2*x^2*y + 2*x*y^2 + K.gen()*y^3, y^3]) @@ -8354,7 +8440,7 @@ def normal_form(self, return_conjugation=False): sage: P. = ProjectiveSpace(GF(3),1) sage: f = DynamicalSystem_projective([2*x**3 + x**2*y, y**3]) - sage: g,m,psi = f.normal_form(return_conjugation=True); psi + sage: g,m,psi = f.normal_form(return_conjugation=True); psi # needs sage.rings.finite_rings Ring morphism: From: Finite Field of size 3 To: Finite Field in z2 of size 3^2 @@ -8524,6 +8610,7 @@ def potential_good_reduction(self, prime, return_conjugation=False): EXAMPLES:: + sage: # needs sage.rings.number_field sage: P. = ProjectiveSpace(QQ, 1) sage: system = DynamicalSystem_projective([x^2 - y^2, 2*x*y]) sage: prime = system.field_of_definition_periodic(1).prime_above(2) @@ -8536,38 +8623,39 @@ def potential_good_reduction(self, prime, return_conjugation=False): Note that this map has good reduction at 2:: - sage: new_system.resultant() + sage: new_system.resultant() # needs sage.rings.number_field 1 Using ``return_conjugation``, we can get the conjugation that achieves good reduction:: - sage: conj = system.potential_good_reduction(prime, True)[2]; conj + sage: conj = system.potential_good_reduction(prime, True)[2]; conj # needs sage.rings.number_field [-1/2*a 1/2] [ 0 1] We can check that this conjugation achieves good reduction:: - sage: system.conjugate(conj).resultant() + sage: system.conjugate(conj).resultant() # needs sage.rings.number_field 1 :: sage: P. = ProjectiveSpace(QQ, 1) sage: system = DynamicalSystem_projective([3^4*x^3 + 3*x*y^2 + y^3, 3^6*y^3]) - sage: prime = system.field_of_definition_periodic(1).prime_above(3) - sage: system.potential_good_reduction(prime) + sage: prime = system.field_of_definition_periodic(1).prime_above(3) # needs sage.rings.number_field + sage: system.potential_good_reduction(prime) # needs sage.rings.number_field (False, None) :: sage: P. = ProjectiveSpace(QQ, 1) sage: system = DynamicalSystem_projective([x^5 - x*y^4, 5*y^5]) - sage: prime = system.field_of_definition_periodic(1).prime_above(5) - sage: system.potential_good_reduction(prime) + sage: prime = system.field_of_definition_periodic(1).prime_above(5) # needs sage.rings.number_field + sage: system.potential_good_reduction(prime) # needs sage.rings.number_field (False, None) TESTS:: + sage: # needs sage.rings.number_field sage: P. = ProjectiveSpace(QQ, 1) sage: R. = QQ[] sage: A. = NumberField(z^2 + 1) @@ -8590,6 +8678,7 @@ def potential_good_reduction(self, prime, return_conjugation=False): :: + sage: # needs sage.rings.number_field sage: P. = ProjectiveSpace(QQ, 1) sage: system = DynamicalSystem_projective([x**5 - 11*y**5, x**4*y]) sage: B, new_sys, conj = system.potential_good_reduction(11, True) @@ -8602,8 +8691,8 @@ def potential_good_reduction(self, prime, return_conjugation=False): sage: P. = ProjectiveSpace(QQ, 1) sage: system = DynamicalSystem_projective([3*x^2 + x*y + y^2, 9*y^2]) - sage: prime = system.field_of_definition_periodic(1).prime_above(3) - sage: system.potential_good_reduction(prime) + sage: prime = system.field_of_definition_periodic(1).prime_above(3) # needs sage.rings.number_field + sage: system.potential_good_reduction(prime) # needs sage.rings.number_field (False, None) """ @@ -8697,6 +8786,7 @@ def reduce_base_field(self): EXAMPLES:: + sage: # needs sage.rings.finite_rings sage: K. = GF(2^3) sage: P. = ProjectiveSpace(K, 2) sage: f = DynamicalSystem_projective([x^2 + y^2, y^2, z^2+z*y]) @@ -8707,17 +8797,19 @@ def reduce_base_field(self): :: + sage: # needs sage.rings.number_field sage.symbolic sage: P. = ProjectiveSpace(QQbar, 2) sage: f = DynamicalSystem_projective([x^2 + QQbar(sqrt(3))*y^2, ....: y^2, QQbar(sqrt(2))*z^2]) sage: f.reduce_base_field() - Dynamical System of Projective Space of dimension 2 over Number Field in a with - defining polynomial y^4 - 4*y^2 + 1 with a = -0.5176380902050415? + Dynamical System of Projective Space of dimension 2 over Number Field in a + with defining polynomial y^4 - 4*y^2 + 1 with a = -0.5176380902050415? Defn: Defined on coordinates by sending (x : y : z) to (x^2 + (-a^2 + 2)*y^2 : y^2 : (a^3 - 3*a)*z^2) :: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: K. = NumberField(x^3 - 2, embedding=(x^3 - 2).roots(ring=CC)[0][0]) sage: R. = QQ[] @@ -8731,6 +8823,7 @@ def reduce_base_field(self): :: + sage: # needs sage.rings.number_field sage: K. = CyclotomicField(5) sage: A. = ProjectiveSpace(K, 1) sage: f = DynamicalSystem_projective([3*x^2 + y^2, x*y]) @@ -8769,7 +8862,7 @@ def is_newton(self, return_conjugation=False): sage: A. = AffineSpace(QQ, 1) sage: f = DynamicalSystem_affine([z - (z^2 + 1)/(2*z)]) sage: F = f.homogenize(1) - sage: F.is_newton(return_conjugation=True) + sage: F.is_newton(return_conjugation=True) # needs sage.rings.number_field ( [1 0] True, [0 1] @@ -8780,21 +8873,22 @@ def is_newton(self, return_conjugation=False): sage: A. = AffineSpace(QQ, 1) sage: f = DynamicalSystem_affine([z^2 + 1]) sage: F = f.homogenize(1) - sage: F.is_newton() + sage: F.is_newton() # needs sage.rings.number_field False - sage: F.is_newton(return_conjugation=True) + sage: F.is_newton(return_conjugation=True) # needs sage.rings.number_field (False, None) :: sage: PP. = ProjectiveSpace(QQ, 1) sage: F = DynamicalSystem_projective([-4*x^3 - 3*x*y^2, -2*y^3]) - sage: F.is_newton(return_conjugation=True)[1] + sage: F.is_newton(return_conjugation=True)[1] # needs sage.rings.number_field [ 0 1] [-4*a 2*a] :: + sage: # needs sage.rings.number_field sage: K. = CyclotomicField(2*4) sage: A. = AffineSpace(K, 1) sage: f = DynamicalSystem_affine(z-(z^3+zeta*z)/(3*z^2+zeta)) @@ -8815,6 +8909,7 @@ def is_newton(self, return_conjugation=False): return False, None else: return False + from sage.rings.qqbar import QQbar Fbar = self.change_ring(QQbar) Pbar = Fbar.domain() fixed = Fbar.periodic_points(1) @@ -8935,7 +9030,7 @@ def orbit_structure(self, P): sage: P. = ProjectiveSpace(GF(7),2) sage: X = P.subscheme(x^2 - y^2) sage: f = DynamicalSystem_projective([x^2, y^2, z^2], domain=X) - sage: f.orbit_structure(X(1,1,2)) + sage: f.orbit_structure(X(1,1,2)) # needs sage.rings.function_field (0, 2) :: @@ -8947,6 +9042,7 @@ def orbit_structure(self, P): :: + sage: # needs sage.rings.finite_rings sage: R. = GF(13^3) sage: P. = ProjectiveSpace(R,1) sage: f = DynamicalSystem_projective([x^2 - y^2, y^2], domain=P) @@ -8980,14 +9076,15 @@ def cyclegraph(self): sage: P. = ProjectiveSpace(GF(13),1) sage: f = DynamicalSystem_projective([x^2 - y^2, y^2]) - sage: f.cyclegraph() + sage: f.cyclegraph() # needs sage.graphs Looped digraph on 14 vertices :: + sage: # needs sage.rings.finite_rings sage: P. = ProjectiveSpace(GF(3^2,'t'),2) sage: f = DynamicalSystem_projective([x^2 + y^2, y^2, z^2 + y*z]) - sage: f.cyclegraph() + sage: f.cyclegraph() # needs sage.graphs Looped digraph on 91 vertices :: @@ -8995,14 +9092,14 @@ def cyclegraph(self): sage: P. = ProjectiveSpace(GF(7),2) sage: X = P.subscheme(x^2 - y^2) sage: f = DynamicalSystem_projective([x^2, y^2, z^2], domain=X) - sage: f.cyclegraph() + sage: f.cyclegraph() # needs sage.graphs Looped digraph on 15 vertices :: sage: P. = ProjectiveSpace(GF(3),2) sage: f = DynamicalSystem_projective([x*z - y^2, x^2 - y^2, y^2 - z^2]) - sage: f.cyclegraph() + sage: f.cyclegraph() # needs sage.graphs Looped digraph on 13 vertices :: @@ -9010,7 +9107,7 @@ def cyclegraph(self): sage: P. = ProjectiveSpace(GF(3),2) sage: X = P.subscheme([x - y]) sage: f = DynamicalSystem_projective([x^2 - y^2, x^2 - y^2, y^2 - z^2], domain=X) - sage: f.cyclegraph() + sage: f.cyclegraph() # needs sage.graphs Looped digraph on 4 vertices """ V = [] @@ -9064,15 +9161,15 @@ def possible_periods(self, return_points=False): EXAMPLES:: sage: P. = ProjectiveSpace(GF(23),1) - sage: f = DynamicalSystem_projective([x^2-2*y^2, y^2]) - sage: f.possible_periods() + sage: f = DynamicalSystem_projective([x^2 - 2*y^2, y^2]) + sage: f.possible_periods() # needs sage.libs.pari [1, 5, 11, 22, 110] :: sage: P. = ProjectiveSpace(GF(13),1) sage: f = DynamicalSystem_projective([x^2 - y^2, y^2]) - sage: sorted(f.possible_periods(True)) + sage: sorted(f.possible_periods(True)) # needs sage.libs.pari [[(0 : 1), 2], [(1 : 0), 1], [(3 : 1), 3], [(3 : 1), 36]] :: @@ -9080,7 +9177,7 @@ def possible_periods(self, return_points=False): sage: PS. = ProjectiveSpace(2,GF(7)) sage: f = DynamicalSystem_projective([-360*x^3 + 760*x*z^2, ....: y^3 - 604*y*z^2 + 240*z^3, 240*z^3]) - sage: f.possible_periods() + sage: f.possible_periods() # needs sage.libs.pari [1, 2, 4, 6, 12, 14, 28, 42, 84] .. TODO:: @@ -9134,6 +9231,7 @@ def automorphism_group(self, **kwds): EXAMPLES:: + sage: # needs sage.rings.finite_rings sage: R. = ProjectiveSpace(GF(7^3,'t'),1) sage: f = DynamicalSystem_projective([x^2 - y^2, x*y]) sage: f.automorphism_group() @@ -9144,11 +9242,12 @@ def automorphism_group(self, **kwds): :: + sage: # needs sage.rings.finite_rings sage: R. = ProjectiveSpace(GF(3^2,'t'),1) sage: f = DynamicalSystem_projective([x^3, y^3]) - sage: lst, label = f.automorphism_group(return_functions=True, # long time + sage: lst, label = f.automorphism_group(return_functions=True, # long time ....: iso_type=True) - sage: sorted(lst, key=str), label # long time + sage: sorted(lst, key=str), label # long time ([(2*x + 1)/(x + 1), (2*x + 1)/x, (2*x + 2)/(x + 2), @@ -9177,6 +9276,7 @@ def automorphism_group(self, **kwds): :: + sage: # needs sage.rings.finite_rings sage: R. = ProjectiveSpace(GF(2^5,'t'),1) sage: f = DynamicalSystem_projective([x^5, y^5]) sage: f.automorphism_group(return_functions=True, iso_type=True) @@ -9184,6 +9284,7 @@ def automorphism_group(self, **kwds): :: + sage: # needs sage.rings.finite_rings sage: R. = ProjectiveSpace(GF(3^4,'t'),1) sage: f = DynamicalSystem_projective([x^2 + 25*x*y + y^2, x*y + 3*y^2]) sage: f.automorphism_group(absolute=True) @@ -9197,7 +9298,7 @@ def automorphism_group(self, **kwds): sage: R. = ProjectiveSpace(GF(5), 2) sage: f = DynamicalSystem_projective([x^3 + x*z^2, y^3 + y*z^2, z^3]) - sage: all([f.conjugate(m) == f for m in f.automorphism_group()]) + sage: all([f.conjugate(m) == f for m in f.automorphism_group()]) # needs sage.rings.function_field True """ absolute = kwds.get('absolute', False) @@ -9233,6 +9334,7 @@ def all_periodic_points(self, **kwds): EXAMPLES:: + sage: # needs sage.rings.finite_rings sage: P. = ProjectiveSpace(GF(5^2),1) sage: f = DynamicalSystem_projective([x^2 + y^2, x*y]) sage: f.all_periodic_points() @@ -9244,18 +9346,18 @@ def all_periodic_points(self, **kwds): sage: f = DynamicalSystem_projective([x^2 + y^2 + z^2, x*y + x*z, z^2]) sage: f.all_periodic_points() [(1 : 0 : 0), - (0 : 0 : 1), - (1 : 0 : 1), - (2 : 1 : 1), - (1 : 4 : 1), - (3 : 0 : 1), - (0 : 3 : 1)] + (0 : 0 : 1), + (1 : 0 : 1), + (2 : 1 : 1), + (1 : 4 : 1), + (3 : 0 : 1), + (0 : 3 : 1)] :: - sage: P.=ProjectiveSpace(GF(3), 1) + sage: P. = ProjectiveSpace(GF(3), 1) sage: f = DynamicalSystem_projective([x^2 - y^2, y^2]) - sage: f.all_periodic_points(R=GF(3^2, 't')) + sage: f.all_periodic_points(R=GF(3^2, 't')) # needs sage.rings.finite_rings [(1 : 0), (0 : 1), (2 : 1), (t : 1), (2*t + 1 : 1)] """ R = kwds.pop("R", None) diff --git a/src/sage/dynamics/arithmetic_dynamics/projective_ds_helper.pyx b/src/sage/dynamics/arithmetic_dynamics/projective_ds_helper.pyx index f8fb37d5cf4..9b0009629de 100644 --- a/src/sage/dynamics/arithmetic_dynamics/projective_ds_helper.pyx +++ b/src/sage/dynamics/arithmetic_dynamics/projective_ds_helper.pyx @@ -24,7 +24,7 @@ from sage.rings.finite_rings.finite_field_constructor import GF from sage.combinat.subset import subsets -cpdef _fast_possible_periods(self, return_points=False): +cpdef _fast_possible_periods(self, return_points=False) noexcept: r""" Return the list of possible minimal periods of a periodic point over `\QQ` and (optionally) a point in each cycle. @@ -177,7 +177,7 @@ def _enum_points(int prime, int dimension): yield _get_point_from_hash(value, prime, dimension) current_range = current_range * prime -cpdef int _hash(list Point, int prime): +cpdef int _hash(list Point, int prime) noexcept: """ Hash point given as list to unique number. @@ -198,7 +198,7 @@ cpdef int _hash(list Point, int prime): return hash_q -cpdef list _get_point_from_hash(int value, int prime, int dimension): +cpdef list _get_point_from_hash(int value, int prime, int dimension) noexcept: """ Hash unique number to point as a list. @@ -217,7 +217,7 @@ cpdef list _get_point_from_hash(int value, int prime, int dimension): return P -cdef inline int _mod_inv(int num, int prime): +cdef inline int _mod_inv(int num, int prime) noexcept: """ Find the inverse of the number modulo the given prime. """ @@ -240,7 +240,7 @@ cdef inline int _mod_inv(int num, int prime): else: return y -cpdef _normalize_coordinates(list point, int prime, int len_points): +cpdef _normalize_coordinates(list point, int prime, int len_points) noexcept: """ Normalize the coordinates of the point for the given prime. @@ -269,7 +269,7 @@ cpdef _normalize_coordinates(list point, int prime, int len_points): for coefficient in range(len_points): point[coefficient] = (point[coefficient] * mod_inverse) % prime -cpdef _all_periodic_points(self): +cpdef _all_periodic_points(self) noexcept: """ Find all periodic points over a finite field. diff --git a/src/sage/dynamics/arithmetic_dynamics/wehlerK3.py b/src/sage/dynamics/arithmetic_dynamics/wehlerK3.py index f1ea230df16..a0eedfed4a6 100644 --- a/src/sage/dynamics/arithmetic_dynamics/wehlerK3.py +++ b/src/sage/dynamics/arithmetic_dynamics/wehlerK3.py @@ -25,25 +25,30 @@ # https://www.gnu.org/licenses/ # **************************************************************************** -from sage.calculus.functions import jacobian -from sage.categories.fields import Fields +from copy import copy + +import sage.rings.abc + from sage.categories.commutative_rings import CommutativeRings +from sage.categories.fields import Fields from sage.categories.number_fields import NumberFields -from sage.misc.functional import sqrt from sage.misc.cachefunc import cached_method +from sage.misc.functional import sqrt +from sage.misc.lazy_import import lazy_import from sage.misc.mrange import xmrange from sage.rings.finite_rings.finite_field_constructor import GF from sage.rings.fraction_field import FractionField from sage.rings.integer_ring import ZZ -from sage.rings.number_field.order import is_NumberFieldOrder -from sage.rings.padics.factory import Qp from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing from sage.rings.rational_field import QQ from sage.rings.real_mpfr import RealField from sage.schemes.generic.algebraic_scheme import AlgebraicScheme_subscheme -from sage.schemes.product_projective.subscheme import AlgebraicScheme_subscheme_product_projective from sage.schemes.product_projective.space import ProductProjectiveSpaces -from copy import copy +from sage.schemes.product_projective.subscheme import AlgebraicScheme_subscheme_product_projective + +lazy_import("sage.calculus.functions", "jacobian") +lazy_import('sage.rings.padics.factory', 'Qp') + _NumberFields = NumberFields() _Fields = Fields() @@ -61,7 +66,7 @@ def WehlerK3Surface(polys): EXAMPLES:: - sage: PP. = ProductProjectiveSpaces([2, 2],QQ) + sage: PP. = ProductProjectiveSpaces([2, 2], QQ) sage: L = x0*y0 + x1*y1 - x2*y2 sage: Q = x0*x1*y1^2 + x2^2*y0*y2 sage: WehlerK3Surface([L, Q]) @@ -159,7 +164,7 @@ def change_ring(self, R): r""" Changes the base ring on which the Wehler K3 Surface is defined. - INPUT: ``R`` - ring + INPUT: ``R`` -- ring OUTPUT: K3 Surface defined over input ring @@ -184,7 +189,7 @@ def _check_satisfies_equations(self, P): r""" Function checks to see if point ``P`` lies on the K3 Surface. - INPUT: ``P`` - point in `\mathbb{P}^2 \times \mathbb{P}^2` + INPUT: ``P`` -- point in `\mathbb{P}^2 \times \mathbb{P}^2` OUTPUT: AttributeError True if the point is not on the surface @@ -330,17 +335,17 @@ def Gpoly(self, component, k): Return the G polynomials `G^*_k`. They are defined as: - `G^*_k = \left(L^*_j\right)^2Q^*_{ii}-L^*_iL^*_jQ^*_{ij}+\left(L^*_i\right)^2Q^*_{jj}`\ - where {i, j, k} is some permutation of (0, 1, 2) and * is either - x (Component = 1) or y (Component = 0). + `G^*_k = \left(L^*_j\right)^2Q^*_{ii}-L^*_iL^*_jQ^*_{ij}+\left(L^*_i\right)^2Q^*_{jj}` + where `(i, j, k)` is some permutation of `(0, 1, 2)` and `*` is either + `x` (``component=1``) or `y` (``component=0``). INPUT: - - ``component`` - Integer: 0 or 1 + - ``component`` -- Integer: 0 or 1 - - ``k`` - Integer: 0, 1 or 2 + - ``k`` -- Integer: 0, 1 or 2 - OUTPUT: polynomial in terms of either y (Component = 0) or x (Component = 1) + OUTPUT: polynomial in terms of either `y` (``component=0``) or `x` (``component=1``) EXAMPLES:: @@ -376,17 +381,17 @@ def Hpoly(self, component, i, j): This polynomial is defined by: `H^*_{ij} = 2L^*_iL^*_jQ^*_{kk}-L^*_iL^*_kQ^*_{jk} - L^*_jL^*_kQ^*_{ik}+\left(L^*_k\right)^2Q^*_{ij}` - where {i, j, k} is some permutation of (0, 1, 2) and * is either y (Component = 0) or x (Component = 1). + where {i, j, k} is some permutation of (0, 1, 2) and * is either y (``component=0``) or x (``component=1``). INPUT: - - ``component`` - Integer: 0 or 1 + - ``component`` -- Integer: 0 or 1 - - ``i`` - Integer: 0, 1 or 2 + - ``i`` -- Integer: 0, 1 or 2 - - ``j`` - Integer: 0, 1 or 2 + - ``j`` -- Integer: 0, 1 or 2 - OUTPUT: polynomial in terms of either y (Component = 0) or x (Component = 1) + OUTPUT: polynomial in terms of either y (``component=0``) or x (``component=1``) EXAMPLES:: @@ -464,7 +469,7 @@ def Qxa(self, a): Notation and definition from: [CS1996]_ - INPUT: ``a`` - Point in `\mathbb{P}^2` + INPUT: ``a`` -- Point in `\mathbb{P}^2` OUTPUT: A polynomial representing the fiber @@ -518,9 +523,9 @@ def Sxa(self, a): sage: X = WehlerK3Surface([Z, Y]) sage: T = PP(1, 1, 0, 1, 0, 0) sage: X.Sxa(T[0]) - Closed subscheme of Projective Space of dimension 2 over Rational Field defined by: - y0 + y1, - 5*y0^2 + 7*y0*y1 + y1^2 + 11*y1*y2 + y2^2 + Closed subscheme of Projective Space of dimension 2 over Rational Field defined by: + y0 + y1, + 5*y0^2 + 7*y0*y1 + y1^2 + 11*y1*y2 + y2^2 """ if a not in self.ambient_space()[0]: raise TypeError("point must be in projective space of dimension 2") @@ -537,7 +542,7 @@ def Lyb(self, b): Notation and definition from: [CS1996]_ - INPUT: ``b`` - Point in projective space + INPUT: ``b`` -- Point in projective space OUTPUT: A polynomial representing the fiber @@ -554,7 +559,7 @@ def Lyb(self, b): sage: X = WehlerK3Surface([Z, Y]) sage: T = PP(1, 1, 0, 1, 0, 0) sage: X.Lyb(T[1]) - x0 + x0 """ if b not in self.ambient_space()[1]: raise TypeError("point must be in projective space of dimension 2") @@ -627,9 +632,9 @@ def Syb(self, b): sage: X = WehlerK3Surface([Z, Y]) sage: T = PP(1, 1, 0, 1, 0, 0) sage: X.Syb(T[1]) - Closed subscheme of Projective Space of dimension 2 over Rational Field defined by: - x0, - x0^2 + 3*x0*x1 + x1^2 + Closed subscheme of Projective Space of dimension 2 over Rational Field defined by: + x0, + x0^2 + 3*x0*x1 + x1^2 """ if b not in self.ambient_space()[1]: @@ -649,23 +654,25 @@ def Ramification_poly(self, i): The roots of this polynomial will either be degenerate fibers or fixed points of the involutions `\sigma_x` or `\sigma_y` for more information, see [CS1996]_. - INPUT: ``i`` - Integer, either 0 (polynomial in y) or 1 (polynomial in x) + INPUT: ``i`` -- Integer, either 0 (polynomial in y) or 1 (polynomial in x) OUTPUT: Polynomial in the coordinate ring of the ambient space EXAMPLES:: sage: PP. = ProductProjectiveSpaces([2, 2], QQ) - sage: Z = x0^2*y0^2 + 3*x0*x1*y0^2 + x1^2*y0^2 + 4*x0^2*y0*y1 + 3*x0*x1*y0*y1\ - - 2*x2^2*y0*y1 - x0^2*y1^2 + 2*x1^2*y1^2 - x0*x2*y1^2 - 4*x1*x2*y1^2 + 5*x0*x2*y0*y2\ - - 4*x1*x2*y0*y2 + 7*x0^2*y1*y2 + 4*x1^2*y1*y2 + x0*x1*y2^2 + 3*x2^2*y2^2 + sage: Z = (x0^2*y0^2 + 3*x0*x1*y0^2 + x1^2*y0^2 + 4*x0^2*y0*y1 + 3*x0*x1*y0*y1 + ....: - 2*x2^2*y0*y1 - x0^2*y1^2 + 2*x1^2*y1^2 - x0*x2*y1^2 - 4*x1*x2*y1^2 + ....: + 5*x0*x2*y0*y2 - 4*x1*x2*y0*y2 + 7*x0^2*y1*y2 + 4*x1^2*y1*y2 + ....: + x0*x1*y2^2 + 3*x2^2*y2^2) sage: Y = x0*y0 + x1*y1 + x2*y2 sage: X = WehlerK3Surface([Z, Y]) sage: X.Ramification_poly(0) 8*y0^5*y1 - 24*y0^4*y1^2 + 48*y0^2*y1^4 - 16*y0*y1^5 + y1^6 + 84*y0^3*y1^2*y2 + 46*y0^2*y1^3*y2 - 20*y0*y1^4*y2 + 16*y1^5*y2 + 53*y0^4*y2^2 + 56*y0^3*y1*y2^2 - 32*y0^2*y1^2*y2^2 - 80*y0*y1^3*y2^2 - 92*y1^4*y2^2 - 12*y0^2*y1*y2^3 - - 168*y0*y1^2*y2^3 - 122*y1^3*y2^3 + 14*y0^2*y2^4 + 8*y0*y1*y2^4 - 112*y1^2*y2^4 + y2^6 + - 168*y0*y1^2*y2^3 - 122*y1^3*y2^3 + 14*y0^2*y2^4 + 8*y0*y1*y2^4 - 112*y1^2*y2^4 + + y2^6 """ return ((self._Lcoeff(i, 0))**2)*(self._Qcoeff(i, 1, 2))**2 + \ ((self._Lcoeff(i, 1))**2)*(self._Qcoeff(i, 0, 2)**2) + \ @@ -755,7 +762,7 @@ def degenerate_fibers(self): The criteria for degeneracy by the common vanishing of the polynomials ``self.Gpoly(1, 0)``, ``self.Gpoly(1, 1)``, ``self.Gpoly(1, 2)``, - ``self.Hpoly(1, 0, 1)``,``self.Hpoly(1, 0, 2)``, + ``self.Hpoly(1, 0, 1)``, ``self.Hpoly(1, 0, 2)``, ``self.Hpoly(1, 1, 2)`` (for the first component), is from Proposition 1.4 in the following article: [CS1996]_. @@ -781,9 +788,10 @@ def degenerate_fibers(self): :: sage: PP. = ProductProjectiveSpaces([2, 2], QQ) - sage: Z = x0^2*y0^2 + 3*x0*x1*y0^2 + x1^2*y0^2 + 4*x0^2*y0*y1 + 3*x0*x1*y0*y1\ - - 2*x2^2*y0*y1 - x0^2*y1^2 + 2*x1^2*y1^2 - x0*x2*y1^2 - 4*x1*x2*y1^2 + 5*x0*x2*y0*y2\ - - 4*x1*x2*y0*y2 + 7*x0^2*y1*y2 + 4*x1^2*y1*y2 + x0*x1*y2^2 + 3*x2^2*y2^2 + sage: Z = (x0^2*y0^2 + 3*x0*x1*y0^2 + x1^2*y0^2 + 4*x0^2*y0*y1 + 3*x0*x1*y0*y1 + ....: - 2*x2^2*y0*y1 - x0^2*y1^2 + 2*x1^2*y1^2 - x0*x2*y1^2 - 4*x1*x2*y1^2 + ....: + 5*x0*x2*y0*y2 - 4*x1*x2*y0*y2 + 7*x0^2*y1*y2 + 4*x1^2*y1*y2 + ....: + x0*x1*y2^2 + 3*x2^2*y2^2) sage: Y = x0*y0 + x1*y1 + x2*y2 sage: X = WehlerK3Surface([Z, Y]) sage: X.degenerate_fibers() @@ -867,28 +875,28 @@ def degenerate_fibers(self): return [xFibers,yFibers] @cached_method - def degenerate_primes(self,check=True): + def degenerate_primes(self, check=True): r""" - Determine which primes `p` self has degenerate fibers over `GF(p)`. + Determine which primes `p` self has degenerate fibers over `\GF{p}`. - If check is False, then may return primes that do not have degenerate fibers. + If ``check`` is ``False``, then may return primes that do not have degenerate fibers. Raises an error if the surface is degenerate. Works only for ``ZZ`` or ``QQ``. - INPUT: ``check`` -- (default: True) boolean, whether the primes are verified + INPUT: ``check`` -- (default: ``True``) boolean, whether the primes are verified ALGORITHM: `p` is a prime of bad reduction if and only if the defining - polynomials of self plus the G and H polynomials have a common + polynomials of ``self`` plus the G and H polynomials have a common zero. Or stated another way, `p` is a prime of bad reduction if and only if the radical of the ideal defined by the defining - polynomials of self plus the G and H polynomials is not + polynomials of ``self`` plus the G and H polynomials is not `(x_0,x_1,\ldots,x_N)`. This happens if and only if some power of each `x_i` is not in the ideal defined by the - defining polynomials of self (with G and H). This last condition + defining polynomials of ``self`` (with G and H). This last condition is what is checked. The lcm of the coefficients of the monomials `x_i` in - a groebner basis is computed. This may return extra primes. + a Groebner basis is computed. This may return extra primes. OUTPUT: List of primes. @@ -905,11 +913,11 @@ def degenerate_primes(self,check=True): [2, 3, 5, 11, 23, 47, 48747691, 111301831] """ PP = self.ambient_space() - if PP.base_ring() in _NumberFields or is_NumberFieldOrder(PP.base_ring()): - if PP.base_ring() != ZZ and PP.base_ring() != QQ: - raise NotImplementedError("must be ZZ or QQ") - else: - raise TypeError("must be over a number field") + if PP.base_ring() != ZZ and PP.base_ring() != QQ: + if PP.base_ring() in _NumberFields or isinstance(PP.base_ring(), sage.rings.abc.Order): + raise NotImplementedError("only implemented for ZZ and QQ") + else: + raise TypeError("must be over a number field or number field order") if self.is_degenerate(): raise TypeError("surface is degenerate at all primes") RR = PP.coordinate_ring() @@ -1038,11 +1046,11 @@ def sigmaX(self, P, **kwds): INPUT: - - ``P`` - a point in `\mathbb{P}^2 \times \mathbb{P}^2` + - ``P`` -- a point in `\mathbb{P}^2 \times \mathbb{P}^2` kwds: - - ``check`` - (default: ``True``) boolean checks to see if point is on the surface + - ``check`` -- (default: ``True``) boolean checks to see if point is on the surface - ``normalize`` -- (default: ``True``) boolean normalizes the point @@ -1083,12 +1091,14 @@ def sigmaX(self, P, **kwds): sage: PP.=ProductProjectiveSpaces([2, 2], GF(3)) sage: l = x0*y0 + x1*y1 + x2*y2 - sage: q=-3*x0^2*y0^2 + 4*x0*x1*y0^2 - 3*x0*x2*y0^2 - 5*x0^2*y0*y1 - \ - 190*x0*x1*y0*y1- 5*x1^2*y0*y1 + 5*x0*x2*y0*y1 + 14*x1*x2*y0*y1 + \ - 5*x2^2*y0*y1 - x0^2*y1^2 - 6*x0*x1*y1^2- 2*x1^2*y1^2 + 2*x0*x2*y1^2 - \ - 4*x2^2*y1^2 + 4*x0^2*y0*y2 - x1^2*y0*y2 + 3*x0*x2*y0*y2+ 6*x1*x2*y0*y2 - \ - 6*x0^2*y1*y2 - 4*x0*x1*y1*y2 - x1^2*y1*y2 + 51*x0*x2*y1*y2 - 7*x1*x2*y1*y2 - \ - 9*x2^2*y1*y2 - x0^2*y2^2 - 4*x0*x1*y2^2 + 4*x1^2*y2^2 - x0*x2*y2^2 + 13*x1*x2*y2^2 - x2^2*y2^2 + sage: q = (-3*x0^2*y0^2 + 4*x0*x1*y0^2 - 3*x0*x2*y0^2 - 5*x0^2*y0*y1 + ....: - 190*x0*x1*y0*y1 - 5*x1^2*y0*y1 + 5*x0*x2*y0*y1 + 14*x1*x2*y0*y1 + ....: + 5*x2^2*y0*y1 - x0^2*y1^2 - 6*x0*x1*y1^2 - 2*x1^2*y1^2 + ....: + 2*x0*x2*y1^2 - 4*x2^2*y1^2 + 4*x0^2*y0*y2 - x1^2*y0*y2 + ....: + 3*x0*x2*y0*y2 + 6*x1*x2*y0*y2 - 6*x0^2*y1*y2 - 4*x0*x1*y1*y2 + ....: - x1^2*y1*y2 + 51*x0*x2*y1*y2 - 7*x1*x2*y1*y2 - 9*x2^2*y1*y2 + ....: - x0^2*y2^2 - 4*x0*x1*y2^2 + 4*x1^2*y2^2 - x0*x2*y2^2 + ....: + 13*x1*x2*y2^2 - x2^2*y2^2) sage: X = WehlerK3Surface([l, q]) sage: P = X([1, 0, 0, 0, 1, 1]) sage: X.sigmaX(X.sigmaX(P)) @@ -1268,12 +1278,12 @@ def sigmaX(self, P, **kwds): def sigmaY(self,P, **kwds): r""" - Function returns the involution on the Wehler K3 surfaces induced by the double covers. + Return the involution on the Wehler K3 surfaces induced by the double covers. - In particular,it fixes the projection to the second coordinate and swaps + In particular, it fixes the projection to the second coordinate and swaps the two points in the fiber, i.e. `(x,y) \to (x',y)`. Note that in the degenerate case, while we can split the fiber into two points, - it is not always possibleto distinguish them, using this algorithm. + it is not always possible to distinguish them, using this algorithm. ALGORITHM: @@ -1283,11 +1293,11 @@ def sigmaY(self,P, **kwds): INPUT: - - ``P`` - a point in `\mathbb{P}^2 \times \mathbb{P}^2` + - ``P`` -- a point in `\mathbb{P}^2 \times \mathbb{P}^2` kwds: - - ``check`` - (default: ``True``) boolean checks to see if point is on the surface + - ``check`` -- (default: ``True``) boolean checks to see if point is on the surface - ``normalize`` -- (default: ``True``) boolean normalizes the point @@ -1326,11 +1336,13 @@ def sigmaY(self,P, **kwds): sage: PP.=ProductProjectiveSpaces([2, 2], GF(3)) sage: l = x0*y0 + x1*y1 + x2*y2 - sage: q=-3*x0^2*y0^2 + 4*x0*x1*y0^2 - 3*x0*x2*y0^2 - 5*x0^2*y0*y1 - 190*x0*x1*y0*y1 \ - - 5*x1^2*y0*y1 + 5*x0*x2*y0*y1 + 14*x1*x2*y0*y1 + 5*x2^2*y0*y1 - x0^2*y1^2 - 6*x0*x1*y1^2 \ - - 2*x1^2*y1^2 + 2*x0*x2*y1^2 - 4*x2^2*y1^2 + 4*x0^2*y0*y2 - x1^2*y0*y2 + 3*x0*x2*y0*y2 \ - + 6*x1*x2*y0*y2 - 6*x0^2*y1*y2 - 4*x0*x1*y1*y2 - x1^2*y1*y2 + 51*x0*x2*y1*y2 - 7*x1*x2*y1*y2 \ - - 9*x2^2*y1*y2 - x0^2*y2^2 - 4*x0*x1*y2^2 + 4*x1^2*y2^2 - x0*x2*y2^2 + 13*x1*x2*y2^2 - x2^2*y2^2 + sage: q = (-3*x0^2*y0^2 + 4*x0*x1*y0^2 - 3*x0*x2*y0^2 - 5*x0^2*y0*y1 + ....: - 190*x0*x1*y0*y1 - 5*x1^2*y0*y1 + 5*x0*x2*y0*y1 + 14*x1*x2*y0*y1 + ....: + 5*x2^2*y0*y1 - x0^2*y1^2 - 6*x0*x1*y1^2 - 2*x1^2*y1^2 + 2*x0*x2*y1^2 + ....: - 4*x2^2*y1^2 + 4*x0^2*y0*y2 - x1^2*y0*y2 + 3*x0*x2*y0*y2 + ....: + 6*x1*x2*y0*y2 - 6*x0^2*y1*y2 - 4*x0*x1*y1*y2 - x1^2*y1*y2 + ....: + 51*x0*x2*y1*y2 - 7*x1*x2*y1*y2 - 9*x2^2*y1*y2 - x0^2*y2^2 + ....: - 4*x0*x1*y2^2 + 4*x1^2*y2^2 - x0*x2*y2^2 + 13*x1*x2*y2^2 - x2^2*y2^2) sage: X = WehlerK3Surface([l ,q]) sage: P = X([0, 1, 1, 1, 0, 0]) sage: X.sigmaY(X.sigmaY(P)) @@ -1521,7 +1533,7 @@ def phi(self, a, **kwds): kwds: - - ``check`` - (default: ``True``) boolean checks to see if point is on the surface + - ``check`` -- (default: ``True``) boolean checks to see if point is on the surface - ``normalize`` -- (default: ``True``) boolean normalizes the point @@ -1561,7 +1573,7 @@ def psi(self,a, **kwds): kwds: - - ``check`` - (default: ``True``) boolean checks to see if point is on the surface + - ``check`` -- (default: ``True``) boolean checks to see if point is on the surface - ``normalize`` -- (default: ``True``) boolean normalizes the point @@ -1604,8 +1616,8 @@ def lambda_plus(self, P, v, N, m, n, prec=100): - ``v`` -- non-negative integer. a place, use v = 0 for the Archimedean place - - ``m,n`` -- positive integers, We compute the local height for the divisor `E_{mn}^{+}`. - These must be indices of non-zero coordinates of the point ``P``. + - ``m``, ``n`` -- positive integers; we compute the local height for the divisor `E_{mn}^{+}`. + These must be indices of non-zero coordinates of the point ``P``. - ``prec`` -- (default: 100) float point or p-adic precision @@ -2004,9 +2016,12 @@ def fiber(self, p, component): sage: PP. = ProductProjectiveSpaces([2, 2], GF(7)) sage: L = x0*y0 + x1*y1 - 1*x2*y2 - sage: Q=(2*x0^2 + x2*x0 + (2*x1^2 + x2^2))*y0^2 + ((x0^2 + x1*x0 +(x1^2 + 2*x2*x1 + x2^2))*y1 + \ - (2*x1^2 + x2*x1 + x2^2)*y2)*y0 + ((2*x0^2+ (x1 + 2*x2)*x0 + (2*x1^2 + x2*x1))*y1^2 + ((2*x1 + 2*x2)*x0 + \ - (x1^2 +x2*x1 + 2*x2^2))*y2*y1 + (2*x0^2 + x1*x0 + (2*x1^2 + x2^2))*y2^2) + sage: Q = ((2*x0^2 + x2*x0 + (2*x1^2 + x2^2))*y0^2 + ....: + ((x0^2 + x1*x0 +(x1^2 + 2*x2*x1 + x2^2))*y1 + ....: + (2*x1^2 + x2*x1 + x2^2)*y2)*y0 + ....: + ((2*x0^2 + (x1 + 2*x2)*x0 + (2*x1^2 + x2*x1))*y1^2 + ....: + ((2*x1 + 2*x2)*x0 + (x1^2 + x2*x1 + 2*x2^2))*y2*y1 + ....: + (2*x0^2 + x1*x0 + (2*x1^2 + x2^2))*y2^2)) sage: W = WehlerK3Surface([L, Q]) sage: W.fiber([4, 0, 1], 0) [(0 : 1 : 0 , 4 : 0 : 1), (4 : 0 : 2 , 4 : 0 : 1)] @@ -2136,7 +2151,7 @@ def fiber(self, p, component): def nth_iterate_phi(self, P, n, **kwds): r""" - Computes the nth iterate for the phi function. + Computes the ``n``-th iterate for the phi function. INPUT: @@ -2158,7 +2173,7 @@ def nth_iterate_phi(self, P, n, **kwds): sage: PP. = ProductProjectiveSpaces([2, 2], QQ) sage: L = x0*y0 + x1*y1 + x2*y2 sage: Q = x1^2*y0^2 + 2*x2^2*y0*y1 + x0^2*y1^2 - x0*x1*y2^2 - sage: W = WehlerK3Surface([L ,Q]) + sage: W = WehlerK3Surface([L, Q]) sage: T = W([-1, -1, 1, 1, 0, 1]) sage: W.nth_iterate_phi(T, 7) (-1 : 0 : 1 , 1 : -2 : 1) @@ -2201,7 +2216,7 @@ def nth_iterate_phi(self, P, n, **kwds): def nth_iterate_psi(self, P, n, **kwds): r""" - Computes the nth iterate for the psi function. + Computes the ``n``-th iterate for the psi function. INPUT: @@ -2262,9 +2277,9 @@ def orbit_phi(self, P, N, **kwds): INPUT: - - ``P`` - Point on the K3 surface + - ``P`` -- Point on the K3 surface - - ``N`` - a non-negative integer or list or tuple of two non-negative integers + - ``N`` -- a non-negative integer or list or tuple of two non-negative integers kwds: @@ -2321,13 +2336,13 @@ def orbit_psi(self, P, N, **kwds): INPUT: - - ``P`` - a point on the K3 surface + - ``P`` -- a point on the K3 surface - - ``N`` - a non-negative integer or list or tuple of two non-negative integers + - ``N`` -- a non-negative integer or list or tuple of two non-negative integers kwds: - - ``check`` - (default: ``True``) boolean, checks to see if point is on the surface + - ``check`` -- (default: ``True``) boolean, checks to see if point is on the surface - ``normalize`` -- (default: ``False``) boolean, normalizes the point @@ -2343,9 +2358,9 @@ def orbit_psi(self, P, N, **kwds): sage: Y = x0*y0 + x1*y1 + x2*y2 sage: X = WehlerK3Surface([Z, Y]) sage: T = X(0, 0, 1, 1, 0, 0) - sage: X.orbit_psi(T, 2, normalize = True) + sage: X.orbit_psi(T, 2, normalize=True) [(0 : 0 : 1 , 1 : 0 : 0), (0 : 0 : 1 , 0 : 1 : 0), (-1 : 0 : 1 , 1 : 1/9 : 1)] - sage: X.orbit_psi(T,[2,3], normalize = True) + sage: X.orbit_psi(T,[2,3], normalize=True) [(-1 : 0 : 1 , 1 : 1/9 : 1), (-12816/6659 : 55413/6659 : 1 , -117756062505511/54767410965117 : -23134047983794359/37466994368025041 : 1)] """ @@ -2371,11 +2386,11 @@ def orbit_psi(self, P, N, **kwds): def is_isomorphic(self, right): r""" - Checks to see if two K3 surfaces have the same defining ideal. + Check to see if two K3 surfaces have the same defining ideal. INPUT: - - ``right`` - the K3 surface to compare to the original + - ``right`` -- the K3 surface to compare to the original OUTPUT: Boolean @@ -2395,12 +2410,12 @@ def is_isomorphic(self, right): :: sage: R. = PolynomialRing(QQ, 6) - sage: L = x*u-y*v + sage: L = x*u - y*v sage: Q = x*y*v^2 + z^2*u*w sage: W1 = WehlerK3Surface([L, Q]) sage: PP. = ProductProjectiveSpaces([2, 2], QQ) sage: L = x0*y0 + x1*y1 + x2*y2 - sage: Q = x1^2*y0^2 + 2*x2^2*y0*y1 + x0^2*y1^2 -x0*x1*y2^2 + sage: Q = x1^2*y0^2 + 2*x2^2*y0*y1 + x0^2*y1^2 - x0*x1*y2^2 sage: W2 = WehlerK3Surface([L, Q]) sage: W1.is_isomorphic(W2) False @@ -2409,12 +2424,12 @@ def is_isomorphic(self, right): def is_symmetric_orbit(self,orbit): r""" - Checks to see if the orbit is symmetric (i.e. if one of the points on the + Check to see if the orbit is symmetric (i.e. if one of the points on the orbit is fixed by '\sigma_x' or '\sigma_y'). INPUT: - - ``orbit``- a periodic cycle of either psi or phi + - ``orbit`` -- a periodic cycle of either psi or phi OUTPUT: Boolean @@ -2463,20 +2478,20 @@ class WehlerK3Surface_field( WehlerK3Surface_ring): class WehlerK3Surface_finite_field( WehlerK3Surface_field): def cardinality( self): r""" - Counts the total number of points on the K3 surface. + Count the total number of points on the K3 surface. ALGORITHM: Enumerate points over `\mathbb{P}^2`, and then count the points on the fiber of each of those points. - OUTPUT: Integer - total number of points on the surface + OUTPUT: Integer -- total number of points on the surface EXAMPLES:: sage: PP. = ProductProjectiveSpaces([2, 2], GF(7)) sage: Z = x0^2*y0^2 + 3*x0*x1*y0^2 + x1^2*y0^2 + 4*x0^2*y0*y1 + \ - 3*x0*x1*y0*y1 -2*x2^2*y0*y1 - x0^2*y1^2 + 2*x1^2*y1^2 - x0*x2*y1^2 \ + 3*x0*x1*y0*y1 - 2*x2^2*y0*y1 - x0^2*y1^2 + 2*x1^2*y1^2 - x0*x2*y1^2 \ - 4*x1*x2*y1^2 + 5*x0*x2*y0*y2 -4*x1*x2*y0*y2 + 7*x0^2*y1*y2 + 4*x1^2*y1*y2 \ + x0*x1*y2^2 + 3*x2^2*y2^2 sage: Y = x0*y0 + x1*y1 + x2*y2 diff --git a/src/sage/dynamics/cellular_automata/elementary.py b/src/sage/dynamics/cellular_automata/elementary.py index cd0915cdde7..26e68c37b01 100644 --- a/src/sage/dynamics/cellular_automata/elementary.py +++ b/src/sage/dynamics/cellular_automata/elementary.py @@ -225,7 +225,7 @@ class ElementaryCellularAutomata(SageObject): sage: ECA = cellular_automata.Elementary(60, width=200) sage: ECA.evolve(200) - sage: ECA.plot() + sage: ECA.plot() # needs sage.plot Graphics object consisting of 1 graphics primitive .. PLOT:: @@ -239,7 +239,7 @@ class ElementaryCellularAutomata(SageObject): sage: ECA = cellular_automata.Elementary(90, initial_state=[1]+[0]*254+[1], boundary=None) sage: ECA.evolve(256) - sage: ECA.plot() + sage: ECA.plot() # needs sage.plot Graphics object consisting of 1 graphics primitive .. PLOT:: @@ -598,7 +598,7 @@ def plot(self, number=None): sage: ECA = cellular_automata.Elementary(110, width=256) sage: ECA.evolve(256) - sage: ECA.plot() + sage: ECA.plot() # needs sage.plot Graphics object consisting of 1 graphics primitive """ if number is None: diff --git a/src/sage/dynamics/cellular_automata/glca.py b/src/sage/dynamics/cellular_automata/glca.py index 46b24619ac2..6b062f2a441 100644 --- a/src/sage/dynamics/cellular_automata/glca.py +++ b/src/sage/dynamics/cellular_automata/glca.py @@ -67,7 +67,7 @@ class GraftalLaceCellularAutomata(SageObject): sage: G = cellular_automata.GraftalLace([2,0,3,3,6,0,2,7]) sage: G.evolve(20) - sage: G.plot() + sage: G.plot() # needs sage.plot Graphics object consisting of 842 graphics primitives .. PLOT:: @@ -398,7 +398,7 @@ def plot(self, number=None): sage: G = cellular_automata.GraftalLace([5,1,2,5,4,5,5,0]) sage: G.evolve(20) - sage: G.plot() + sage: G.plot() # needs sage.plot Graphics object consisting of 865 graphics primitives """ if number is None: diff --git a/src/sage/dynamics/complex_dynamics/mandel_julia.py b/src/sage/dynamics/complex_dynamics/mandel_julia.py index f387c84ccec..f3d6fbfa5a0 100644 --- a/src/sage/dynamics/complex_dynamics/mandel_julia.py +++ b/src/sage/dynamics/complex_dynamics/mandel_julia.py @@ -31,7 +31,6 @@ # http://www.gnu.org/licenses/ #***************************************************************************** -from sage.dynamics.arithmetic_dynamics.generic_ds import DynamicalSystem from sage.dynamics.complex_dynamics.mandel_julia_helper import (fast_mandelbrot_plot, fast_external_ray, convert_to_pixels, @@ -56,6 +55,8 @@ from sage.rings.fraction_field import is_FractionField from sage.categories.function_fields import FunctionFields +lazy_import('sage.dynamics.arithmetic_dynamics.generic_ds', 'DynamicalSystem') + EPS = 0.00001 def mandelbrot_plot(f=None, **kwds): diff --git a/src/sage/dynamics/complex_dynamics/mandel_julia_helper.pyx b/src/sage/dynamics/complex_dynamics/mandel_julia_helper.pyx index 9ee71e4f4bf..32ffb1effe5 100644 --- a/src/sage/dynamics/complex_dynamics/mandel_julia_helper.pyx +++ b/src/sage/dynamics/complex_dynamics/mandel_julia_helper.pyx @@ -1,4 +1,5 @@ # cython: binding=True +# sage.doctest: needs sage.plot r""" Mandelbrot and Julia sets (Cython helper) @@ -60,7 +61,7 @@ def _color_to_RGB(color): cpdef fast_mandelbrot_plot(double x_center, double y_center, double image_width, long max_iteration, long pixel_count, - long level_sep, long color_num, base_color): + long level_sep, long color_num, base_color) noexcept: r""" Plots the Mandelbrot set in the complex plane for the map `Q_c(z) = z^2 + c`. @@ -178,7 +179,7 @@ cpdef fast_mandelbrot_plot(double x_center, double y_center, cpdef fast_external_ray(double theta, long D=30, long S=10, long R=100, - long pixel_count=500, double image_width=4, long prec=300): + long pixel_count=500, double image_width=4, long prec=300) noexcept: r""" Return a list of points that approximate the external ray for a given angle. @@ -289,7 +290,7 @@ cpdef fast_external_ray(double theta, long D=30, long S=10, long R=100, return c_list cpdef convert_to_pixels(point_list, double x_0, double y_0, double width, - long number_of_pixels): + long number_of_pixels) noexcept: r""" Converts cartesian coordinates to pixels within a specified window. @@ -333,7 +334,7 @@ cpdef convert_to_pixels(point_list, double x_0, double y_0, double width, pixel_list.append((x_pixel, y_pixel)) return pixel_list -cpdef get_line(start, end): +cpdef get_line(start, end) noexcept: r""" Produces a list of pixel coordinates approximating a line from a starting point to an ending point using the Bresenham's Line Algorithm. @@ -420,7 +421,7 @@ cpdef get_line(start, end): cpdef fast_julia_plot(double c_real, double c_imag, double x_center=0, double y_center=0, double image_width=4, long max_iteration=500, long pixel_count=500, long level_sep=2, - long color_num=40, base_color=[50, 50, 50]): + long color_num=40, base_color=[50, 50, 50]) noexcept: r""" Plots the Julia set for a given `c` value in the complex plane for the map `Q_c(z) = z^2 + c`. @@ -539,7 +540,7 @@ cpdef fast_julia_plot(double c_real, double c_imag, cpdef julia_helper(double c_real, double c_imag, double x_center=0, double y_center=0, double image_width=4, long max_iteration=500, long pixel_count=500, long level_sep=2, long color_num=40, - base_color=[50, 50, 50], point_color=[255, 0, 0]): + base_color=[50, 50, 50], point_color=[255, 0, 0]) noexcept: r""" Helper function that returns the image of a Julia set for a given `c` value side by side with the Mandelbrot set with a point denoting @@ -630,7 +631,7 @@ cpdef julia_helper(double c_real, double c_imag, double x_center=0, cpdef polynomial_mandelbrot(f, parameter=None, double x_center=0, double y_center=0, image_width=4, int max_iteration=50, int pixel_count=500, - int level_sep=1, int color_num=30, base_color=Color('red')): + int level_sep=1, int color_num=30, base_color=Color('red')) noexcept: r""" Plots the Mandelbrot set in the complex plane for a family of polynomial maps. @@ -933,7 +934,7 @@ cpdef polynomial_mandelbrot(f, parameter=None, double x_center=0, cpdef general_julia(f, double x_center=0, double y_center=0, image_width=4, int max_iteration=50, int pixel_count=500, int level_sep=1, int color_num=30, - base_color=[50,50,50]): + base_color=[50,50,50]) noexcept: r""" Plots Julia sets for general polynomials. diff --git a/src/sage/env.py b/src/sage/env.py index f4899639a6d..b1fe9a89cd1 100644 --- a/src/sage/env.py +++ b/src/sage/env.py @@ -1,10 +1,6 @@ r""" Sage Runtime Environment -AUTHORS: - -- \R. Andrew Ohana (2012): Initial version. - Verify that importing ``sage.all`` works in Sage's Python without any ``SAGE_`` environment variables, and has the same ``SAGE_ROOT`` and ``SAGE_LOCAL`` (see also :trac:`29446`):: @@ -16,6 +12,11 @@ sage: out = check_output([sys.executable, "-c", cmd], env=env).decode().strip() # long time sage: out == repr((SAGE_ROOT, SAGE_LOCAL)) # long time True + +AUTHORS: + +- \R. Andrew Ohana (2012): initial version + """ # **************************************************************************** @@ -200,7 +201,6 @@ def var(key: str, *fallbacks: Optional[str], force: bool = False) -> Optional[st POLYTOPE_DATA_DIR = var("POLYTOPE_DATA_DIR", join(SAGE_SHARE, "reflexive_polytopes")) GAP_LIB_DIR = var("GAP_LIB_DIR", join(SAGE_LOCAL, "lib", "gap")) GAP_SHARE_DIR = var("GAP_SHARE_DIR", join(SAGE_SHARE, "gap")) -THEBE_DIR = var("THEBE_DIR", join(SAGE_SHARE, "thebe")) COMBINATORIAL_DESIGN_DATA_DIR = var("COMBINATORIAL_DESIGN_DATA_DIR", join(SAGE_SHARE, "combinatorial_designs")) CREMONA_MINI_DATA_DIR = var("CREMONA_MINI_DATA_DIR", join(SAGE_SHARE, "cremona")) CREMONA_LARGE_DATA_DIR = var("CREMONA_LARGE_DATA_DIR", join(SAGE_SHARE, "cremona")) diff --git a/src/sage/ext/fast_callable.pyx b/src/sage/ext/fast_callable.pyx index baf2e7c6d6e..bad30e0e605 100644 --- a/src/sage/ext/fast_callable.pyx +++ b/src/sage/ext/fast_callable.pyx @@ -1577,7 +1577,7 @@ cdef class ExpressionChoice(Expression): repr(self._cond), repr(self._iffalse)) -cpdef _expression_binop_helper(s, o, op): +cpdef _expression_binop_helper(s, o, op) noexcept: r""" Make an Expression for (s op o). Either s or o (or both) must already be an expression. @@ -1713,7 +1713,7 @@ class IntegerPowerFunction(): return x**self.exponent cdef dict builtin_functions = None -cpdef dict get_builtin_functions(): +cpdef dict get_builtin_functions() noexcept: r""" To handle ExpressionCall, we need to map from Sage and Python functions to opcode names. @@ -1767,7 +1767,7 @@ cpdef dict get_builtin_functions(): cdef class InstructionStream # forward declaration -cpdef generate_code(Expression expr, InstructionStream stream): +cpdef generate_code(Expression expr, InstructionStream stream) noexcept: r""" Generate code from an Expression tree; write the result into an InstructionStream. @@ -2142,7 +2142,7 @@ cdef class InstructionStream: """ self.instr('load_arg', n) - cpdef bint has_instr(self, opname): + cpdef bint has_instr(self, opname) noexcept: r""" Check whether this InstructionStream knows how to generate code for a given instruction. @@ -2191,7 +2191,7 @@ cdef class InstructionStream: """ self.instr0(opname, args) - cdef instr0(self, opname, tuple args): + cdef instr0(self, opname, tuple args) noexcept: """ Cdef version of instr. (Can't cpdef because of star args.) """ diff --git a/src/sage/ext/memory.pyx b/src/sage/ext/memory.pyx index 1e93581a370..e7961348cb8 100644 --- a/src/sage/ext/memory.pyx +++ b/src/sage/ext/memory.pyx @@ -42,7 +42,7 @@ cdef extern from "Python.h": int unlikely(int) nogil # Defined by Cython -cdef void alloc_error(size_t size) nogil: +cdef void alloc_error(size_t size) noexcept nogil: """ Jump back to ``sig_on()``, raising a :class:`MemoryError`. """ @@ -51,7 +51,7 @@ cdef void alloc_error(size_t size) nogil: sig_error() -cdef void* sage_sig_malloc(size_t size) nogil: +cdef void* sage_sig_malloc(size_t size) noexcept nogil: """ ``malloc()`` function for the MPIR/GMP library. @@ -63,7 +63,7 @@ cdef void* sage_sig_malloc(size_t size) nogil: return p -cdef void* sage_sig_realloc(void *ptr, size_t old_size, size_t new_size) nogil: +cdef void* sage_sig_realloc(void *ptr, size_t old_size, size_t new_size) noexcept nogil: """ ``realloc()`` function for the MPIR/GMP library. @@ -75,7 +75,7 @@ cdef void* sage_sig_realloc(void *ptr, size_t old_size, size_t new_size) nogil: return p -cdef void sage_sig_free(void *ptr, size_t size) nogil: +cdef void sage_sig_free(void *ptr, size_t size) noexcept nogil: """ ``free()`` function for the MPIR/GMP library. """ diff --git a/src/sage/ext/memory_allocator.pxd b/src/sage/ext/memory_allocator.pxd index f96253345f6..5fc54a1cd27 100644 --- a/src/sage/ext/memory_allocator.pxd +++ b/src/sage/ext/memory_allocator.pxd @@ -6,7 +6,7 @@ cdef extern from *: int unlikely(int) nogil # defined by Cython -cdef inline void* align(void* ptr, size_t alignment): +cdef inline void* align(void* ptr, size_t alignment) noexcept: """ Round up ``ptr`` to the nearest multiple of ``alignment``, which must be a power of 2 diff --git a/src/sage/ext/stdsage.pxd b/src/sage/ext/stdsage.pxd index e2bf7434f35..7249fbf84d8 100644 --- a/src/sage/ext/stdsage.pxd +++ b/src/sage/ext/stdsage.pxd @@ -13,7 +13,7 @@ Standard C helper code for Cython modules from cpython.object cimport Py_TYPE, PyTypeObject, PyObject -cdef inline PY_NEW(type t): +cdef inline PY_NEW(type t) noexcept: """ Return ``t.__new__(t)``. This works even for types like :class:`Integer` where we change ``tp_new`` at runtime (Cython @@ -22,7 +22,7 @@ cdef inline PY_NEW(type t): return (t).tp_new(t, NULL, NULL) -cdef inline void PY_SET_TP_NEW(type dst, type src): +cdef inline void PY_SET_TP_NEW(type dst, type src) noexcept: """ Manually set ``dst.__new__`` to ``src.__new__``. This is used to speed up Cython's boilerplate object construction code by skipping @@ -31,7 +31,7 @@ cdef inline void PY_SET_TP_NEW(type dst, type src): (dst).tp_new = (src).tp_new -cdef inline bint HAS_DICTIONARY(obj): +cdef inline bint HAS_DICTIONARY(obj) noexcept: """ Test whether the given object has a Python dictionary. """ diff --git a/src/sage/features/join_feature.py b/src/sage/features/join_feature.py index 802cb433ba3..6360eec1576 100644 --- a/src/sage/features/join_feature.py +++ b/src/sage/features/join_feature.py @@ -148,7 +148,7 @@ def hide(self): """ for f in self._features: f.hide() - super(JoinFeature, self).hide() + super().hide() def unhide(self): r""" @@ -172,4 +172,4 @@ def unhide(self): """ for f in self._features: f.unhide() - super(JoinFeature, self).unhide() + super().unhide() diff --git a/src/sage/functions/orthogonal_polys.py b/src/sage/functions/orthogonal_polys.py index 7a9322973ad..f4e0dc1bdbf 100644 --- a/src/sage/functions/orthogonal_polys.py +++ b/src/sage/functions/orthogonal_polys.py @@ -454,7 +454,7 @@ def __init__(self, name, nargs=2, latex_name=None, conversions=None): self._maxima_name = conversions['maxima'] except KeyError: pass - super(OrthogonalFunction, self).__init__(name=name, nargs=nargs, + super().__init__(name=name, nargs=nargs, latex_name=latex_name, conversions=conversions) @@ -529,7 +529,7 @@ def __call__(self, *args, **kwds): kwds['hold'] = True return _maxima(self._eval_(*args, **kwds))._sage_() - return super(OrthogonalFunction, self).__call__(*args, **kwds) + return super().__call__(*args, **kwds) class ChebyshevFunction(OrthogonalFunction): @@ -575,7 +575,7 @@ def __call__(self, n, *args, **kwds): except Exception: pass - return super(ChebyshevFunction, self).__call__(n, *args, **kwds) + return super().__call__(n, *args, **kwds) def _eval_(self, n, x): """ diff --git a/src/sage/functions/other.py b/src/sage/functions/other.py index 249eb2ea56f..eed84964be3 100644 --- a/src/sage/functions/other.py +++ b/src/sage/functions/other.py @@ -2209,7 +2209,7 @@ def _evalf_(self, poly, index, parent=None, algorithm=None): sage: complex_root_of(x^8 - 1, 7).n(20) # needs sage.symbolic 0.70711 + 0.70711*I """ - from sympy.core.evalf import prec_to_dps + from mpmath.libmp import prec_to_dps from sympy.polys import CRootOf, Poly try: prec = parent.precision() diff --git a/src/sage/functions/piecewise.py b/src/sage/functions/piecewise.py index a41c07228fc..1638637287f 100644 --- a/src/sage/functions/piecewise.py +++ b/src/sage/functions/piecewise.py @@ -473,8 +473,7 @@ def items(self, parameters, variable): support is {0}, function is sin(x) support is (0, 2), function is cos(x) """ - for pair in parameters: - yield pair + yield from parameters def __call__(self, parameters, variable, value=None, **kwds): """ diff --git a/src/sage/functions/prime_pi.pyx b/src/sage/functions/prime_pi.pyx index 141e538cf74..2f64469c731 100644 --- a/src/sage/functions/prime_pi.pyx +++ b/src/sage/functions/prime_pi.pyx @@ -210,7 +210,7 @@ cdef class PrimePi(BuiltinFunction): prime_pi = PrimePi() -cpdef Integer legendre_phi(x, a): +cpdef Integer legendre_phi(x, a) noexcept: r""" Legendre's formula, also known as the partial sieve function, is a useful combinatorial function for computing the prime counting function (the diff --git a/src/sage/geometry/hyperplane_arrangement/arrangement.py b/src/sage/geometry/hyperplane_arrangement/arrangement.py index 7174a80ece5..90e620b71bc 100644 --- a/src/sage/geometry/hyperplane_arrangement/arrangement.py +++ b/src/sage/geometry/hyperplane_arrangement/arrangement.py @@ -287,7 +287,7 @@ False sage: a.sign_vector((1,1,1)) (-1, 1, -1, 1, -1, 1) - sage: a.varchenko_matrix() + sage: a.varchenko_matrix()[:6, :6] [ 1 h2 h2*h4 h2*h3 h2*h3*h4 h2*h3*h4*h5] [ h2 1 h4 h3 h3*h4 h3*h4*h5] [ h2*h4 h4 1 h3*h4 h3 h3*h5] @@ -3157,11 +3157,24 @@ def varchenko_matrix(self, names='h'): sage: a = hyperplane_arrangements.coordinate(3) sage: v = a.varchenko_matrix(); v - [ 1 h2 h1] - [ h2 1 h1*h2] - [ h1 h1*h2 1] + [ 1 h2 h1 h1*h2 h0*h1*h2 h0*h1 h0*h2 h0] + [ h2 1 h1*h2 h1 h0*h1 h0*h1*h2 h0 h0*h2] + [ h1 h1*h2 1 h2 h0*h2 h0 h0*h1*h2 h0*h1] + [ h1*h2 h1 h2 1 h0 h0*h2 h0*h1 h0*h1*h2] + [h0*h1*h2 h0*h1 h0*h2 h0 1 h2 h1 h1*h2] + [ h0*h1 h0*h1*h2 h0 h0*h2 h2 1 h1*h2 h1] + [ h0*h2 h0 h0*h1*h2 h0*h1 h1 h1*h2 1 h2] + [ h0 h0*h2 h0*h1 h0*h1*h2 h1*h2 h1 h2 1] sage: factor(det(v)) - (h2 - 1) * (h2 + 1) * (h1 - 1) * (h1 + 1) + (h2 - 1)^4 * (h2 + 1)^4 * (h1 - 1)^4 * (h1 + 1)^4 * (h0 - 1)^4 * (h0 + 1)^4 + + TESTS: + + Verify that :issue:`36490` is fixed:: + + sage: hyperplane_arrangements.coordinate(1).varchenko_matrix() + [1 h] + [h 1] """ from sage.matrix.constructor import identity_matrix from sage.misc.misc_c import prod @@ -3169,9 +3182,10 @@ def varchenko_matrix(self, names='h'): R = PolynomialRing(QQ, names, k) h = R.gens() region = self.regions() - v = identity_matrix(R, k, k) - for i in range(k): - for j in range(i+1, k): + n = len(region) + v = identity_matrix(R, n, n) + for i in range(n): + for j in range(i + 1, n): t = prod(h[p] for p in range(k) if self.is_separating_hyperplane(region[i], region[j], self[p])) v[i, j] = v[j, i] = t diff --git a/src/sage/geometry/integral_points.pxi b/src/sage/geometry/integral_points.pxi index 037efb41da8..3ea46051b47 100644 --- a/src/sage/geometry/integral_points.pxi +++ b/src/sage/geometry/integral_points.pxi @@ -70,7 +70,7 @@ from sage.modules.free_module import FreeModule # existing lattice point and then copy it! -cpdef tuple parallelotope_points(spanning_points, lattice): +cpdef tuple parallelotope_points(spanning_points, lattice) noexcept: r""" Return integral points in the parallelotope starting at the origin and spanned by the ``spanning_points``. @@ -143,7 +143,7 @@ cpdef tuple parallelotope_points(spanning_points, lattice): return points -cpdef tuple ray_matrix_normal_form(R): +cpdef tuple ray_matrix_normal_form(R) noexcept: r""" Compute the Smith normal form of the ray matrix for :func:`parallelotope_points`. @@ -179,7 +179,7 @@ cpdef tuple ray_matrix_normal_form(R): # The optimized version avoids constructing new matrices, vectors, and lattice points cpdef tuple loop_over_parallelotope_points(e, d, MatrixClass VDinv, MatrixClass R, lattice, - A=None, b=None): + A=None, b=None) noexcept: r""" The inner loop of :func:`parallelotope_points`. @@ -244,7 +244,7 @@ cpdef tuple loop_over_parallelotope_points(e, d, MatrixClass VDinv, ############################################################################## -cpdef tuple simplex_points(vertices): +cpdef tuple simplex_points(vertices) noexcept: r""" Return the integral points in a lattice simplex. @@ -329,7 +329,7 @@ cpdef tuple simplex_points(vertices): return points -cdef translate_points(v_list, VectorClass delta): +cdef translate_points(v_list, VectorClass delta) noexcept: r""" Add ``delta`` to each vector in ``v_list``. """ @@ -348,7 +348,7 @@ cdef translate_points(v_list, VectorClass delta): cpdef rectangular_box_points(list box_min, list box_max, polyhedron=None, count_only=False, - return_saturated=False): + return_saturated=False) noexcept: r""" Return the integral points in the lattice bounding box that are also contained in the given polyhedron. @@ -583,7 +583,7 @@ cpdef rectangular_box_points(list box_min, list box_max, return tuple(points) -cdef list perm_action(list p, list lst): +cdef list perm_action(list p, list lst) noexcept: """ Return the action of a permutation ``p`` of `(0, ..., n-1)` on a list of length `n`. @@ -592,7 +592,7 @@ cdef list perm_action(list p, list lst): cdef loop_over_rectangular_box_points(list box_min, list box_max, InequalityCollection inequalities, - int d, bint count_only): + int d, bint count_only) noexcept: """ The inner loop of :func:`rectangular_box_points`. @@ -666,7 +666,7 @@ cdef loop_over_rectangular_box_points(list box_min, list box_max, cdef loop_over_rectangular_box_points_saturated(list box_min, list box_max, InequalityCollection inequalities, - int d): + int d) noexcept: """ The analog of :func:`rectangular_box_points` except that it keeps track of which inequalities are saturated. @@ -790,7 +790,7 @@ cdef class Inequality_generic: s += ') x + ' + str(self.b) + ' >= 0' return s - cdef prepare_next_to_inner_loop(self, p): + cdef prepare_next_to_inner_loop(self, p) noexcept: """ In :class:`Inequality_int` this method is used to peel of the next-to-inner loop. @@ -799,7 +799,7 @@ cdef class Inequality_generic: """ pass - cdef prepare_inner_loop(self, p): + cdef prepare_inner_loop(self, p) noexcept: """ Peel off the inner loop. @@ -956,7 +956,7 @@ cdef class Inequality_int: s += ') x + ' + str(self.b) + ' >= 0' return s - cdef prepare_next_to_inner_loop(Inequality_int self, p): + cdef prepare_next_to_inner_loop(Inequality_int self, p) noexcept: """ Peel off the next-to-inner loop. @@ -967,7 +967,7 @@ cdef class Inequality_int: for j in range(2, self.dim): self.cache_next += self.A[j] * p[j] - cdef prepare_inner_loop(Inequality_int self, p): + cdef prepare_inner_loop(Inequality_int self, p) noexcept: """ Peel off the inner loop. @@ -979,10 +979,10 @@ cdef class Inequality_int: else: self.cache = self.cache_next - cdef bint is_not_satisfied(Inequality_int self, int inner_loop_variable): + cdef bint is_not_satisfied(Inequality_int self, int inner_loop_variable) noexcept: return inner_loop_variable * self.coeff + self.cache < 0 - cdef bint is_equality(Inequality_int self, int inner_loop_variable): + cdef bint is_equality(Inequality_int self, int inner_loop_variable) noexcept: return inner_loop_variable * self.coeff + self.cache == 0 @@ -1054,7 +1054,7 @@ cdef class InequalityCollection: s += str(ineq) + '\n' return s.strip() - cpdef tuple _make_A_b(self, Hrep_obj, list permutation): + cpdef tuple _make_A_b(self, Hrep_obj, list permutation) noexcept: r""" Return the coefficients and constant of the H-representation object. @@ -1124,7 +1124,7 @@ cdef class InequalityCollection: raise TypeError('Cannot extract Hrepresentation data from polyhedron.') cdef _cinit_from_PPL(self, list max_abs_coordinates, list permutation, - polyhedron): + polyhedron) noexcept: """ Initialize the inequalities from a PPL C_Polyhedron @@ -1173,7 +1173,7 @@ cdef class InequalityCollection: self.ineqs_generic.append(H) cdef _cinit_from_Polyhedron(self, list max_abs_coordinates, - list permutation, polyhedron): + list permutation, polyhedron) noexcept: """ Initialize the inequalities from a Sage Polyhedron @@ -1225,7 +1225,7 @@ cdef class InequalityCollection: H = Inequality_generic(A, b, Hrep_obj.index()) self.ineqs_generic.append(H) - cpdef prepare_next_to_inner_loop(self, p): + cpdef prepare_next_to_inner_loop(self, p) noexcept: r""" Peel off the next-to-inner loop. @@ -1263,7 +1263,7 @@ cdef class InequalityCollection: for ineq in self.ineqs_generic: (ineq).prepare_next_to_inner_loop(p) - cpdef prepare_inner_loop(self, p): + cpdef prepare_inner_loop(self, p) noexcept: r""" Peel off the inner loop. @@ -1302,7 +1302,7 @@ cdef class InequalityCollection: for ineq in self.ineqs_generic: (ineq).prepare_inner_loop(p) - cpdef swap_ineq_to_front(self, int i): + cpdef swap_ineq_to_front(self, int i) noexcept: r""" Swap the ``i``-th entry of the list to the front of the list of inequalities. @@ -1377,7 +1377,7 @@ cdef class InequalityCollection: return False return True - cpdef frozenset satisfied_as_equalities(self, inner_loop_variable): + cpdef frozenset satisfied_as_equalities(self, inner_loop_variable) noexcept: """ Return the inequalities (by their index) that are satisfied as equalities. @@ -1423,7 +1423,7 @@ cdef class InequalityCollection: -cpdef print_cache(InequalityCollection inequality_collection): +cpdef print_cache(InequalityCollection inequality_collection) noexcept: r""" Print the cached values in :class:`Inequality_int` (for debugging/doctesting only). diff --git a/src/sage/geometry/polyhedral_complex.py b/src/sage/geometry/polyhedral_complex.py index 2e20e508057..d6e3b075656 100644 --- a/src/sage/geometry/polyhedral_complex.py +++ b/src/sage/geometry/polyhedral_complex.py @@ -415,8 +415,7 @@ def cell_iterator(self, increasing=True): dim_index = reversed(dim_index) for d in dim_index: if d in cells: - for c in cells[d]: - yield c + yield from cells[d] def _n_cells_sorted(self, n, subcomplex=None): """ @@ -543,8 +542,7 @@ def maximal_cell_iterator(self, increasing=False): dim_index = reversed(dim_index) for d in dim_index: if d in maximal_cells: - for c in maximal_cells[d]: - yield c + yield from maximal_cells[d] def n_maximal_cells(self, n): r""" diff --git a/src/sage/geometry/polyhedron/base0.py b/src/sage/geometry/polyhedron/base0.py index 556eefc5148..4b31a8eb6ed 100644 --- a/src/sage/geometry/polyhedron/base0.py +++ b/src/sage/geometry/polyhedron/base0.py @@ -753,8 +753,7 @@ def Hrep_generator(self): sage: next(p.Hrep_generator()) An inequality (-1, 0, 0) x + 1 >= 0 """ - for H in self.Hrepresentation(): - yield H + yield from self.Hrepresentation() @cached_method def n_Hrepresentation(self): @@ -843,8 +842,7 @@ def Vrep_generator(self): sage: next(vg) A vertex at (1, 1, 1) """ - for V in self.Vrepresentation(): - yield V + yield from self.Vrepresentation() def inequality_generator(self): """ diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd index 030c9defa45..85a020df78a 100644 --- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd +++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd @@ -30,34 +30,34 @@ cdef class CombinatorialPolyhedron(SageObject): cdef ListOfPairs _face_lattice_incidences # stores incidences in Hasse diagram labeled indices of the faces cdef PolyhedronFaceLattice _all_faces # class to generate Hasse diagram incidences - cdef tuple Vrep(self) - cdef tuple facet_names(self) - cdef tuple equations(self) - cdef tuple equalities(self) - cdef unsigned int n_Vrepresentation(self) - cdef unsigned int n_Hrepresentation(self) - cdef bint is_bounded(self) - cdef ListOfFaces bitrep_facets(self) - cdef ListOfFaces bitrep_Vrep(self) - cdef tuple far_face_tuple(self) + cdef tuple Vrep(self) noexcept + cdef tuple facet_names(self) noexcept + cdef tuple equations(self) noexcept + cdef tuple equalities(self) noexcept + cdef unsigned int n_Vrepresentation(self) noexcept + cdef unsigned int n_Hrepresentation(self) noexcept + cdef bint is_bounded(self) noexcept + cdef ListOfFaces bitrep_facets(self) noexcept + cdef ListOfFaces bitrep_Vrep(self) noexcept + cdef tuple far_face_tuple(self) noexcept cdef int _algorithm_to_dual(self, algorithm) except -2 # Methods to initialize the combinatorial polyhedron. - cdef _init_from_polyhedron(self, data) - cdef _init_from_lattice_polytope(self, data) - cdef _init_from_cone(self, data) - cdef _init_facet_names(self, facets) - cdef _init_from_incidence_matrix(self, data) - cdef _init_from_list_of_facets(self, data) - cdef _init_from_ListOfFaces(self, ListOfFaces facets, ListOfFaces Vrep) - cdef _initialize_far_face(self) - cdef _init_as_trivial_polyhedron(self, int dimension) + cdef _init_from_polyhedron(self, data) noexcept + cdef _init_from_lattice_polytope(self, data) noexcept + cdef _init_from_cone(self, data) noexcept + cdef _init_facet_names(self, facets) noexcept + cdef _init_from_incidence_matrix(self, data) noexcept + cdef _init_from_list_of_facets(self, data) noexcept + cdef _init_from_ListOfFaces(self, ListOfFaces facets, ListOfFaces Vrep) noexcept + cdef _initialize_far_face(self) noexcept + cdef _init_as_trivial_polyhedron(self, int dimension) noexcept # Methods to obtain a different combinatorial polyhedron. - cpdef CombinatorialPolyhedron dual(self) - cpdef CombinatorialPolyhedron pyramid(self, new_vertex=*, new_facet=*) + cpdef CombinatorialPolyhedron dual(self) noexcept + cpdef CombinatorialPolyhedron pyramid(self, new_vertex=*, new_facet=*) noexcept - cdef FaceIterator _face_iter(self, bint dual, int dimension) + cdef FaceIterator _face_iter(self, bint dual, int dimension) noexcept cdef int _compute_f_vector(self, size_t num_threads, size_t parallelization_depth, int dual) except -1 cdef int _persist_f_vector(self, size_t* input_f_vector, bint input_is_reversed) except -1 diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pyx b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pyx index 5a07abb2408..8282fbbd1ca 100644 --- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pyx +++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pyx @@ -398,7 +398,7 @@ cdef class CombinatorialPolyhedron(SageObject): else: self._init_from_list_of_facets(data) - cdef _init_from_polyhedron(self, data): + cdef _init_from_polyhedron(self, data) noexcept: r''' Initialize from :class:`~sage.geometry.polyhedron.parent.Polyhedron_base`. ''' @@ -415,7 +415,7 @@ cdef class CombinatorialPolyhedron(SageObject): return self._init_from_incidence_matrix(data.incidence_matrix()) - cdef _init_from_lattice_polytope(self, data): + cdef _init_from_lattice_polytope(self, data) noexcept: r''' Initialize from :class:`~sage.geometry.lattice_polytope.LatticePolytopeClass`. ''' @@ -425,7 +425,7 @@ cdef class CombinatorialPolyhedron(SageObject): self._dimension = data.dimension() return self._init_from_incidence_matrix(data.incidence_matrix()) - cdef _init_from_cone(self, data): + cdef _init_from_cone(self, data) noexcept: r''' Initialize from :class:`~sage.geometry.cone.ConvexRationalPolyhedralCone`. ''' @@ -440,7 +440,7 @@ cdef class CombinatorialPolyhedron(SageObject): + [[ZZ.one() for _ in range(len(data.facet_normals()))]]) return self._init_from_incidence_matrix(incidence_matrix) - cdef _init_facet_names(self, facets): + cdef _init_facet_names(self, facets) noexcept: ''' Store facet names and compute equations. ''' @@ -461,7 +461,7 @@ cdef class CombinatorialPolyhedron(SageObject): else: self._facet_names = None - cdef _init_from_incidence_matrix(self, data): + cdef _init_from_incidence_matrix(self, data) noexcept: """ Initialize from an incidence matrix. """ @@ -498,7 +498,7 @@ cdef class CombinatorialPolyhedron(SageObject): self._initialize_far_face() - cdef _init_from_list_of_facets(self, data): + cdef _init_from_list_of_facets(self, data) noexcept: """ Initialize from a list of facets. @@ -543,7 +543,7 @@ cdef class CombinatorialPolyhedron(SageObject): self._initialize_far_face() - cdef _init_from_ListOfFaces(self, ListOfFaces facets, ListOfFaces Vrep): + cdef _init_from_ListOfFaces(self, ListOfFaces facets, ListOfFaces Vrep) noexcept: """ Initialize self from two ``ListOfFaces``. """ @@ -556,7 +556,7 @@ cdef class CombinatorialPolyhedron(SageObject): self._initialize_far_face() - cdef _initialize_far_face(self): + cdef _initialize_far_face(self) noexcept: """ Initialize far_face if unbounded. """ @@ -564,7 +564,7 @@ cdef class CombinatorialPolyhedron(SageObject): face_init(self._far_face, self.bitrep_facets().n_atoms(), self._n_facets) Vrep_list_to_bit_rep(tuple(self._far_face_tuple), self._far_face) - cdef _init_as_trivial_polyhedron(self, int dimension): + cdef _init_as_trivial_polyhedron(self, int dimension) noexcept: """ Initialize polyhedron equal to its affine hull. """ @@ -2805,7 +2805,7 @@ cdef class CombinatorialPolyhedron(SageObject): face_iter = face_generator - cdef FaceIterator _face_iter(self, bint dual, int dimension): + cdef FaceIterator _face_iter(self, bint dual, int dimension) noexcept: r""" A method to obtain the FaceIterator as Cython object. @@ -3255,13 +3255,13 @@ cdef class CombinatorialPolyhedron(SageObject): tester.assertTrue(all(j in f.ambient_V_indices() for f in b)) tester.assertTrue(all(i in f.ambient_H_indices() for f in b)) - cdef tuple Vrep(self): + cdef tuple Vrep(self) noexcept: r""" Return the names of the Vrepresentation, if they exist. Else return ``None``. """ return self._Vrep - cdef tuple facet_names(self): + cdef tuple facet_names(self) noexcept: r""" Return the names Hrepresentatives, which are facets. @@ -3269,7 +3269,7 @@ cdef class CombinatorialPolyhedron(SageObject): """ return self._facet_names - cdef tuple equations(self): + cdef tuple equations(self) noexcept: r""" Return the names of the equations. @@ -3277,18 +3277,18 @@ cdef class CombinatorialPolyhedron(SageObject): """ return self._equations - cdef tuple equalities(self): + cdef tuple equalities(self) noexcept: from sage.misc.superseded import deprecation deprecation(31834, "the method equalities of CombinatorialPolyhedron is deprecated; use equations", 3) return self.equations() - cdef unsigned int n_Vrepresentation(self): + cdef unsigned int n_Vrepresentation(self) noexcept: r""" Return the number of elements in the Vrepresentation. """ return self._n_Vrepresentation - cdef unsigned int n_Hrepresentation(self): + cdef unsigned int n_Hrepresentation(self) noexcept: r""" Return the number of elements in the Hrepresentation. """ @@ -3315,25 +3315,25 @@ cdef class CombinatorialPolyhedron(SageObject): """ return self.is_bounded() - cdef bint is_bounded(self): + cdef bint is_bounded(self) noexcept: r""" Return whether the polyhedron is bounded. """ return self._bounded - cdef ListOfFaces bitrep_facets(self): + cdef ListOfFaces bitrep_facets(self) noexcept: r""" Return the facets in bit representation. """ return self._bitrep_facets - cdef ListOfFaces bitrep_Vrep(self): + cdef ListOfFaces bitrep_Vrep(self) noexcept: r""" Return the Vrepresentations in bit representation. """ return self._bitrep_Vrep - cdef tuple far_face_tuple(self): + cdef tuple far_face_tuple(self) noexcept: r""" Return the far face as it was given on initialization. """ @@ -3357,7 +3357,7 @@ cdef class CombinatorialPolyhedron(SageObject): # Methods to obtain a different combinatorial polyhedron. - cpdef CombinatorialPolyhedron dual(self): + cpdef CombinatorialPolyhedron dual(self) noexcept: r""" Return the dual/polar of self. @@ -3400,7 +3400,7 @@ cdef class CombinatorialPolyhedron(SageObject): polar = dual - cpdef CombinatorialPolyhedron pyramid(self, new_vertex=None, new_facet=None): + cpdef CombinatorialPolyhedron pyramid(self, new_vertex=None, new_facet=None) noexcept: r""" Return the pyramid of ``self``. diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/combinatorial_face.pxd b/src/sage/geometry/polyhedron/combinatorial_polyhedron/combinatorial_face.pxd index 9193a5417a9..2169fe539f6 100644 --- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/combinatorial_face.pxd +++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/combinatorial_face.pxd @@ -31,7 +31,7 @@ cdef class CombinatorialFace(SageObject): # If ``dual == 0``, then coatoms are facets, atoms vertices and vice versa. cdef ListOfFaces atoms, coatoms - cpdef dimension(self) + cpdef dimension(self) noexcept cdef size_t n_atom_rep(self) except -1 cdef size_t set_coatom_rep(self) except -1 cdef size_t set_atom_rep(self) except -1 diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/combinatorial_face.pyx b/src/sage/geometry/polyhedron/combinatorial_polyhedron/combinatorial_face.pyx index bf01025707f..541927c6c11 100644 --- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/combinatorial_face.pyx +++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/combinatorial_face.pyx @@ -497,7 +497,7 @@ cdef class CombinatorialFace(SageObject): else: raise NotImplementedError("is_subface only implemented for faces of the same polyhedron") - cpdef dimension(self): + cpdef dimension(self) noexcept: r""" Return the dimension of the face. diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_data_structure.pxd b/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_data_structure.pxd index f37bcd36085..3ed71a664e1 100644 --- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_data_structure.pxd +++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_data_structure.pxd @@ -43,27 +43,27 @@ cdef inline bint face_init(face_t face, mp_bitcnt_t n_atoms, mp_bitcnt_t n_coato bitset_init(face.atoms, n_atoms) bitset_init(face.coatoms, n_coatoms) -cdef inline void face_free(face_t face): +cdef inline void face_free(face_t face) noexcept: """ Free ``face``. """ bitset_free(face.atoms) bitset_free(face.coatoms) -cdef inline bint face_check_alignment(face_t face): +cdef inline bint face_check_alignment(face_t face) noexcept: """ Return whether the data is correctly aligned. """ return bitset_check_alignment(face.atoms) -cdef inline void face_clear(face_t face): +cdef inline void face_clear(face_t face) noexcept: """ Remove all atoms and coatoms from face. """ bitset_clear(face.atoms) bitset_clear(face.coatoms) -cdef inline void face_copy(face_t dst, face_t src): +cdef inline void face_copy(face_t dst, face_t src) noexcept: """ Copy src to dst overwriting dst. @@ -77,20 +77,20 @@ cdef inline void face_copy(face_t dst, face_t src): # Face Comparison ############################################################################# -cdef inline bint face_isempty(face_t face) nogil: +cdef inline bint face_isempty(face_t face) noexcept nogil: """ Return whether ``face`` contains no coatoms. """ return bitset_isempty(face.atoms) -cdef inline int face_cmp(face_t a, face_t b): +cdef inline int face_cmp(face_t a, face_t b) noexcept: """ Return ``0`` if the faces are equal and consistently ``-1`` and ``1`` if not. """ return bitset_cmp(a.atoms, b.atoms) -cdef inline bint face_issubset_fused(face_t a, face_t b, algorithm_variant algorithm) nogil: +cdef inline bint face_issubset_fused(face_t a, face_t b, algorithm_variant algorithm) noexcept nogil: """ Return whether ``a`` is a subface of ``b``. """ @@ -99,20 +99,20 @@ cdef inline bint face_issubset_fused(face_t a, face_t b, algorithm_variant algor else: return bitset_issuperset(a.coatoms, b.coatoms) -cdef inline bint face_issubset(face_t a, face_t b) nogil: +cdef inline bint face_issubset(face_t a, face_t b) noexcept nogil: return face_issubset_fused(a, b, 0) ############################################################################# # Face Bit Manipulation ############################################################################# -cdef inline bint face_atom_in(face_t face, mp_bitcnt_t n): +cdef inline bint face_atom_in(face_t face, mp_bitcnt_t n) noexcept: """ Return whether ``n`` is an atom of ``face``. """ return bitset_in(face.atoms, n) -cdef inline void face_add_atom(face_t face, mp_bitcnt_t n): +cdef inline void face_add_atom(face_t face, mp_bitcnt_t n) noexcept: """ Add atom `n` to the face. """ @@ -126,20 +126,20 @@ cdef inline int face_add_atom_safe(face_t face, mp_bitcnt_t n) except -1: raise KeyError(n) bitset_add(face.atoms, n) -cdef inline void face_discard_atom(face_t face, mp_bitcnt_t n): +cdef inline void face_discard_atom(face_t face, mp_bitcnt_t n) noexcept: """ Discard atom `n` of the face. """ bitset_discard(face.atoms, n) -cdef inline void facet_set_coatom(face_t face, mp_bitcnt_t n): +cdef inline void facet_set_coatom(face_t face, mp_bitcnt_t n) noexcept: """ Set the facet to be coatom ``n``. """ bitset_clear(face.coatoms) bitset_add(face.coatoms, n) -cdef inline void face_set_first_n_atoms(face_t face, mp_bitcnt_t n): +cdef inline void face_set_first_n_atoms(face_t face, mp_bitcnt_t n) noexcept: """ Set exactly the first ``n`` atoms. """ @@ -150,7 +150,7 @@ cdef inline void face_set_first_n_atoms(face_t face, mp_bitcnt_t n): # Face Searching ############################################################################# -cdef inline long face_next_atom(face_t face, mp_bitcnt_t n): +cdef inline long face_next_atom(face_t face, mp_bitcnt_t n) noexcept: """ Return the index of the next atom in ``face`` with index >= ``n``. @@ -158,7 +158,7 @@ cdef inline long face_next_atom(face_t face, mp_bitcnt_t n): """ return bitset_next(face.atoms, n) -cdef inline long face_first_missing_atom(face_t face): +cdef inline long face_first_missing_atom(face_t face) noexcept: """ Return the index of the first atom not in ``face``. @@ -166,7 +166,7 @@ cdef inline long face_first_missing_atom(face_t face): """ return bitset_first_in_complement(face.atoms) -cdef inline long face_len_atoms(face_t face) nogil: +cdef inline long face_len_atoms(face_t face) noexcept nogil: """ Calculate the number of atoms in the face. """ @@ -177,7 +177,7 @@ cdef inline long face_len_atoms(face_t face) nogil: # Arithmetic ############################################################################# -cdef inline void face_intersection_fused(face_t dest, face_t A, face_t B, algorithm_variant algorithm) nogil: +cdef inline void face_intersection_fused(face_t dest, face_t A, face_t B, algorithm_variant algorithm) noexcept nogil: """ Set ``dest`` to the intersection of ``A`` and ``B``. """ @@ -188,7 +188,7 @@ cdef inline void face_intersection_fused(face_t dest, face_t A, face_t B, algori bitset_intersection(dest.atoms, A.atoms, B.atoms) bitset_union(dest.coatoms, A.coatoms, B.coatoms) -cdef inline void face_intersection(face_t dest, face_t A, face_t B) nogil: +cdef inline void face_intersection(face_t dest, face_t A, face_t B) noexcept nogil: face_intersection_fused(dest, A, B, 0) @@ -196,11 +196,11 @@ cdef inline void face_intersection(face_t dest, face_t A, face_t B) nogil: # Miscellaneous ############################################################################# -cdef inline void swap_faces(face_t a, face_t b) nogil: +cdef inline void swap_faces(face_t a, face_t b) noexcept nogil: cdef face_t tmp tmp[0] = a[0] a[0] = b[0] b[0] = tmp[0] -cdef inline bint faces_are_identical(face_t a, face_t b) nogil: +cdef inline bint faces_are_identical(face_t a, face_t b) noexcept nogil: return a.atoms.limbs == b.atoms.limbs diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_iterator.pxd b/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_iterator.pxd index 1dd74505306..f148c81f7a9 100644 --- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_iterator.pxd +++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_iterator.pxd @@ -70,7 +70,7 @@ cdef class FaceIterator_base(SageObject): # If ``dual == 0``, then coatoms are facets, atoms vertices and vice versa. cdef ListOfFaces atoms, coatoms, coatoms_coatom_rep - cdef inline CombinatorialFace next_face(self) + cdef inline CombinatorialFace next_face(self) noexcept cdef inline int next_dimension(self) except -1 cdef inline int next_face_loop(self) except -1 cdef size_t n_atom_rep(self) except -1 @@ -94,6 +94,6 @@ cdef int parallel_f_vector(iter_t* structures, size_t num_threads, size_t parall # Nogil definitions of crucial functions. -cdef int next_dimension(iter_t structure, size_t parallelization_depth=?) nogil except -1 -cdef int next_face_loop(iter_t structure) nogil except -1 -cdef size_t n_atom_rep(iter_t structure) nogil except -1 +cdef int next_dimension(iter_t structure, size_t parallelization_depth=?) except -1 nogil +cdef int next_face_loop(iter_t structure) except -1 nogil +cdef size_t n_atom_rep(iter_t structure) except -1 nogil diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_iterator.pyx b/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_iterator.pyx index f03f0f832ff..d35033fc855 100644 --- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_iterator.pyx +++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_iterator.pyx @@ -1201,7 +1201,7 @@ cdef class FaceIterator_base(SageObject): # for the dimension. By this time the current dimension has changed. self.structure.highest_dimension = self.structure.current_dimension - 1 - cdef inline CombinatorialFace next_face(self): + cdef inline CombinatorialFace next_face(self) noexcept: r""" Set attribute ``face`` to the next face and return it as :class:`sage.geometry.polyhedron.combinatorial_polyhedron.combinatorial_face.CombinatorialFace`. @@ -1923,7 +1923,7 @@ cdef class FaceIterator_geom(FaceIterator_base): # Nogil definitions of crucial functions. -cdef inline int next_dimension(iter_t structure, size_t parallelization_depth=0) nogil except -1: +cdef inline int next_dimension(iter_t structure, size_t parallelization_depth=0) except -1 nogil: r""" See :meth:`FaceIterator.next_dimension`. @@ -1937,7 +1937,7 @@ cdef inline int next_dimension(iter_t structure, size_t parallelization_depth=0) structure._index += 1 return structure.current_dimension -cdef inline int next_face_loop(iter_t structure) nogil except -1: +cdef inline int next_face_loop(iter_t structure) except -1 nogil: r""" See :meth:`FaceIterator.next_face_loop`. """ @@ -2023,7 +2023,7 @@ cdef inline int next_face_loop(iter_t structure) nogil except -1: structure.first_time[structure.current_dimension] = True return 0 -cdef inline size_t n_atom_rep(iter_t structure) nogil except -1: +cdef inline size_t n_atom_rep(iter_t structure) except -1 nogil: r""" See :meth:`FaceIterator.n_atom_rep`. """ @@ -2114,7 +2114,7 @@ cdef int parallel_f_vector(iter_t* structures, size_t num_threads, size_t parall f_vector[j] += parallel_structs[i].f_vector[j] cdef int _parallel_f_vector(iter_t structure, size_t parallelization_depth, - parallel_f_t parallel_struct, size_t job_id) nogil except -1: + parallel_f_t parallel_struct, size_t job_id) except -1 nogil: """ Set up a job and then visit all faces. """ @@ -2129,7 +2129,7 @@ cdef int _parallel_f_vector(iter_t structure, size_t parallelization_depth, cdef inline int prepare_face_iterator_for_partial_job( iter_t structure, size_t parallelization_depth, - parallel_f_t parallel_struct, size_t job_id) nogil except -1: + parallel_f_t parallel_struct, size_t job_id) except -1 nogil: """ Set ``structure`` according to ``job_id``. @@ -2258,7 +2258,7 @@ cdef inline int prepare_face_iterator_for_partial_job( return 1 -cdef inline size_t get_digit(size_t job_id, size_t pos, size_t padto, size_t base) nogil: +cdef inline size_t get_digit(size_t job_id, size_t pos, size_t padto, size_t base) noexcept nogil: """ Get the digit ``pos`` of ``job_id`` with base ``base`` padding the number of digits to ``pad_to``. diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_list_data_structure.pxd b/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_list_data_structure.pxd index 79b319e1982..105cc81b9a4 100644 --- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_list_data_structure.pxd +++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_list_data_structure.pxd @@ -56,7 +56,7 @@ cdef inline int face_list_shallow_init(face_list_t faces, size_t n_faces, size_t faces.is_not_new_face = check_allocarray(n_faces, sizeof(bint)) faces.polyhedron_is_simple = False -cdef inline void face_list_free(face_list_t faces): +cdef inline void face_list_free(face_list_t faces) noexcept: """ Free faces. """ @@ -66,7 +66,7 @@ cdef inline void face_list_free(face_list_t faces): face_free(faces.faces[i]) face_list_shallow_free(faces) -cdef inline void face_list_shallow_free(face_list_t faces): +cdef inline void face_list_shallow_free(face_list_t faces) noexcept: """ Free a shallow list of faces. """ @@ -106,7 +106,7 @@ cdef inline int face_list_shallow_copy(face_list_t dst, face_list_t src) except for i in range(src.n_faces): dst.faces[i][0] = src.faces[i][0] -cdef inline int add_face_shallow(face_list_t faces, face_t face) nogil except -1: +cdef inline int add_face_shallow(face_list_t faces, face_t face) except -1 nogil: """ Add a face to faces. """ @@ -124,7 +124,7 @@ cdef inline int add_face_deep(face_list_t faces, face_t face) except -1: face_copy(faces.faces[faces.n_faces], face) faces.n_faces += 1 -cdef inline void face_list_delete_faces_by_array(face_list_t faces, bint *delete): +cdef inline void face_list_delete_faces_by_array(face_list_t faces, bint *delete) noexcept: r""" Remove face ``i`` if and only if ``delete[i]`` decreasing ``faces.n_faces``. @@ -144,7 +144,7 @@ cdef inline void face_list_delete_faces_by_array(face_list_t faces, bint *delete faces.n_faces = n_newfaces faces.total_n_faces = n_newfaces -cdef inline void face_list_delete_faces_by_face(face_list_t faces, face_t face): +cdef inline void face_list_delete_faces_by_face(face_list_t faces, face_t face) noexcept: r""" Remove all faces such that the ``i``-th bit in ``face`` is not set descreasing ``faces.n_faces``. @@ -170,9 +170,9 @@ cdef inline void face_list_delete_faces_by_face(face_list_t faces, face_t face): # Face Comparison ############################################################################# -cdef void sort_faces_list(face_list_t faces) +cdef void sort_faces_list(face_list_t faces) noexcept -cdef inline size_t find_face(face_t face, face_list_t faces): +cdef inline size_t find_face(face_t face, face_list_t faces) noexcept: r""" Return the index of ``face`` in ``faces``. @@ -211,7 +211,7 @@ cdef inline size_t find_face(face_t face, face_list_t faces): else: return -1 -cdef inline bint is_contained_in_one_fused(face_t face, face_list_t faces, algorithm_variant algorithm) nogil: +cdef inline bint is_contained_in_one_fused(face_t face, face_list_t faces, algorithm_variant algorithm) noexcept nogil: """ Return whether ``face`` is contained in one of ``faces``. """ @@ -221,7 +221,7 @@ cdef inline bint is_contained_in_one_fused(face_t face, face_list_t faces, algor return True return False -cdef inline bint is_not_maximal_fused(face_list_t faces, size_t j, algorithm_variant algorithm, bint* is_not_new_face) nogil: +cdef inline bint is_not_maximal_fused(face_list_t faces, size_t j, algorithm_variant algorithm, bint* is_not_new_face) noexcept nogil: """ Return whether face ``j`` is not maximal in ``faces``. """ @@ -246,7 +246,7 @@ cdef inline bint is_not_maximal_fused(face_list_t faces, size_t j, algorithm_var # Arithmetic ############################################################################# -cdef inline int face_list_intersection_fused(face_list_t dest, face_list_t A, face_t b, algorithm_variant algorithm) nogil except -1: +cdef inline int face_list_intersection_fused(face_list_t dest, face_list_t A, face_t b, algorithm_variant algorithm) except -1 nogil: """ Set ``dest`` to be the intersection of each face of ``A`` with ``b``. """ @@ -267,7 +267,7 @@ cdef inline int face_list_intersection_fused(face_list_t dest, face_list_t A, fa cdef inline size_t get_next_level_fused( face_list_t faces, face_list_t new_faces, - face_list_t visited_all, algorithm_variant algorithm) nogil except -1: + face_list_t visited_all, algorithm_variant algorithm) except -1 nogil: """ Set ``new_faces`` to be the facets of ``faces.faces[face.n_faces-1]`` that are not contained in a face of ``visited_all``. @@ -337,7 +337,7 @@ cdef inline size_t get_next_level_fused( cdef inline size_t get_next_level( face_list_t faces, face_list_t new_faces, - face_list_t visited_all) nogil except -1: + face_list_t visited_all) except -1 nogil: cdef size_t output if faces.polyhedron_is_simple: @@ -346,7 +346,7 @@ cdef inline size_t get_next_level( output = get_next_level_fused(faces, new_faces, visited_all, 0) return output -cdef inline size_t bit_rep_to_coatom_rep(face_t face, face_list_t coatoms, size_t *output): +cdef inline size_t bit_rep_to_coatom_rep(face_t face, face_list_t coatoms, size_t *output) noexcept: """ Write the coatom-representation of face in output. Return length. ``face_length`` is the length of ``face`` and ``coatoms[i]`` @@ -361,7 +361,7 @@ cdef inline size_t bit_rep_to_coatom_rep(face_t face, face_list_t coatoms, size_ count_length += 1 return count_length -cdef inline bint face_list_check_alignment(face_list_t faces): +cdef inline bint face_list_check_alignment(face_list_t faces) noexcept: """ Return whether all faces in ``faces`` are aligned correctly. """ diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_list_data_structure.pyx b/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_list_data_structure.pyx index ec9c23d090d..3f33aec8ec6 100644 --- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_list_data_structure.pyx +++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/face_list_data_structure.pyx @@ -11,7 +11,7 @@ Sorting of a list of faces. # https://www.gnu.org/licenses/ #**************************************************************************** -cdef void sort_faces_list(face_list_t faces): +cdef void sort_faces_list(face_list_t faces) noexcept: r""" Sorts faces in place. """ @@ -23,7 +23,7 @@ cdef void sort_faces_list(face_list_t faces): # Sort the faces using merge sort. _sort_faces_loop(faces.faces, faces.faces, extra_mem, faces.n_faces) -cdef void _sort_faces_loop(face_t* inp, face_t* out, face_t* extra_mem, size_t n_faces): +cdef void _sort_faces_loop(face_t* inp, face_t* out, face_t* extra_mem, size_t n_faces) noexcept: """ This is merge sort. diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/list_of_faces.pxd b/src/sage/geometry/polyhedron/combinatorial_polyhedron/list_of_faces.pxd index d16065979eb..d50c8f85539 100644 --- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/list_of_faces.pxd +++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/list_of_faces.pxd @@ -7,23 +7,23 @@ cdef class ListOfFaces: # It will be of "type" ``uint64_t[n_faces][face_length]`` cdef face_list_t data - cpdef ListOfFaces __copy__(self) + cpdef ListOfFaces __copy__(self) noexcept cpdef int compute_dimension(self) except -2 - cdef inline size_t n_faces(self): + cdef inline size_t n_faces(self) noexcept: return self.data.n_faces - cdef inline size_t n_atoms(self): + cdef inline size_t n_atoms(self) noexcept: return self.data.n_atoms - cdef inline size_t n_coatoms(self): + cdef inline size_t n_coatoms(self) noexcept: return self.data.n_coatoms - cpdef ListOfFaces pyramid(self) + cpdef ListOfFaces pyramid(self) noexcept - cdef ListOfFaces delete_atoms_unsafe(self, bint* delete, face_t face) # not in place - cdef void delete_faces_unsafe(self, bint* delete, face_t face) # in place + cdef ListOfFaces delete_atoms_unsafe(self, bint* delete, face_t face) noexcept # not in place + cdef void delete_faces_unsafe(self, bint* delete, face_t face) noexcept # in place - cdef void get_not_inclusion_maximal_unsafe(self, bint *not_inclusion_maximal) - cdef void get_faces_all_set_unsafe(self, bint *all_set) + cdef void get_not_inclusion_maximal_unsafe(self, bint *not_inclusion_maximal) noexcept + cdef void get_faces_all_set_unsafe(self, bint *all_set) noexcept -cdef tuple face_as_combinatorial_polyhedron(ListOfFaces facets, ListOfFaces Vrep, face_t face, bint dual) +cdef tuple face_as_combinatorial_polyhedron(ListOfFaces facets, ListOfFaces Vrep, face_t face, bint dual) noexcept diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/list_of_faces.pyx b/src/sage/geometry/polyhedron/combinatorial_polyhedron/list_of_faces.pyx index dffa76036fa..9b5f3dd4ada 100644 --- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/list_of_faces.pyx +++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/list_of_faces.pyx @@ -178,7 +178,7 @@ cdef class ListOfFaces: """ assert face_list_check_alignment(self.data) - cpdef ListOfFaces __copy__(self): + cpdef ListOfFaces __copy__(self) noexcept: r""" Return a copy of self. @@ -303,7 +303,7 @@ cdef class ListOfFaces: # by calculating dimension of one of its faces. return new_faces.compute_dimension() + 1 - cpdef ListOfFaces pyramid(self): + cpdef ListOfFaces pyramid(self) noexcept: r""" Return the list of faces of the pyramid. @@ -381,7 +381,7 @@ cdef class ListOfFaces: return copy - cdef ListOfFaces delete_atoms_unsafe(self, bint *delete, face_t face): + cdef ListOfFaces delete_atoms_unsafe(self, bint *delete, face_t face) noexcept: r""" Return a copy of ``self`` where bits in ``delete`` have been removed/contracted. @@ -421,7 +421,7 @@ cdef class ListOfFaces: return output - cdef void delete_faces_unsafe(self, bint *delete, face_t face): + cdef void delete_faces_unsafe(self, bint *delete, face_t face) noexcept: r""" Deletes face ``i`` if and only if ``delete[i]``. @@ -439,7 +439,7 @@ cdef class ListOfFaces: else: face_list_delete_faces_by_face(self.data, face) - cdef void get_not_inclusion_maximal_unsafe(self, bint *not_inclusion_maximal): + cdef void get_not_inclusion_maximal_unsafe(self, bint *not_inclusion_maximal) noexcept: r""" Get all faces that are not inclusion maximal. @@ -458,7 +458,7 @@ cdef class ListOfFaces: for i in range(self.n_faces()): not_inclusion_maximal[i] = is_not_maximal_fused(self.data, i, 0, not_inclusion_maximal) - cdef void get_faces_all_set_unsafe(self, bint *all_set): + cdef void get_faces_all_set_unsafe(self, bint *all_set) noexcept: r""" Get the faces that have all ``bits`` set. @@ -518,7 +518,7 @@ cdef class ListOfFaces: M.set_immutable() return M -cdef tuple face_as_combinatorial_polyhedron(ListOfFaces facets, ListOfFaces Vrep, face_t face, bint dual): +cdef tuple face_as_combinatorial_polyhedron(ListOfFaces facets, ListOfFaces Vrep, face_t face, bint dual) noexcept: r""" Obtain facets and Vrepresentation of ``face`` as new combinatorial polyhedron. diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/polyhedron_face_lattice.pxd b/src/sage/geometry/polyhedron/combinatorial_polyhedron/polyhedron_face_lattice.pxd index 4e7987b0d7a..438dc8de6f7 100644 --- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/polyhedron_face_lattice.pxd +++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/polyhedron_face_lattice.pxd @@ -40,11 +40,11 @@ cdef class PolyhedronFaceLattice: cdef int _sort(self) except -1 cdef inline size_t find_face(self, int dimension, face_t face) except -2 - cpdef CombinatorialFace get_face(self, int dimension, size_t index) + cpdef CombinatorialFace get_face(self, int dimension, size_t index) noexcept cdef size_t set_coatom_rep(self, int dimension, size_t index) except -1 cdef size_t set_atom_rep(self, int dimension, size_t index) except -1 - cdef void incidence_init(self, int dimension_one, int dimension_two) - cdef inline bint next_incidence(self, size_t *one, size_t *two) - cdef inline bint next_incidence_loop(self, size_t *one, size_t *two) - cdef inline bint next_trivial_incidence(self, size_t *one, size_t *two) - cdef inline bint next_trivial_incidence2(self, size_t *one, size_t *two) + cdef void incidence_init(self, int dimension_one, int dimension_two) noexcept + cdef inline bint next_incidence(self, size_t *one, size_t *two) noexcept + cdef inline bint next_incidence_loop(self, size_t *one, size_t *two) noexcept + cdef inline bint next_trivial_incidence(self, size_t *one, size_t *two) noexcept + cdef inline bint next_trivial_incidence2(self, size_t *one, size_t *two) noexcept diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/polyhedron_face_lattice.pyx b/src/sage/geometry/polyhedron/combinatorial_polyhedron/polyhedron_face_lattice.pyx index be6ffbda794..9f5a98c7ece 100644 --- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/polyhedron_face_lattice.pyx +++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/polyhedron_face_lattice.pyx @@ -315,7 +315,7 @@ cdef class PolyhedronFaceLattice: return find_face(face, self.faces[dimension+1]) - cpdef CombinatorialFace get_face(self, int dimension, size_t index): + cpdef CombinatorialFace get_face(self, int dimension, size_t index) noexcept: r""" Return the face of dimension ``dimension`` and index ``index``. @@ -401,7 +401,7 @@ cdef class PolyhedronFaceLattice: cdef face_t face = self.faces[dimension+1].faces[index] return bit_rep_to_Vrep_list(face, self.atom_rep) - cdef void incidence_init(self, int dimension_one, int dimension_two): + cdef void incidence_init(self, int dimension_one, int dimension_two) noexcept: r""" Initialize the :class:`PolyhedronFaceLattice` to give incidences between ``dimension_one`` and ``dimension_two``. @@ -454,7 +454,7 @@ cdef class PolyhedronFaceLattice: self.incidence_counter_two = 0 self.is_incidence_initialized = 1 - cdef inline bint next_incidence(self, size_t *one, size_t *two): + cdef inline bint next_incidence(self, size_t *one, size_t *two) noexcept: r""" Set ``one[0]`` and ``two[0]`` to be the next incidence. Return ``True`` unless there are no more incidences, then return `0`. @@ -484,7 +484,7 @@ cdef class PolyhedronFaceLattice: return result - cdef inline bint next_incidence_loop(self, size_t *one, size_t *two): + cdef inline bint next_incidence_loop(self, size_t *one, size_t *two) noexcept: r""" Set ``one[0]`` and ``two[0]`` to be the next incidence. Return ``True`` on success and ``False`` otherwise. @@ -534,7 +534,7 @@ cdef class PolyhedronFaceLattice: if self.is_incidence_initialized == 0: return 0 - cdef inline bint next_trivial_incidence(self, size_t *one, size_t *two): + cdef inline bint next_trivial_incidence(self, size_t *one, size_t *two) noexcept: r""" Handling the case where ``dimension_one`` is dimension of polyhedron. @@ -551,7 +551,7 @@ cdef class PolyhedronFaceLattice: return (two[0] < self.f_vector[self.incidence_dim_two + 1]) - cdef inline bint next_trivial_incidence2(self, size_t *one, size_t *two): + cdef inline bint next_trivial_incidence2(self, size_t *one, size_t *two) noexcept: r""" Handling the case where ``dimension_two`` is `-1`. diff --git a/src/sage/geometry/polyhedron/generating_function.py b/src/sage/geometry/polyhedron/generating_function.py index 2c6cfccf200..7a33bd528b9 100644 --- a/src/sage/geometry/polyhedron/generating_function.py +++ b/src/sage/geometry/polyhedron/generating_function.py @@ -772,7 +772,7 @@ def decode_factor(factor): return _simplify_(numerator, terms) -class _TransformHrepresentation(object): +class _TransformHrepresentation: r""" An abstract base class for transformations of the Hrepresentation of a polyhedron together with its @@ -1428,7 +1428,7 @@ def __init__(self, inequalities, equations, B, mod): <..._TransformMod object at 0x...> """ self.mod = mod - super(_TransformMod, self).__init__(inequalities, equations, B) + super().__init__(inequalities, equations, B) def _transform_(self): r""" diff --git a/src/sage/geometry/polyhedron/plot.py b/src/sage/geometry/polyhedron/plot.py index b6bb235b711..03628f60e22 100644 --- a/src/sage/geometry/polyhedron/plot.py +++ b/src/sage/geometry/polyhedron/plot.py @@ -843,8 +843,7 @@ def defining_equation(): # corresponding to a polygon if polyhedron.dim() < 3: yield next(polyhedron.equation_generator()) else: - for ineq in polyhedron.inequality_generator(): - yield ineq + yield from polyhedron.inequality_generator() faces = [] face_inequalities = [] diff --git a/src/sage/geometry/toric_lattice_element.pyx b/src/sage/geometry/toric_lattice_element.pyx index 40897c019f5..bc736243642 100644 --- a/src/sage/geometry/toric_lattice_element.pyx +++ b/src/sage/geometry/toric_lattice_element.pyx @@ -223,7 +223,7 @@ cdef class ToricLatticeElement(Vector_integer_dense): """ return Vector_integer_dense.__hash__(self) - cpdef _act_on_(self, other, bint self_on_left): + cpdef _act_on_(self, other, bint self_on_left) noexcept: """ Act on ``other``. @@ -298,7 +298,7 @@ cdef class ToricLatticeElement(Vector_integer_dense): # We need to override this function to prohibit default behaviour. # It seems to be called when right is in the same lattice as self, which # is wrong from our point of view. - cpdef _dot_product_(self, Vector right): + cpdef _dot_product_(self, Vector right) noexcept: """ Raise a ``TypeError`` exception. diff --git a/src/sage/geometry/triangulation/base.pyx b/src/sage/geometry/triangulation/base.pyx index d66186db098..cbb1673d0f2 100644 --- a/src/sage/geometry/triangulation/base.pyx +++ b/src/sage/geometry/triangulation/base.pyx @@ -109,7 +109,7 @@ cdef class Point(SageObject): """ return hash(self._point_configuration) ^ (self._index) - cpdef point_configuration(self): + cpdef point_configuration(self) noexcept: r""" Return the point configuration to which the point belongs. @@ -158,7 +158,7 @@ cdef class Point(SageObject): """ return len(self._affine) - cpdef index(self): + cpdef index(self) noexcept: """ Return the index of the point in the point configuration. @@ -172,7 +172,7 @@ cdef class Point(SageObject): """ return self._index - cpdef projective(self): + cpdef projective(self) noexcept: r""" Return the projective coordinates of the point in the ambient space. @@ -198,7 +198,7 @@ cdef class Point(SageObject): """ return self._projective - cpdef affine(self): + cpdef affine(self) noexcept: r""" Return the affine coordinates of the point in the ambient space. @@ -224,7 +224,7 @@ cdef class Point(SageObject): """ return self._affine - cpdef reduced_affine(self): + cpdef reduced_affine(self) noexcept: r""" Return the affine coordinates of the point on the hyperplane spanned by the point configuration. @@ -251,7 +251,7 @@ cdef class Point(SageObject): """ return self._reduced_affine - cpdef reduced_projective(self): + cpdef reduced_projective(self) noexcept: r""" Return the projective coordinates of the point on the hyperplane spanned by the point configuration. @@ -278,7 +278,7 @@ cdef class Point(SageObject): """ return tuple(self._reduced_affine)+(1,) - cpdef reduced_affine_vector(self): + cpdef reduced_affine_vector(self) noexcept: """ Return the affine coordinates of the point on the hyperplane spanned by the point configuration. @@ -305,7 +305,7 @@ cdef class Point(SageObject): """ return self._reduced_affine_vector - cpdef reduced_projective_vector(self): + cpdef reduced_projective_vector(self) noexcept: """ Return the affine coordinates of the point on the hyperplane spanned by the point configuration. @@ -334,7 +334,7 @@ cdef class Point(SageObject): """ return self._reduced_projective_vector - cpdef _repr_(self): + cpdef _repr_(self) noexcept: """ Return a string representation of the point. @@ -396,7 +396,7 @@ cdef class PointConfiguration_base(Parent): cdef bint _is_affine cdef object _reduced_affine_vector_space, _reduced_projective_vector_space - cdef _init_points(self, tuple projective_points): + cdef _init_points(self, tuple projective_points) noexcept: """ Internal method to determine coordinates of points. @@ -466,7 +466,7 @@ cdef class PointConfiguration_base(Parent): """ return hash_by_id( self) - cpdef reduced_affine_vector_space(self): + cpdef reduced_affine_vector_space(self) noexcept: """ Return the vector space that contains the affine points. @@ -486,7 +486,7 @@ cdef class PointConfiguration_base(Parent): """ return self._reduced_affine_vector_space - cpdef reduced_projective_vector_space(self): + cpdef reduced_projective_vector_space(self) noexcept: """ Return the vector space that is spanned by the homogeneous coordinates. @@ -507,7 +507,7 @@ cdef class PointConfiguration_base(Parent): """ return self._reduced_projective_vector_space - cpdef ambient_dim(self): + cpdef ambient_dim(self) noexcept: """ Return the dimension of the ambient space of the point configuration. @@ -524,7 +524,7 @@ cdef class PointConfiguration_base(Parent): """ return self._ambient_dim - cpdef dim(self): + cpdef dim(self) noexcept: """ Return the actual dimension of the point configuration. @@ -540,7 +540,7 @@ cdef class PointConfiguration_base(Parent): """ return self._dim - cpdef base_ring(self): + cpdef base_ring(self) noexcept: r""" Return the base ring, that is, the ring containing the coordinates of the points. @@ -565,7 +565,7 @@ cdef class PointConfiguration_base(Parent): """ return self._base_ring - cpdef bint is_affine(self): + cpdef bint is_affine(self) noexcept: """ Return whether the configuration is defined by affine points. @@ -632,7 +632,7 @@ cdef class PointConfiguration_base(Parent): """ return self._pts[i] - cpdef n_points(self): + cpdef n_points(self) noexcept: """ Return the number of points. @@ -653,7 +653,7 @@ cdef class PointConfiguration_base(Parent): """ return len(self._pts) - cpdef points(self): + cpdef points(self) noexcept: """ Return a list of the points. @@ -731,7 +731,7 @@ cdef class PointConfiguration_base(Parent): """ return len(self._pts) - cpdef simplex_to_int(self, simplex): + cpdef simplex_to_int(self, simplex) noexcept: r""" Return an integer that uniquely identifies the given simplex. @@ -776,7 +776,7 @@ cdef class PointConfiguration_base(Parent): k = l+1 return s - cpdef int_to_simplex(self, int s): + cpdef int_to_simplex(self, int s) noexcept: r""" Reverse the enumeration of possible simplices in :meth:`simplex_to_int`. diff --git a/src/sage/geometry/triangulation/element.py b/src/sage/geometry/triangulation/element.py index 16b55ab7cac..e8c8d7e1a51 100644 --- a/src/sage/geometry/triangulation/element.py +++ b/src/sage/geometry/triangulation/element.py @@ -336,8 +336,7 @@ def __iter__(self): ... StopIteration """ - for p in self._triangulation: - yield p + yield from self._triangulation def __getitem__(self, i): """ diff --git a/src/sage/geometry/triangulation/point_configuration.py b/src/sage/geometry/triangulation/point_configuration.py index 14afe670c16..68ac3119945 100644 --- a/src/sage/geometry/triangulation/point_configuration.py +++ b/src/sage/geometry/triangulation/point_configuration.py @@ -501,8 +501,7 @@ def __iter__(self): sage: [p.point(i) for i in range(p.n_points())] [P(1, 1), P(2, 2), P(3, 3)] """ - for p in self.points(): - yield p + yield from self.points() def _repr_(self): r""" @@ -719,8 +718,7 @@ def _TOPCOM_triangulations(self, verbose=True): if self._regular is False: command += ' --nonregular' - for t in self._TOPCOM_communicate(command, verbose): - yield t + yield from self._TOPCOM_communicate(command, verbose) def _TOPCOM_triangulate(self, verbose=True): r""" @@ -988,8 +986,7 @@ def triangulations(self, verbose=False): sage: p.set_engine('internal') """ if self._use_TOPCOM: - for triangulation in self._TOPCOM_triangulations(verbose): - yield triangulation + yield from self._TOPCOM_triangulations(verbose) else: if not self._connected: raise ValueError('Need TOPCOM to find disconnected triangulations.') diff --git a/src/sage/graphs/asteroidal_triples.pyx b/src/sage/graphs/asteroidal_triples.pyx index d2423c912e3..fc5cc3ff09b 100644 --- a/src/sage/graphs/asteroidal_triples.pyx +++ b/src/sage/graphs/asteroidal_triples.pyx @@ -184,7 +184,7 @@ cdef list is_asteroidal_triple_free_C(uint32_t n, short_digraph sd, uint32_t** connected_structure, uint32_t* waiting_list, - bitset_t seen): + bitset_t seen) noexcept: """ INPUT: diff --git a/src/sage/graphs/base/boost_graph.pyx b/src/sage/graphs/base/boost_graph.pyx index f158aaafd27..84b048c84c5 100644 --- a/src/sage/graphs/base/boost_graph.pyx +++ b/src/sage/graphs/base/boost_graph.pyx @@ -55,7 +55,7 @@ from libcpp.set cimport set as cset from libcpp.pair cimport pair -cdef boost_graph_from_sage_graph(BoostGenGraph *g, g_sage, vertex_to_int, reverse=False): +cdef boost_graph_from_sage_graph(BoostGenGraph *g, g_sage, vertex_to_int, reverse=False) noexcept: r""" Initialize the Boost graph ``g`` to be equal to ``g_sage``. @@ -98,7 +98,7 @@ cdef boost_weighted_graph_from_sage_graph(BoostWeightedGraph *g, g_sage, vertex_to_int, weight_function=None, - reverse=False): + reverse=False) noexcept: r""" Initialize the Boost weighted graph ``g`` to be equal to ``g_sage``. @@ -169,7 +169,7 @@ cdef boost_weighted_graph_from_sage_graph(BoostWeightedGraph *g, g.add_edge(vertex_to_int[u], vertex_to_int[v], 1) -cdef boost_edge_connectivity(BoostVecGenGraph *g): +cdef boost_edge_connectivity(BoostVecGenGraph *g) noexcept: r""" Compute the edge connectivity of the input Boost graph. @@ -189,7 +189,7 @@ cdef boost_edge_connectivity(BoostVecGenGraph *g): return (result.ec, edges) -cpdef edge_connectivity(g): +cpdef edge_connectivity(g) noexcept: r""" Compute the edge connectivity of the input graph, using Boost. @@ -244,7 +244,7 @@ cpdef edge_connectivity(g): return (ec, [(int_to_vertex[u], int_to_vertex[v]) for u, v in edges]) -cdef boost_clustering_coeff(BoostGenGraph *g, vertices): +cdef boost_clustering_coeff(BoostGenGraph *g, vertices) noexcept: r""" Compute the clustering coefficient of all vertices in the list provided. @@ -276,7 +276,7 @@ cdef boost_clustering_coeff(BoostGenGraph *g, vertices): return ((sum(clust_of_v.itervalues()) / len(clust_of_v)), clust_of_v) -cpdef clustering_coeff(g, vertices=None): +cpdef clustering_coeff(g, vertices=None) noexcept: r""" Compute the clustering coefficient of the input graph, using Boost. @@ -343,7 +343,7 @@ cpdef clustering_coeff(g, vertices=None): @cython.binding(True) -cpdef dominator_tree(g, root, return_dict=False, reverse=False): +cpdef dominator_tree(g, root, return_dict=False, reverse=False) noexcept: r""" Use Boost to compute the dominator tree of ``g``, rooted at ``root``. @@ -500,7 +500,7 @@ cpdef dominator_tree(g, root, return_dict=False, reverse=False): return Graph(edges) -cpdef bandwidth_heuristics(g, algorithm='cuthill_mckee'): +cpdef bandwidth_heuristics(g, algorithm='cuthill_mckee') noexcept: r""" Use Boost heuristics to approximate the bandwidth of the input graph. @@ -608,7 +608,7 @@ cpdef bandwidth_heuristics(g, algorithm='cuthill_mckee'): cpdef min_spanning_tree(g, weight_function=None, - algorithm='Kruskal'): + algorithm='Kruskal') noexcept: r""" Use Boost to compute the minimum spanning tree of the input graph. @@ -733,7 +733,7 @@ cpdef min_spanning_tree(g, return [(u, v, g.edge_label(u, v)) for u, v in edges] -cpdef blocks_and_cut_vertices(g): +cpdef blocks_and_cut_vertices(g) noexcept: r""" Compute the blocks and cut vertices of the graph. @@ -828,7 +828,7 @@ cpdef blocks_and_cut_vertices(g): return (result_blocks, list(result_cut)) -cpdef shortest_paths(g, start, weight_function=None, algorithm=None): +cpdef shortest_paths(g, start, weight_function=None, algorithm=None) noexcept: r""" Compute the shortest paths from ``start`` to all other vertices. @@ -1026,7 +1026,7 @@ cpdef shortest_paths(g, start, weight_function=None, algorithm=None): return (dist, pred) -cdef get_predecessors(BoostWeightedGraph g, result, int_to_v, directed, weight_type): +cdef get_predecessors(BoostWeightedGraph g, result, int_to_v, directed, weight_type) noexcept: r""" Return the predecessor matrix from the distance matrix of the graph. @@ -1083,7 +1083,7 @@ cdef get_predecessors(BoostWeightedGraph g, result, int_to_v, directed, weight_t return pred -cpdef johnson_shortest_paths(g, weight_function=None, distances=True, predecessors=False): +cpdef johnson_shortest_paths(g, weight_function=None, distances=True, predecessors=False) noexcept: r""" Use Johnson algorithm to solve the all-pairs-shortest-paths. @@ -1238,7 +1238,7 @@ cpdef johnson_shortest_paths(g, weight_function=None, distances=True, predecesso return pred -cpdef floyd_warshall_shortest_paths(g, weight_function=None, distances=True, predecessors=False): +cpdef floyd_warshall_shortest_paths(g, weight_function=None, distances=True, predecessors=False) noexcept: r""" Use Floyd-Warshall algorithm to solve the all-pairs-shortest-paths. @@ -1394,7 +1394,7 @@ cpdef floyd_warshall_shortest_paths(g, weight_function=None, distances=True, pre return pred -cpdef johnson_closeness_centrality(g, weight_function=None): +cpdef johnson_closeness_centrality(g, weight_function=None) noexcept: r""" Use Johnson algorithm to compute the closeness centrality of all vertices. @@ -1499,7 +1499,7 @@ cpdef johnson_closeness_centrality(g, weight_function=None): return {v: closeness[i] for i, v in enumerate(int_to_v) if closeness[i] != sys.float_info.max} -cpdef min_cycle_basis(g_sage, weight_function=None, by_weight=False): +cpdef min_cycle_basis(g_sage, weight_function=None, by_weight=False) noexcept: r""" Return a minimum weight cycle basis of the input graph ``g_sage``. @@ -1618,7 +1618,7 @@ cpdef min_cycle_basis(g_sage, weight_function=None, by_weight=False): return cycle_basis -cpdef eccentricity_DHV(g, vertex_list=None, weight_function=None, check_weight=True): +cpdef eccentricity_DHV(g, vertex_list=None, weight_function=None, check_weight=True) noexcept: r""" Return the vector of eccentricities using the algorithm of [Dragan2018]_. @@ -1806,7 +1806,7 @@ cpdef eccentricity_DHV(g, vertex_list=None, weight_function=None, check_weight=T return eccentricity -cpdef radius_DHV(g, weight_function=None, check_weight=True): +cpdef radius_DHV(g, weight_function=None, check_weight=True) noexcept: r""" Return the radius of weighted graph `g`. @@ -1943,7 +1943,7 @@ cpdef radius_DHV(g, weight_function=None, check_weight=True): return UB -cpdef diameter_DHV(g, weight_function=None, check_weight=True): +cpdef diameter_DHV(g, weight_function=None, check_weight=True) noexcept: r""" Return the diameter of weighted graph `g`. @@ -2116,7 +2116,7 @@ cpdef diameter_DHV(g, weight_function=None, check_weight=True): cdef tuple diameter_lower_bound_2Dsweep(BoostVecWeightedDiGraphU g_boost, BoostVecWeightedDiGraphU rev_g_boost, v_index source, - str algorithm): + str algorithm) noexcept: r""" Return a lower bound on the diameter of `G`. @@ -2477,7 +2477,7 @@ cdef double diameter_DiFUB(BoostVecWeightedDiGraphU g_boost, return LB cpdef diameter(G, algorithm=None, source=None, - weight_function=None, check_weight=True): + weight_function=None, check_weight=True) noexcept: r""" Return the diameter of `G`. @@ -2613,7 +2613,7 @@ cpdef diameter(G, algorithm=None, source=None, return LB cpdef shortest_paths_from_vertices(g, vertex_list=None, order=None, - weight_function=None, algorithm=None): + weight_function=None, algorithm=None) noexcept: r""" Compute the shortest paths to all vertices from each vertex in ``vertex_list``. @@ -2856,7 +2856,7 @@ cpdef shortest_paths_from_vertices(g, vertex_list=None, order=None, return distances, predecessors -cpdef wiener_index(g, algorithm=None, weight_function=None, check_weight=True): +cpdef wiener_index(g, algorithm=None, weight_function=None, check_weight=True) noexcept: r""" Return the Wiener index of the graph. diff --git a/src/sage/graphs/base/c_graph.pxd b/src/sage/graphs/base/c_graph.pxd index d5302e81cdd..1d5fb583eb5 100644 --- a/src/sage/graphs/base/c_graph.pxd +++ b/src/sage/graphs/base/c_graph.pxd @@ -21,13 +21,13 @@ cdef class CGraph: ################################### cpdef bint has_vertex(self, int n) except -1 - cpdef check_vertex(self, int n) - cpdef del_vertex(self, int v) - cpdef int current_allocation(self) - cpdef list verts(self) - cpdef add_vertices(self, verts) + cpdef check_vertex(self, int n) noexcept + cpdef del_vertex(self, int v) noexcept + cpdef int current_allocation(self) noexcept + cpdef list verts(self) noexcept + cpdef add_vertices(self, verts) noexcept cdef int del_vertex_unsafe(self, int) except -1 - cpdef realloc(self, int) + cpdef realloc(self, int) noexcept cdef int add_vertex_unsafe(self, int) except -1 ################################### @@ -42,9 +42,9 @@ cdef class CGraph: cdef int del_arc_unsafe(self, int, int) except -1 - cpdef add_arc(self, int u, int v) + cpdef add_arc(self, int u, int v) noexcept cpdef bint has_arc(self, int u, int v) except -1 - cpdef del_all_arcs(self, int u, int v) + cpdef del_all_arcs(self, int u, int v) noexcept ################################### # Labeled Edge Functions @@ -56,10 +56,10 @@ cdef class CGraph: cdef int arc_label_unsafe(self, int, int) except -1 cdef int all_arcs_unsafe(self, int, int, int *, int) except -1 - cpdef int arc_label(self, int u, int v) - cpdef list all_arcs(self, int u, int v) - cpdef del_arc_label(self, int u, int v, int l) - cpdef bint has_arc_label(self, int u, int v, int l) + cpdef int arc_label(self, int u, int v) noexcept + cpdef list all_arcs(self, int u, int v) noexcept + cpdef del_arc_label(self, int u, int v, int l) noexcept + cpdef bint has_arc_label(self, int u, int v, int l) noexcept ################################### # Neighbor Functions @@ -76,16 +76,16 @@ cdef class CGraph: cdef int next_out_neighbor_unsafe(self, int, int, int*) except -2 cdef int next_in_neighbor_unsafe(self, int, int, int*) except -2 - cdef adjacency_sequence_out(self, int n, int *vertices, int v, int* sequence) - cdef adjacency_sequence_in(self, int n, int *vertices, int v, int* sequence) - cpdef list in_neighbors(self, int v) - cpdef list out_neighbors(self, int u) + cdef adjacency_sequence_out(self, int n, int *vertices, int v, int* sequence) noexcept + cdef adjacency_sequence_in(self, int n, int *vertices, int v, int* sequence) noexcept + cpdef list in_neighbors(self, int v) noexcept + cpdef list out_neighbors(self, int u) noexcept cdef class CGraphBackend(GenericGraphBackend): cdef int get_vertex(self, u) except ? -2 cdef int get_vertex_checked(self, u) except ? -2 - cdef vertex_label(self, int u_int) + cdef vertex_label(self, int u_int) noexcept cdef int check_labelled_vertex(self, u, bint reverse) except ? -1 #cdef CGraph _cg # a child class should declare this accordingly cdef bint _directed @@ -94,12 +94,12 @@ cdef class CGraphBackend(GenericGraphBackend): cdef dict edge_labels cdef bint _loops cdef bint _multiple_edges - cdef CGraph cg(self) - cpdef add_edge(self, object u, object v, object l, bint directed) - cpdef del_edge(self, object u, object v, object l, bint directed) + cdef CGraph cg(self) noexcept + cpdef add_edge(self, object u, object v, object l, bint directed) noexcept + cpdef del_edge(self, object u, object v, object l, bint directed) noexcept cdef bint _has_labeled_edge_unsafe(self, int, int, object) except -1 - cdef bint _delete_edge_before_adding(self) + cdef bint _delete_edge_before_adding(self) noexcept cdef int new_edge_label(self, object l) except -1 cdef int free_edge_label(self, int l_int) except -1 cdef int _use_edge_iterator_on_subgraph(self, CGraphBackend other, object vertices, const int modus) except -1 - cdef list _all_edge_labels(self, int u, int v, uint32_t* edge=*) + cdef list _all_edge_labels(self, int u, int v, uint32_t* edge=*) noexcept diff --git a/src/sage/graphs/base/c_graph.pyx b/src/sage/graphs/base/c_graph.pyx index 79e62e13a33..7ca6c5dd124 100644 --- a/src/sage/graphs/base/c_graph.pyx +++ b/src/sage/graphs/base/c_graph.pyx @@ -126,7 +126,7 @@ cdef class CGraph: n < self.active_vertices.size and bitset_in(self.active_vertices, n)) - cpdef check_vertex(self, int n): + cpdef check_vertex(self, int n) noexcept: """ Check that ``n`` is a vertex of ``self``. @@ -333,7 +333,7 @@ cdef class CGraph: self.realloc(2 * self.active_vertices.size) return self.add_vertex_unsafe(k) - cpdef add_vertices(self, verts): + cpdef add_vertices(self, verts) noexcept: """ Add vertices from the iterable ``verts``. @@ -433,7 +433,7 @@ cdef class CGraph: self.num_verts -= 1 bitset_remove(self.active_vertices, v) - cpdef del_vertex(self, int v): + cpdef del_vertex(self, int v) noexcept: """ Delete the vertex ``v``, along with all edges incident to it. @@ -523,7 +523,7 @@ cdef class CGraph: if self.has_vertex(v): self.del_vertex_unsafe(v) - cpdef int current_allocation(self): + cpdef int current_allocation(self) noexcept: r""" Report the number of vertices allocated. @@ -581,7 +581,7 @@ cdef class CGraph: """ return self.active_vertices.size - cpdef list verts(self): + cpdef list verts(self) noexcept: """ Return a list of the vertices in ``self``. @@ -614,7 +614,7 @@ cdef class CGraph: """ return bitset_list(self.active_vertices) - cpdef realloc(self, int total): + cpdef realloc(self, int total) noexcept: """ Reallocate the number of vertices to use, without actually adding any. @@ -725,7 +725,7 @@ cdef class CGraph: cdef int del_arc_unsafe(self, int u, int v) except -1: raise NotImplementedError() - cpdef add_arc(self, int u, int v): + cpdef add_arc(self, int u, int v) noexcept: """ Add arc ``(u, v)`` to the graph. @@ -823,7 +823,7 @@ cdef class CGraph: return False return self.has_arc_unsafe(u, v) == 1 - cpdef del_all_arcs(self, int u, int v): + cpdef del_all_arcs(self, int u, int v) noexcept: """ Delete all arcs from ``u`` to ``v``. @@ -891,7 +891,7 @@ cdef class CGraph: cdef int all_arcs_unsafe(self, int u, int v, int* arc_labels, int size) except -1: raise NotImplementedError() - cpdef int arc_label(self, int u, int v): + cpdef int arc_label(self, int u, int v) noexcept: """ Retrieves the first label found associated with ``(u, v)``. @@ -933,7 +933,7 @@ cdef class CGraph: self.check_vertex(v) return self.arc_label_unsafe(u, v) - cpdef list all_arcs(self, int u, int v): + cpdef list all_arcs(self, int u, int v) noexcept: """ Gives the labels of all arcs ``(u, v)``. An unlabeled arc is interpreted as having label 0. @@ -973,7 +973,7 @@ cdef class CGraph: sig_free(arc_labels) return output - cpdef del_arc_label(self, int u, int v, int l): + cpdef del_arc_label(self, int u, int v, int l) noexcept: """ Delete an arc ``(u, v)`` with label ``l``. @@ -1006,7 +1006,7 @@ cdef class CGraph: raise ValueError("Label ({0}) must be a nonnegative integer.".format(l)) self.del_arc_label_unsafe(u, v, l) - cpdef bint has_arc_label(self, int u, int v, int l): + cpdef bint has_arc_label(self, int u, int v, int l) noexcept: """ Indicates whether there is an arc ``(u, v)`` with label ``l``. @@ -1124,7 +1124,7 @@ cdef class CGraph: cdef int next_in_neighbor_unsafe(self, int v, int u, int* l) except -2: raise NotImplementedError() - cdef adjacency_sequence_out(self, int n, int *vertices, int v, int* sequence): + cdef adjacency_sequence_out(self, int n, int *vertices, int v, int* sequence) noexcept: r""" Return the adjacency sequence corresponding to a list of vertices and a vertex. @@ -1164,7 +1164,7 @@ cdef class CGraph: for i in range(n): sequence[i] = self.has_arc_unsafe(v, vertices[i]) - cdef adjacency_sequence_in(self, int n, int *vertices, int v, int* sequence): + cdef adjacency_sequence_in(self, int n, int *vertices, int v, int* sequence) noexcept: r""" Compute the adjacency sequence corresponding to a list of vertices and a vertex. @@ -1203,7 +1203,7 @@ cdef class CGraph: for i in range(n): sequence[i] = self.has_arc_unsafe(vertices[i], v) - cpdef list out_neighbors(self, int u): + cpdef list out_neighbors(self, int u) noexcept: """ Return the list of out-neighbors of the vertex ``u``. @@ -1257,7 +1257,7 @@ cdef class CGraph: sig_free(neighbors) return output - cpdef list in_neighbors(self, int v): + cpdef list in_neighbors(self, int v) noexcept: """ Return the list of in-neighbors of the vertex ``v``. @@ -1375,7 +1375,7 @@ cdef class CGraphBackend(GenericGraphBackend): # Basic Access ################################### - cdef CGraph cg(self): + cdef CGraph cg(self) noexcept: r""" Return the attribute ``_cg`` casted into ``CGraph``. """ @@ -1553,7 +1553,7 @@ cdef class CGraphBackend(GenericGraphBackend): """ return self.cg().num_verts - cdef bint _delete_edge_before_adding(self): + cdef bint _delete_edge_before_adding(self) noexcept: """ Return whether we should delete edges before adding any. @@ -1631,7 +1631,7 @@ cdef class CGraphBackend(GenericGraphBackend): else: return -1 - cdef vertex_label(self, int u_int): + cdef vertex_label(self, int u_int) noexcept: """ Return the object represented by ``u_int``, or ``None`` if this does not represent a vertex. @@ -2357,7 +2357,7 @@ cdef class CGraphBackend(GenericGraphBackend): continue self.add_edge(u, v, l, directed) - cpdef add_edge(self, object u, object v, object l, bint directed): + cpdef add_edge(self, object u, object v, object l, bint directed) noexcept: """ Add the edge ``(u,v)`` to self. @@ -2489,7 +2489,7 @@ cdef class CGraphBackend(GenericGraphBackend): l = None self.del_edge(u, v, l, directed) - cpdef del_edge(self, object u, object v, object l, bint directed): + cpdef del_edge(self, object u, object v, object l, bint directed) noexcept: """ Delete edge ``(u, v, l)``. @@ -2607,7 +2607,7 @@ cdef class CGraphBackend(GenericGraphBackend): cdef int free_edge_label(self, int l_int) except -1: raise NotImplementedError() - cdef list _all_edge_labels(self, int u, int v, uint32_t* edge=NULL): + cdef list _all_edge_labels(self, int u, int v, uint32_t* edge=NULL) noexcept: """ Gives the labels of all arcs from ``u`` to ``v``. @@ -4885,7 +4885,7 @@ cdef class Search_iterator: """ return self - cdef inline next_breadth_first_search(self): + cdef inline next_breadth_first_search(self) noexcept: r""" Return the next vertex in a breadth first search traversal of a graph. @@ -4947,7 +4947,7 @@ cdef class Search_iterator: return value_prev, value return value - cdef inline next_depth_first_search(self): + cdef inline next_depth_first_search(self) noexcept: r""" Return the next vertex in a depth first search traversal of a graph. @@ -5009,7 +5009,7 @@ cdef class Search_iterator: # Functions to simplify edge iterator. ############################## -cdef inline bint _reorganize_edge(object v, object u, const int modus): +cdef inline bint _reorganize_edge(object v, object u, const int modus) noexcept: """ Return ``True`` if ``v`` and ``u`` should be exchanged according to the modus. diff --git a/src/sage/graphs/base/dense_graph.pxd b/src/sage/graphs/base/dense_graph.pxd index 839fa8ccba6..f5c194cec8a 100644 --- a/src/sage/graphs/base/dense_graph.pxd +++ b/src/sage/graphs/base/dense_graph.pxd @@ -21,5 +21,5 @@ cdef int copy_dense_graph(DenseGraph dest, DenseGraph src) except -1 cdef class DenseGraphBackend(CGraphBackend): cdef DenseGraph _cg - cdef inline CGraph cg(self): + cdef inline CGraph cg(self) noexcept: return self._cg diff --git a/src/sage/graphs/base/dense_graph.pyx b/src/sage/graphs/base/dense_graph.pyx index 9cb0a1676ae..db4a02a5a3f 100644 --- a/src/sage/graphs/base/dense_graph.pyx +++ b/src/sage/graphs/base/dense_graph.pyx @@ -195,7 +195,7 @@ cdef class DenseGraph(CGraph): sig_free(self.out_degrees) bitset_free(self.active_vertices) - cpdef realloc(self, int total_verts): + cpdef realloc(self, int total_verts) noexcept: """ Reallocate the number of vertices to use, without actually adding any. @@ -580,7 +580,7 @@ cdef class DenseGraphBackend(CGraphBackend): self.vertex_labels = {} self.vertex_ints = {} - cdef bint _delete_edge_before_adding(self): + cdef bint _delete_edge_before_adding(self) noexcept: """ Return whether we should delete edges before adding any. diff --git a/src/sage/graphs/base/sparse_graph.pxd b/src/sage/graphs/base/sparse_graph.pxd index 719ad0ef8c9..b925e9170ec 100644 --- a/src/sage/graphs/base/sparse_graph.pxd +++ b/src/sage/graphs/base/sparse_graph.pxd @@ -31,19 +31,19 @@ cdef class SparseGraph(CGraph): cdef SparseGraphBTNode **vertices cdef SparseGraphBTNode **vertices_rev cdef bint _directed - cpdef bint is_directed(self) + cpdef bint is_directed(self) noexcept cdef int _del_arc_unsafe(self, int, int, SparseGraphBTNode **) except -1 cdef int _add_arc_label_unsafe(self, int, int, int, SparseGraphBTNode **) except -1 - cdef int _del_arc_label_unsafe(self, int, int, int, SparseGraphBTNode **) - cdef SparseGraphLLNode* arc_labels_unsafe(self, int u, int v) - cpdef int out_degree(self, int u) - cpdef int in_degree(self, int u) + cdef int _del_arc_label_unsafe(self, int, int, int, SparseGraphBTNode **) noexcept + cdef SparseGraphLLNode* arc_labels_unsafe(self, int u, int v) noexcept + cpdef int out_degree(self, int u) noexcept + cpdef int in_degree(self, int u) noexcept - cdef int out_neighbors_BTNode_unsafe(self, int u, SparseGraphBTNode *** p_pointers) - cdef int in_neighbors_BTNode_unsafe(self, int u, SparseGraphBTNode *** p_pointers) + cdef int out_neighbors_BTNode_unsafe(self, int u, SparseGraphBTNode *** p_pointers) noexcept + cdef int in_neighbors_BTNode_unsafe(self, int u, SparseGraphBTNode *** p_pointers) noexcept - cdef inline SparseGraphBTNode* next_out_neighbor_BTNode_unsafe(self, int u, int v): + cdef inline SparseGraphBTNode* next_out_neighbor_BTNode_unsafe(self, int u, int v) noexcept: """ Return the next out-neighbor of ``u`` that is greater than ``v``. @@ -53,7 +53,7 @@ cdef class SparseGraph(CGraph): """ return self.next_neighbor_BTNode_unsafe(self.vertices, u, v) - cdef inline SparseGraphBTNode* next_in_neighbor_BTNode_unsafe(self, int v, int u): + cdef inline SparseGraphBTNode* next_in_neighbor_BTNode_unsafe(self, int v, int u) noexcept: """ Return the next in-neighbor of ``v`` that is greater than ``u``. @@ -63,12 +63,12 @@ cdef class SparseGraph(CGraph): """ return self.next_neighbor_BTNode_unsafe(self.vertices_rev, v, u) - cdef inline SparseGraphBTNode* next_neighbor_BTNode_unsafe(self, SparseGraphBTNode** vertices, int u, int v) + cdef inline SparseGraphBTNode* next_neighbor_BTNode_unsafe(self, SparseGraphBTNode** vertices, int u, int v) noexcept cdef class SparseGraphBackend(CGraphBackend): cdef int edge_labels_max cdef list edge_labels_available_ids cdef SparseGraph _cg - cdef inline CGraph cg(self): + cdef inline CGraph cg(self) noexcept: return self._cg diff --git a/src/sage/graphs/base/sparse_graph.pyx b/src/sage/graphs/base/sparse_graph.pyx index 714da06e519..e512832d958 100644 --- a/src/sage/graphs/base/sparse_graph.pyx +++ b/src/sage/graphs/base/sparse_graph.pyx @@ -207,7 +207,7 @@ cdef enum: # or three nodes. -cdef inline int compare(int a, int b): +cdef inline int compare(int a, int b) noexcept: # Here we rely on the fact that C performs arithmetic on unsigned # ints modulo 2^wordsize. cdef unsigned int aa = a, bb = b # signed ints lead to badness like a>b>c>a... @@ -370,7 +370,7 @@ cdef class SparseGraph(CGraph): sig_free(self.out_degrees) bitset_free(self.active_vertices) - cpdef realloc(self, int total): + cpdef realloc(self, int total) noexcept: """ Reallocate the number of vertices to use, without actually adding any. @@ -459,7 +459,7 @@ cdef class SparseGraph(CGraph): # self.active_vertices bitset_realloc(self.active_vertices, s_total) - cpdef inline bint is_directed(self): + cpdef inline bint is_directed(self) noexcept: r""" Return whether the graph is directed. @@ -610,7 +610,7 @@ cdef class SparseGraph(CGraph): # Neighbor functions ################################### - cdef int out_neighbors_BTNode_unsafe(self, int u, SparseGraphBTNode *** p_pointers): + cdef int out_neighbors_BTNode_unsafe(self, int u, SparseGraphBTNode *** p_pointers) noexcept: """ List the out-neighbors of a vertex as BTNodes @@ -667,7 +667,7 @@ cdef class SparseGraph(CGraph): else: return -1 - cdef inline SparseGraphBTNode* next_neighbor_BTNode_unsafe(self, SparseGraphBTNode** vertices, int u, int v): + cdef inline SparseGraphBTNode* next_neighbor_BTNode_unsafe(self, SparseGraphBTNode** vertices, int u, int v) noexcept: """ Return the next neighbor of ``u`` that is greater than ``v``. @@ -710,7 +710,7 @@ cdef class SparseGraph(CGraph): return temp return NULL - cpdef int out_degree(self, int u): + cpdef int out_degree(self, int u) noexcept: """ Returns the out-degree of ``v`` @@ -732,7 +732,7 @@ cdef class SparseGraph(CGraph): """ return self.out_degrees[u] - cdef int in_neighbors_BTNode_unsafe(self, int v, SparseGraphBTNode *** p_pointers): + cdef int in_neighbors_BTNode_unsafe(self, int v, SparseGraphBTNode *** p_pointers) noexcept: """ List the in-neighbors of a vertex as BTNodes @@ -789,7 +789,7 @@ cdef class SparseGraph(CGraph): else: return -1 - cpdef int in_degree(self, int v): + cpdef int in_degree(self, int v) noexcept: """ Returns the in-degree of ``v`` @@ -995,7 +995,7 @@ cdef class SparseGraph(CGraph): return -1 return num_arcs - cdef SparseGraphLLNode* arc_labels_unsafe(self, int u, int v): + cdef SparseGraphLLNode* arc_labels_unsafe(self, int u, int v) noexcept: """ Return the first label of arcs (u, v) or ``NULL`` if there are none. @@ -1024,7 +1024,7 @@ cdef class SparseGraph(CGraph): return NULL return temp.labels - cdef inline int _del_arc_label_unsafe(self, int u, int v, int l, SparseGraphBTNode **parent): + cdef inline int _del_arc_label_unsafe(self, int u, int v, int l, SparseGraphBTNode **parent) noexcept: """ .. WARNING:: diff --git a/src/sage/graphs/base/static_dense_graph.pxd b/src/sage/graphs/base/static_dense_graph.pxd index 0e580a02b57..d1c2a0aa3f9 100644 --- a/src/sage/graphs/base/static_dense_graph.pxd +++ b/src/sage/graphs/base/static_dense_graph.pxd @@ -1,4 +1,4 @@ from sage.data_structures.binary_matrix cimport binary_matrix_t from libc.stdint cimport uint32_t, uint64_t -cdef dict dense_graph_init(binary_matrix_t m, g, translation = ?, force_undirected = ?) +cdef dict dense_graph_init(binary_matrix_t m, g, translation = ?, force_undirected = ?) noexcept diff --git a/src/sage/graphs/base/static_dense_graph.pyx b/src/sage/graphs/base/static_dense_graph.pyx index 78711fae2f1..9d8732b2f83 100644 --- a/src/sage/graphs/base/static_dense_graph.pyx +++ b/src/sage/graphs/base/static_dense_graph.pyx @@ -54,7 +54,7 @@ from itertools import product from sage.misc.flatten import flatten -cdef dict dense_graph_init(binary_matrix_t m, g, translation=None, force_undirected=False): +cdef dict dense_graph_init(binary_matrix_t m, g, translation=None, force_undirected=False) noexcept: r""" Fill a binary matrix with the information from a Sage (di)graph. diff --git a/src/sage/graphs/base/static_sparse_backend.pxd b/src/sage/graphs/base/static_sparse_backend.pxd index 1bffe2b3be2..db62534cb09 100644 --- a/src/sage/graphs/base/static_sparse_backend.pxd +++ b/src/sage/graphs/base/static_sparse_backend.pxd @@ -18,6 +18,6 @@ cdef class StaticSparseBackend(CGraphBackend): cdef list _vertex_to_labels cdef dict _vertex_to_int cdef StaticSparseCGraph _cg - cdef inline CGraph cg(self): + cdef inline CGraph cg(self) noexcept: return self._cg cdef int _use_edge_iterator_on_subgraph(self, CGraphBackend other, object vertices, const int modus) except -1 diff --git a/src/sage/graphs/base/static_sparse_backend.pyx b/src/sage/graphs/base/static_sparse_backend.pyx index 2eecc1a69d0..ae76a399240 100644 --- a/src/sage/graphs/base/static_sparse_backend.pyx +++ b/src/sage/graphs/base/static_sparse_backend.pyx @@ -196,7 +196,7 @@ cdef class StaticSparseCGraph(CGraph): """ self.add_vertex_unsafe(k) - cpdef del_vertex(self, int k): + cpdef del_vertex(self, int k) noexcept: r""" Remove a vertex from the graph. No way. @@ -211,7 +211,7 @@ cdef class StaticSparseCGraph(CGraph): """ self.del_vertex_unsafe(k) - cpdef list verts(self): + cpdef list verts(self) noexcept: r""" Returns the list of vertices @@ -318,7 +318,7 @@ cdef class StaticSparseCGraph(CGraph): neighbors[i] = self.g_rev.neighbors[u][i] return -1 if size < degree else degree - cpdef list out_neighbors(self, int u): + cpdef list out_neighbors(self, int u) noexcept: r""" List the out-neighbors of a vertex @@ -343,7 +343,7 @@ cdef class StaticSparseCGraph(CGraph): cdef int i return [ self.g.neighbors[u][i] for i in range(out_degree(self.g, u))] - cpdef list in_neighbors(self, int u): + cpdef list in_neighbors(self, int u) noexcept: r""" Return the in-neighbors of a vertex @@ -556,7 +556,7 @@ cdef class StaticSparseBackend(CGraphBackend): """ return v in self._vertex_to_int - cpdef add_edge(self, object u, object v, object l, bint directed): + cpdef add_edge(self, object u, object v, object l, bint directed) noexcept: r""" Set edge label. No way. @@ -601,7 +601,7 @@ cdef class StaticSparseBackend(CGraphBackend): """ raise ValueError("graph is immutable; please change a copy instead (use function copy())") - cpdef del_edge(self, object u, object v, object l, bint directed): + cpdef del_edge(self, object u, object v, object l, bint directed) noexcept: r""" Set edge label. No way. @@ -698,7 +698,7 @@ cdef class StaticSparseBackend(CGraphBackend): return self._all_edge_labels(u, v, edge) return edge_label(cg.g, edge) - cdef inline list _all_edge_labels(self, int u, int v, uint32_t* edge=NULL): + cdef inline list _all_edge_labels(self, int u, int v, uint32_t* edge=NULL) noexcept: """ Gives the labels of all arcs from ``u`` to ``v``. diff --git a/src/sage/graphs/base/static_sparse_graph.pxd b/src/sage/graphs/base/static_sparse_graph.pxd index b7d6be3a823..b5cd2d73009 100644 --- a/src/sage/graphs/base/static_sparse_graph.pxd +++ b/src/sage/graphs/base/static_sparse_graph.pxd @@ -23,17 +23,17 @@ ctypedef struct short_digraph_s: ctypedef short_digraph_s short_digraph[1] cdef int init_short_digraph(short_digraph g, G, edge_labelled=?, vertex_list=?) except -1 -cdef void free_short_digraph(short_digraph g) +cdef void free_short_digraph(short_digraph g) noexcept cdef int init_reverse(short_digraph dst, short_digraph src) except -1 -cdef int out_degree(short_digraph g, int u) -cdef uint32_t * has_edge(short_digraph g, int u, int v) -cdef object edge_label(short_digraph g, uint32_t * edge) -cdef int tarjan_strongly_connected_components_C(short_digraph g, int *scc) -cdef void strongly_connected_components_digraph_C(short_digraph g, int nscc, int *scc, short_digraph output) +cdef int out_degree(short_digraph g, int u) noexcept +cdef uint32_t * has_edge(short_digraph g, int u, int v) noexcept +cdef object edge_label(short_digraph g, uint32_t * edge) noexcept +cdef int tarjan_strongly_connected_components_C(short_digraph g, int *scc) noexcept +cdef void strongly_connected_components_digraph_C(short_digraph g, int nscc, int *scc, short_digraph output) noexcept cdef uint32_t simple_BFS(short_digraph g, uint32_t source, uint32_t *distances, uint32_t *predecessors, uint32_t *waiting_list, - bitset_t seen) + bitset_t seen) noexcept diff --git a/src/sage/graphs/base/static_sparse_graph.pyx b/src/sage/graphs/base/static_sparse_graph.pyx index 4b98ff027a3..90e47b6e069 100644 --- a/src/sage/graphs/base/static_sparse_graph.pyx +++ b/src/sage/graphs/base/static_sparse_graph.pyx @@ -310,7 +310,7 @@ cdef int init_short_digraph(short_digraph g, G, edge_labelled=False, vertex_list cpython.Py_XINCREF(g.edge_labels) -cdef inline int n_edges(short_digraph g): +cdef inline int n_edges(short_digraph g) noexcept: """ Return the number of edges in ``g``. @@ -319,7 +319,7 @@ cdef inline int n_edges(short_digraph g): return (g.neighbors[g.n] - g.edges) -cdef inline int out_degree(short_digraph g, int i): +cdef inline int out_degree(short_digraph g, int i) noexcept: """ Return the out-degree of vertex `i` in ``g``. @@ -402,14 +402,14 @@ cdef int init_reverse(short_digraph dst, short_digraph src) except -1: return 0 -cdef int compare_uint32_p(const_void *a, const_void *b): +cdef int compare_uint32_p(const_void *a, const_void *b) noexcept: """ Comparison function needed for ``bsearch``. """ return ( a)[0] - ( b)[0] -cdef inline uint32_t * has_edge(short_digraph g, int u, int v): +cdef inline uint32_t * has_edge(short_digraph g, int u, int v) noexcept: r""" Test the existence of an edge. @@ -418,7 +418,7 @@ cdef inline uint32_t * has_edge(short_digraph g, int u, int v): return bsearch(&v, g.neighbors[u], g.neighbors[u + 1] - g.neighbors[u], sizeof(uint32_t), compare_uint32_p) -cdef inline object edge_label(short_digraph g, uint32_t * edge): +cdef inline object edge_label(short_digraph g, uint32_t * edge) noexcept: r""" Return the label associated with a given edge """ @@ -433,7 +433,7 @@ cdef uint32_t simple_BFS(short_digraph g, uint32_t *distances, uint32_t *predecessors, uint32_t *waiting_list, - bitset_t seen): + bitset_t seen) noexcept: """ Perform a breadth first search (BFS) using the same method as in sage.graphs.distances_all_pairs.all_pairs_shortest_path_BFS @@ -565,7 +565,7 @@ cdef int can_be_reached_from(short_digraph g, int src, bitset_t reached) except sig_free(stack) -cdef int tarjan_strongly_connected_components_C(short_digraph g, int *scc): +cdef int tarjan_strongly_connected_components_C(short_digraph g, int *scc) noexcept: r""" The Tarjan algorithm to compute strongly connected components (SCCs). @@ -765,7 +765,7 @@ def tarjan_strongly_connected_components(G): return output -cdef void strongly_connected_components_digraph_C(short_digraph g, int nscc, int *scc, short_digraph output): +cdef void strongly_connected_components_digraph_C(short_digraph g, int nscc, int *scc, short_digraph output) noexcept: r""" Compute the strongly connected components (SCCs) digraph of `g`. @@ -889,7 +889,7 @@ def strongly_connected_components_digraph(G): return output, {v: scc[i] for i, v in enumerate(int_to_vertex)} -cdef strongly_connected_component_containing_vertex(short_digraph g, short_digraph g_reversed, int v, bitset_t scc): +cdef strongly_connected_component_containing_vertex(short_digraph g, short_digraph g_reversed, int v, bitset_t scc) noexcept: """ Feed ``scc`` with the vertices in the strongly connected component of ``v``. """ @@ -903,7 +903,7 @@ cdef strongly_connected_component_containing_vertex(short_digraph g, short_digra bitset_intersection(scc, scc, scc_reversed) -cdef void free_short_digraph(short_digraph g): +cdef void free_short_digraph(short_digraph g) noexcept: """ Free the resources used by ``g`` """ diff --git a/src/sage/graphs/bliss.pyx b/src/sage/graphs/bliss.pyx index 0a1b5ea313f..40a576a99cb 100644 --- a/src/sage/graphs/bliss.pyx +++ b/src/sage/graphs/bliss.pyx @@ -65,7 +65,7 @@ cdef extern from "bliss_cpp/bliss_find_automorphisms.h": void bliss_find_automorphisms(Graph*, void (*)(void*, unsigned int, const unsigned int*), void*, Stats&) void bliss_find_automorphisms(Digraph*, void (*)(void*, unsigned int, const unsigned int*), void*, Stats&) -cdef int encoding_numbits(int n): +cdef int encoding_numbits(int n) noexcept: r""" Return the number of bits needed to encode the `n` numbers from `1` to `n`. In other words, the last bit set in `n`. @@ -79,7 +79,7 @@ cdef int encoding_numbits(int n): return i -cdef void add_gen(void *user_param, unsigned int n, const unsigned int *aut): +cdef void add_gen(void *user_param, unsigned int n, const unsigned int *aut) noexcept: r""" Function called each time a new generator of the automorphism group is found. @@ -129,7 +129,7 @@ cdef void add_gen(void *user_param, unsigned int n, const unsigned int *aut): # constructing bliss graphs from edge lists ##################################################### -cdef Graph *bliss_graph_from_labelled_edges(int Vnr, int Lnr, Vout, Vin, labels, partition): +cdef Graph *bliss_graph_from_labelled_edges(int Vnr, int Lnr, Vout, Vin, labels, partition) noexcept: r""" Return a bliss graph from the input data @@ -220,7 +220,7 @@ cdef Graph *bliss_graph_from_labelled_edges(int Vnr, int Lnr, Vout, Vin, labels, return g -cdef Digraph *bliss_digraph_from_labelled_edges(int Vnr, int Lnr, Vout, Vin, labels, partition): +cdef Digraph *bliss_digraph_from_labelled_edges(int Vnr, int Lnr, Vout, Vin, labels, partition) noexcept: r""" Return a bliss digraph from the input data @@ -301,7 +301,7 @@ cdef Digraph *bliss_digraph_from_labelled_edges(int Vnr, int Lnr, Vout, Vin, lab ##################################################### cdef canonical_form_from_edge_list(int Vnr, list Vout, list Vin, int Lnr=1, list labels=[], - list partition=None, bint directed=False, bint certificate=False): + list partition=None, bint directed=False, bint certificate=False) noexcept: r""" Return an unsorted list of labelled edges of a canonical form. @@ -378,7 +378,7 @@ cdef canonical_form_from_edge_list(int Vnr, list Vout, list Vin, int Lnr=1, list return new_edges -cpdef canonical_form(G, partition=None, return_graph=False, use_edge_labels=True, certificate=False): +cpdef canonical_form(G, partition=None, return_graph=False, use_edge_labels=True, certificate=False) noexcept: r""" Return a canonical label for the given (di)graph. @@ -599,7 +599,7 @@ cpdef canonical_form(G, partition=None, return_graph=False, use_edge_labels=True ##################################################### cdef automorphism_group_gens_from_edge_list(int Vnr, Vout, Vin, int Lnr=1, labels=[], - int2vert=[], partition=None, bint directed=False): + int2vert=[], partition=None, bint directed=False) noexcept: r""" Return an unsorted list of labelled edges of a canonical form. @@ -650,7 +650,7 @@ cdef automorphism_group_gens_from_edge_list(int Vnr, Vout, Vin, int Lnr=1, label return [[cyc for cyc in gen if cyc[0] is not None] for gen in gens] -cpdef automorphism_group(G, partition=None, use_edge_labels=True): +cpdef automorphism_group(G, partition=None, use_edge_labels=True) noexcept: """ Return the automorphism group of the given (di)graph. @@ -848,7 +848,7 @@ cpdef automorphism_group(G, partition=None, use_edge_labels=True): # old direct interactions graphs <-> bliss graphs ##################################################### -cdef Graph *bliss_graph(G, partition, vert2int, int2vert): +cdef Graph *bliss_graph(G, partition, vert2int, int2vert) noexcept: r""" Return a bliss copy of a graph G @@ -882,7 +882,7 @@ cdef Graph *bliss_graph(G, partition, vert2int, int2vert): return g -cdef Digraph *bliss_digraph(G, partition, vert2int, int2vert): +cdef Digraph *bliss_digraph(G, partition, vert2int, int2vert) noexcept: r""" Return a bliss copy of a digraph G diff --git a/src/sage/graphs/centrality.pyx b/src/sage/graphs/centrality.pyx index 161f3f710e2..2fa2d4d303e 100755 --- a/src/sage/graphs/centrality.pyx +++ b/src/sage/graphs/centrality.pyx @@ -123,7 +123,7 @@ def centrality_betweenness(G, bint exact=False, bint normalize=True): @cython.cdivision(True) -cdef dict centrality_betweenness_C(G, numerical_type _, bint normalize=True): +cdef dict centrality_betweenness_C(G, numerical_type _, bint normalize=True) noexcept: r""" Return the centrality betweenness of G (C implementation) @@ -327,7 +327,7 @@ cdef dict centrality_betweenness_C(G, numerical_type _, bint normalize=True): return {vv: betweenness_list[i] for i, vv in enumerate(int_to_vertex)} -cdef void _estimate_reachable_vertices_dir(short_digraph g, int* reachL, int* reachU): +cdef void _estimate_reachable_vertices_dir(short_digraph g, int* reachL, int* reachU) noexcept: r""" For each vertex ``v``, bounds the number of vertices reachable from ``v``. @@ -460,7 +460,7 @@ cdef void _estimate_reachable_vertices_dir(short_digraph g, int* reachL, int* re reachU[i] = min(reachU_scc[scc[i]], g.n) -cdef void _compute_reachable_vertices_undir(short_digraph g, int* reachable): +cdef void _compute_reachable_vertices_undir(short_digraph g, int* reachable) noexcept: r""" For each vertex ``v``, compute the number of vertices reachable from ``v``. @@ -513,7 +513,7 @@ cdef void _compute_reachable_vertices_undir(short_digraph g, int* reachable): reachable[v] = len(currentcc) -cdef void _sort_vertices_degree(short_digraph g, int* sorted_verts): +cdef void _sort_vertices_degree(short_digraph g, int* sorted_verts) noexcept: r""" Sort vertices in decreasing order of degree. diff --git a/src/sage/graphs/connectivity.pxd b/src/sage/graphs/connectivity.pxd index 36898d75e76..329d2d29dad 100644 --- a/src/sage/graphs/connectivity.pxd +++ b/src/sage/graphs/connectivity.pxd @@ -16,9 +16,9 @@ cdef class _Component: cdef _LinkedList * edge_list cdef int component_type - cdef add_edge(self, Py_ssize_t e_index) - cdef finish_tric_or_poly(self, Py_ssize_t e_index) - cdef list get_edge_list(self) + cdef add_edge(self, Py_ssize_t e_index) noexcept + cdef finish_tric_or_poly(self, Py_ssize_t e_index) noexcept + cdef list get_edge_list(self) noexcept cdef class TriconnectivitySPQR: cdef MemoryAllocator mem @@ -88,7 +88,7 @@ cdef class TriconnectivitySPQR: ### Methods ### - cdef inline __tstack_push(self, int h, int a, int b): + cdef inline __tstack_push(self, int h, int a, int b) noexcept: """ Push ``(h, a, b)`` triple on ``Tstack``. """ @@ -97,26 +97,26 @@ cdef class TriconnectivitySPQR: self.t_stack_a[self.t_stack_top] = a self.t_stack_b[self.t_stack_top] = b - cdef inline __tstack_push_eos(self): + cdef inline __tstack_push_eos(self) noexcept: """ Push end-of-stack marker on ``Tstack``. """ self.t_stack_top += 1 self.t_stack_a[self.t_stack_top] = -1 - cdef inline bint __tstack_not_eos(self): + cdef inline bint __tstack_not_eos(self) noexcept: """ Return ``True`` iff end-of-stack marker is not on top of ``Tstack``. """ return self.t_stack_a[self.t_stack_top] != -1 - cdef inline int __estack_pop(self): + cdef inline int __estack_pop(self) noexcept: """ Pop from estack and return the popped element """ return self.e_stack.pop() - cdef inline __new_component(self, list edges, int type_c): + cdef inline __new_component(self, list edges, int type_c) noexcept: """ Create a new component and add ``edges`` to it. @@ -124,7 +124,7 @@ cdef class TriconnectivitySPQR: """ self.components_list.append(_Component(edges, type_c)) - cdef inline bint __is_virtual_edge(self, int e_index): + cdef inline bint __is_virtual_edge(self, int e_index) noexcept: """ Return ``True`` if edge number ``e_index`` is a virtual edge. @@ -134,7 +134,7 @@ cdef class TriconnectivitySPQR: """ return e_index >= self.m - cdef inline int __edge_other_extremity(self, int e_index, int u): + cdef inline int __edge_other_extremity(self, int e_index, int u) noexcept: """ Return the other extremity of the edge """ @@ -143,16 +143,16 @@ cdef class TriconnectivitySPQR: return self.edge_extremity_first[e_index] - cdef int __new_virtual_edge(self, int u, int v) - cdef _LinkedListNode * __new_LinkedListNode(self, Py_ssize_t e_index) - cdef Py_ssize_t __high(self, Py_ssize_t v) - cdef __del_high(self, int e_index) - cdef __split_multiple_edges(self) - cdef int __dfs1(self, int start, bint check=*) - cdef __build_acceptable_adj_struct(self) - cdef __path_finder(self, int start) - cdef __dfs2(self) + cdef int __new_virtual_edge(self, int u, int v) noexcept + cdef _LinkedListNode * __new_LinkedListNode(self, Py_ssize_t e_index) noexcept + cdef Py_ssize_t __high(self, Py_ssize_t v) noexcept + cdef __del_high(self, int e_index) noexcept + cdef __split_multiple_edges(self) noexcept + cdef int __dfs1(self, int start, bint check=*) noexcept + cdef __build_acceptable_adj_struct(self) noexcept + cdef __path_finder(self, int start) noexcept + cdef __dfs2(self) noexcept cdef int __path_search(self, int start) except -1 - cdef __assemble_triconnected_components(self) - cdef __build_spqr_tree(self) + cdef __assemble_triconnected_components(self) noexcept + cdef __build_spqr_tree(self) noexcept diff --git a/src/sage/graphs/connectivity.pyx b/src/sage/graphs/connectivity.pyx index 5a206221da9..8880d1f2b75 100644 --- a/src/sage/graphs/connectivity.pyx +++ b/src/sage/graphs/connectivity.pyx @@ -2674,7 +2674,7 @@ def spqr_tree_to_graph(T): # Helper methods for ``TriconnectivitySPQR``. # Define a doubly linked list -cdef inline _LinkedListNode_initialize(_LinkedListNode * node, Py_ssize_t data): +cdef inline _LinkedListNode_initialize(_LinkedListNode * node, Py_ssize_t data) noexcept: """ Initialize the ``_LinkedListNode`` with value data. """ @@ -2683,7 +2683,7 @@ cdef inline _LinkedListNode_initialize(_LinkedListNode * node, Py_ssize_t data): node.data = data -cdef inline _LinkedList_initialize(_LinkedList * ll): +cdef inline _LinkedList_initialize(_LinkedList * ll) noexcept: """ Initialize the ``_LinkedList``. """ @@ -2691,7 +2691,7 @@ cdef inline _LinkedList_initialize(_LinkedList * ll): ll.tail = NULL ll.length = 0 -cdef _LinkedList_set_head(_LinkedList * ll, _LinkedListNode * h): +cdef _LinkedList_set_head(_LinkedList * ll, _LinkedListNode * h) noexcept: """ Set the node ``h`` as the head and tail of the linked list ``ll``. """ @@ -2699,19 +2699,19 @@ cdef _LinkedList_set_head(_LinkedList * ll, _LinkedListNode * h): ll.tail = h ll.length = 1 -cdef inline _LinkedListNode * _LinkedList_get_head(_LinkedList * ll): +cdef inline _LinkedListNode * _LinkedList_get_head(_LinkedList * ll) noexcept: """ Return the head of the linked list ``ll``. """ return ll.head -cdef inline Py_ssize_t _LinkedList_get_length(_LinkedList * ll): +cdef inline Py_ssize_t _LinkedList_get_length(_LinkedList * ll) noexcept: """ Return the length of the linked list ``ll``. """ return ll.length -cdef _LinkedList_append(_LinkedList * ll, _LinkedListNode * node): +cdef _LinkedList_append(_LinkedList * ll, _LinkedListNode * node) noexcept: """ Append the node ``node`` to the linked list ``ll``. """ @@ -2723,7 +2723,7 @@ cdef _LinkedList_append(_LinkedList * ll, _LinkedListNode * node): ll.tail = node ll.length += 1 -cdef _LinkedList_remove(_LinkedList * ll, _LinkedListNode * node): +cdef _LinkedList_remove(_LinkedList * ll, _LinkedListNode * node) noexcept: """ Remove the node ``node`` from the linked list ``ll``. """ @@ -2741,7 +2741,7 @@ cdef _LinkedList_remove(_LinkedList * ll, _LinkedListNode * node): node.next.prev = node.prev ll.length -= 1 -cdef _LinkedList_push_front(_LinkedList * ll, _LinkedListNode * node): +cdef _LinkedList_push_front(_LinkedList * ll, _LinkedListNode * node) noexcept: """ Add node ``node`` to the beginning of the linked list ``ll``. """ @@ -2753,7 +2753,7 @@ cdef _LinkedList_push_front(_LinkedList * ll, _LinkedListNode * node): ll.head = node ll.length += 1 -cdef _LinkedList_concatenate(_LinkedList * lst1, _LinkedList * lst2): +cdef _LinkedList_concatenate(_LinkedList * lst1, _LinkedList * lst2) noexcept: """ Concatenate lst2 to lst1. @@ -2766,7 +2766,7 @@ cdef _LinkedList_concatenate(_LinkedList * lst1, _LinkedList * lst2): lst2.head = NULL lst2.length = 0 -cdef str _LinkedList_to_string(_LinkedList * ll): +cdef str _LinkedList_to_string(_LinkedList * ll) noexcept: """ Return a string representation of self. """ @@ -2825,7 +2825,7 @@ cdef class _Component: self.add_edge(e_index) self.component_type = type_c - cdef add_edge(self, Py_ssize_t e_index): + cdef add_edge(self, Py_ssize_t e_index) noexcept: """ Add edge index ``e_index`` to the component. """ @@ -2833,7 +2833,7 @@ cdef class _Component: _LinkedListNode_initialize(node, e_index) _LinkedList_append(self.edge_list, node) - cdef finish_tric_or_poly(self, Py_ssize_t e_index): + cdef finish_tric_or_poly(self, Py_ssize_t e_index) noexcept: r""" Finalize the component by adding edge ``e``. @@ -2871,7 +2871,7 @@ cdef class _Component: type_str = "Triconnected: " return type_str + _LinkedList_to_string(self.edge_list) - cdef list get_edge_list(self): + cdef list get_edge_list(self) noexcept: """ Return the list of edges belonging to the component. """ @@ -3269,7 +3269,7 @@ cdef class TriconnectivitySPQR: self.__build_spqr_tree() - cdef int __new_virtual_edge(self, int u, int v): + cdef int __new_virtual_edge(self, int u, int v) noexcept: """ Return a new virtual edge between ``u`` and ``v``. """ @@ -3281,7 +3281,7 @@ cdef class TriconnectivitySPQR: self.edge_status[e_index] = 0 return e_index - cdef _LinkedListNode * __new_LinkedListNode(self, Py_ssize_t e_index): + cdef _LinkedListNode * __new_LinkedListNode(self, Py_ssize_t e_index) noexcept: """ Create a new ``_LinkedListNode`` initialized with value ``e_index``. """ @@ -3289,7 +3289,7 @@ cdef class TriconnectivitySPQR: _LinkedListNode_initialize(node, e_index) return node - cdef Py_ssize_t __high(self, Py_ssize_t v): + cdef Py_ssize_t __high(self, Py_ssize_t v) noexcept: """ Return the ``high(v)`` value, which is the first value in ``highpt`` list of ``v``. @@ -3299,7 +3299,7 @@ cdef class TriconnectivitySPQR: return head.data return 0 - cdef __del_high(self, int e_index): + cdef __del_high(self, int e_index) noexcept: """ Delete edge ``e`` from the ``highpt`` list of the endpoint ``v`` it belongs to. @@ -3313,7 +3313,7 @@ cdef class TriconnectivitySPQR: v = self.edge_extremity_second[e_index] _LinkedList_remove(self.highpt[v], it) - cdef __split_multiple_edges(self): + cdef __split_multiple_edges(self) noexcept: """ Make the graph simple and build bonds recording multiple edges. @@ -3362,7 +3362,7 @@ cdef class TriconnectivitySPQR: sb.append(virtual_e_index) self.__new_component(sb, 0) - cdef int __dfs1(self, int start, bint check=True): + cdef int __dfs1(self, int start, bint check=True) noexcept: """ Build the palm-tree of the graph using a dfs traversal. @@ -3485,7 +3485,7 @@ cdef class TriconnectivitySPQR: return cut_vertex # cut_vertex is -1 if graph does not have a cut vertex - cdef __build_acceptable_adj_struct(self): + cdef __build_acceptable_adj_struct(self) noexcept: """ Build the adjacency lists for each vertex with certain properties of the ordering, using the ``lowpt1`` and ``lowpt2`` values. @@ -3540,7 +3540,7 @@ cdef class TriconnectivitySPQR: _LinkedList_append(self.adj[self.edge_extremity_first[e_index]], node) self.in_adj[e_index] = node - cdef __path_finder(self, int start): + cdef __path_finder(self, int start) noexcept: """ This function is a helper function for :meth:`__dfs2` function. @@ -3599,7 +3599,7 @@ cdef class TriconnectivitySPQR: self.dfs_counter -= 1 stack_top -= 1 - cdef __dfs2(self): + cdef __dfs2(self) noexcept: """ Update the values of ``lowpt1`` and ``lowpt2`` lists with the help of new numbering obtained from :meth:`__path_finder`. @@ -3982,7 +3982,7 @@ cdef class TriconnectivitySPQR: # Go to next edge in adjacency list e_node_dict[v] = e_node.next - cdef __assemble_triconnected_components(self): + cdef __assemble_triconnected_components(self) noexcept: """ Iterate through all the split components built by :meth:`__path_finder` and merges two bonds or two polygons that share an edge for constructing @@ -4109,7 +4109,7 @@ cdef class TriconnectivitySPQR: self.comp_type.append((<_Component> comp).component_type) self.comp_final_edge_list.append(e_list_new) - cdef __build_spqr_tree(self): + cdef __build_spqr_tree(self) noexcept: """ Build the SPQR-tree of the graph and store it in variable ``self.spqr_tree``. See diff --git a/src/sage/graphs/convexity_properties.pxd b/src/sage/graphs/convexity_properties.pxd index f6c1b68b6b8..cc80e214ea5 100644 --- a/src/sage/graphs/convexity_properties.pxd +++ b/src/sage/graphs/convexity_properties.pxd @@ -7,9 +7,9 @@ cdef class ConvexityProperties: cdef dict _dict_vertices_to_integers cdef binary_matrix_t _cache_hull_pairs - cdef list _vertices_to_integers(self, vertices) - cdef list _integers_to_vertices(self, list integers) - cdef _bitset_convex_hull(self, bitset_t hull) - cpdef hull(self, list vertices) - cdef _greedy_increase(self, bitset_t bs) - cpdef hull_number(self, value_only = *, verbose = *) + cdef list _vertices_to_integers(self, vertices) noexcept + cdef list _integers_to_vertices(self, list integers) noexcept + cdef _bitset_convex_hull(self, bitset_t hull) noexcept + cpdef hull(self, list vertices) noexcept + cdef _greedy_increase(self, bitset_t bs) noexcept + cpdef hull_number(self, value_only = *, verbose = *) noexcept diff --git a/src/sage/graphs/convexity_properties.pyx b/src/sage/graphs/convexity_properties.pyx index c422d0c3190..0c96c518e83 100644 --- a/src/sage/graphs/convexity_properties.pyx +++ b/src/sage/graphs/convexity_properties.pyx @@ -230,20 +230,20 @@ cdef class ConvexityProperties: """ binary_matrix_free(self._cache_hull_pairs) - cdef list _vertices_to_integers(self, vertices): + cdef list _vertices_to_integers(self, vertices) noexcept: r""" Converts a list of vertices to a list of integers with the cached data. """ return [self._dict_vertices_to_integers[v] for v in vertices] - cdef list _integers_to_vertices(self, list integers): + cdef list _integers_to_vertices(self, list integers) noexcept: r""" Convert a list of integers to a list of vertices with the cached data. """ cdef int i return [self._list_integers_to_vertices[i] for i in integers] - cdef _bitset_convex_hull(self, bitset_t hull): + cdef _bitset_convex_hull(self, bitset_t hull) noexcept: r""" Compute the convex hull of a list of vertices given as a bitset. @@ -293,7 +293,7 @@ cdef class ConvexityProperties: # Otherwise, update and back to the loop count = tmp_count - cpdef hull(self, list vertices): + cpdef hull(self, list vertices) noexcept: r""" Return the convex hull of a set of vertices. @@ -324,7 +324,7 @@ cdef class ConvexityProperties: return answer - cdef _greedy_increase(self, bitset_t bs): + cdef _greedy_increase(self, bitset_t bs) noexcept: r""" Given a bitset whose hull is not the whole set, greedily add vertices and stop before its hull is the whole set. @@ -346,7 +346,7 @@ cdef class ConvexityProperties: bitset_free(tmp) - cpdef hull_number(self, value_only=True, verbose=False): + cpdef hull_number(self, value_only=True, verbose=False) noexcept: r""" Compute the hull number and a corresponding generating set. diff --git a/src/sage/graphs/digraph_generators.py b/src/sage/graphs/digraph_generators.py index ec2f608e28c..2b29e0e73ef 100644 --- a/src/sage/graphs/digraph_generators.py +++ b/src/sage/graphs/digraph_generators.py @@ -1331,7 +1331,7 @@ def RandomDirectedAcyclicGraph(self, n, p, weight_max=None): return D - def RandomDirectedGN(self, n, kernel=lambda x: x, seed=None): + def RandomDirectedGN(self, n, kernel=None, seed=None): r""" Return a random growing network (GN) digraph with `n` vertices. @@ -1346,7 +1346,7 @@ def RandomDirectedGN(self, n, kernel=lambda x: x, seed=None): - ``n`` -- integer; number of vertices - - ``kernel`` -- the attachment kernel + - ``kernel`` -- the attachment kernel (default: identity function) - ``seed`` -- a ``random.Random`` seed or a Python ``int`` for the random number generator (default: ``None``) @@ -1365,6 +1365,8 @@ def RandomDirectedGN(self, n, kernel=lambda x: x, seed=None): True sage: D.show() # long time """ + if kernel is None: + kernel = lambda x: x if seed is None: seed = int(current_randstate().long_seed() % sys.maxsize) import networkx diff --git a/src/sage/graphs/distances_all_pairs.pxd b/src/sage/graphs/distances_all_pairs.pxd index 22b81467ec6..98301b92213 100644 --- a/src/sage/graphs/distances_all_pairs.pxd +++ b/src/sage/graphs/distances_all_pairs.pxd @@ -1,11 +1,11 @@ from libc.stdint cimport uint32_t cdef unsigned short * c_shortest_path_all_pairs(G, vertex_list=*) except NULL -cdef unsigned short * c_distances_all_pairs(G, vertex_list=*) +cdef unsigned short * c_distances_all_pairs(G, vertex_list=*) noexcept cdef all_pairs_shortest_path_BFS(gg, unsigned short * predecessors, unsigned short * distances, uint32_t * eccentricity, - vertex_list=*) + vertex_list=*) noexcept cdef uint32_t * c_eccentricity(G, vertex_list=*) except NULL diff --git a/src/sage/graphs/distances_all_pairs.pyx b/src/sage/graphs/distances_all_pairs.pyx index 9445442f603..a61fd4168a4 100644 --- a/src/sage/graphs/distances_all_pairs.pyx +++ b/src/sage/graphs/distances_all_pairs.pyx @@ -145,7 +145,7 @@ from sage.graphs.base.static_sparse_graph cimport (short_digraph, cdef inline c_all_pairs_shortest_path_BFS(short_digraph sd, unsigned short* predecessors, unsigned short* distances, - uint32_t* eccentricity): + uint32_t* eccentricity) noexcept: r""" See the module's documentation. """ @@ -271,7 +271,7 @@ cdef inline all_pairs_shortest_path_BFS(gg, unsigned short* predecessors, unsigned short* distances, uint32_t* eccentricity, - vertex_list=None): + vertex_list=None) noexcept: r""" See the module's documentation. @@ -412,7 +412,7 @@ def shortest_path_all_pairs(G): # Distances # ############# -cdef unsigned short * c_distances_all_pairs(G, vertex_list=None): +cdef unsigned short * c_distances_all_pairs(G, vertex_list=None) noexcept: r""" Returns the matrix of distances in G. @@ -1085,7 +1085,7 @@ cdef uint32_t diameter_lower_bound_2sweep(short_digraph g, uint32_t* distances, uint32_t* predecessors, uint32_t* waiting_list, - bitset_t seen): + bitset_t seen) noexcept: """ Compute a lower bound on the diameter using the 2-sweep algorithm. @@ -1144,7 +1144,7 @@ cdef uint32_t diameter_lower_bound_2sweep(short_digraph g, cdef tuple diameter_lower_bound_2Dsweep(short_digraph g, short_digraph rev_g, - uint32_t source): + uint32_t source) noexcept: r""" Lower bound on the diameter of digraph using directed version of 2-sweep. @@ -1258,7 +1258,7 @@ cdef tuple diameter_lower_bound_2Dsweep(short_digraph g, cdef tuple diameter_lower_bound_multi_sweep(short_digraph g, - uint32_t source): + uint32_t source) noexcept: """ Lower bound on the diameter using multi-sweep. @@ -1336,7 +1336,7 @@ cdef tuple diameter_lower_bound_multi_sweep(short_digraph g, cdef uint32_t diameter_iFUB(short_digraph g, - uint32_t source): + uint32_t source) noexcept: """ Compute the diameter of the input Graph using the ``iFUB`` algorithm. @@ -1420,7 +1420,7 @@ cdef uint32_t diameter_iFUB(short_digraph g, cdef uint32_t diameter_DiFUB(short_digraph sd, - uint32_t source): + uint32_t source) noexcept: r""" Return the diameter of unweighted directed graph. @@ -1545,7 +1545,7 @@ cdef uint32_t diameter_DiFUB(short_digraph sd, return LB -cdef uint32_t diameter_DHV(short_digraph g): +cdef uint32_t diameter_DHV(short_digraph g) noexcept: r""" Return the diameter of unweighted graph `g`. @@ -2088,7 +2088,7 @@ def wiener_index(G): # Szeged index # ################ -cdef uint64_t c_szeged_index_low_memory(short_digraph sd): +cdef uint64_t c_szeged_index_low_memory(short_digraph sd) noexcept: r""" Return the Szeged index of the graph. @@ -2196,7 +2196,7 @@ cdef uint64_t c_szeged_index_low_memory(short_digraph sd): return s -cdef uint64_t c_szeged_index_high_memory(short_digraph sd): +cdef uint64_t c_szeged_index_high_memory(short_digraph sd) noexcept: r""" Return the Szeged index of the graph. diff --git a/src/sage/graphs/edge_connectivity.pyx b/src/sage/graphs/edge_connectivity.pyx index 014e46f7500..72416b560b6 100644 --- a/src/sage/graphs/edge_connectivity.pyx +++ b/src/sage/graphs/edge_connectivity.pyx @@ -300,7 +300,7 @@ cdef class GabowEdgeConnectivity: _ = self.compute_edge_connectivity() sig_check() - cdef build_graph_data_structure(self): + cdef build_graph_data_structure(self) noexcept: r""" Build graph data structures. @@ -447,7 +447,7 @@ cdef class GabowEdgeConnectivity: return True - cdef void increase_memory_for_new_tree(self, int tree): + cdef void increase_memory_for_new_tree(self, int tree) noexcept: """ Allocate data structure for the new tree/forest. @@ -495,7 +495,7 @@ cdef class GabowEdgeConnectivity: self.L_roots[tree] = self.UNUSED self.tree_flag[tree] = False - cdef void compute_dfs_tree(self): + cdef void compute_dfs_tree(self) noexcept: r""" Find a DFS spanning forest of `G \backslash T`. @@ -530,7 +530,7 @@ cdef class GabowEdgeConnectivity: # Each call of find_dfs_tree creates an f-tree self.num_start_f_trees += 1 - cdef void find_dfs_tree(self, int r): + cdef void find_dfs_tree(self, int r) noexcept: r""" Find more vertices of the f-tree rooted at `r`. @@ -577,7 +577,7 @@ cdef class GabowEdgeConnectivity: # We are done with u. We pop. t -= 1 - cdef void find_dfs_tree_rec(self, int u, int r): + cdef void find_dfs_tree_rec(self, int u, int r) noexcept: r""" Find more vertices of the f-tree rooted at `r`. @@ -609,7 +609,7 @@ cdef class GabowEdgeConnectivity: # recursively find more vertices and grow the subtree rooted at r self.find_dfs_tree_rec(v, r) - cdef int choose_root(self): + cdef int choose_root(self) noexcept: """ Return the root of an active f_tree, or INT_MAX if none exists. @@ -694,7 +694,7 @@ cdef class GabowEdgeConnectivity: return True return False - cdef void join(self, int e_id): + cdef void join(self, int e_id) noexcept: """ Assign edge e_id to current tree. @@ -864,7 +864,7 @@ cdef class GabowEdgeConnectivity: return self.label_A_path(e_id) - cdef bint is_joining_edge(self, int e_id): + cdef bint is_joining_edge(self, int e_id) noexcept: """ Check if edge e_id is joining. @@ -879,7 +879,7 @@ cdef class GabowEdgeConnectivity: cdef int root_y = self.root[self.my_to[e_id]] return (root_x != root_y) and (root_x == self.augmenting_root or root_y == self.augmenting_root) - cdef int label_A_path(self, int e_id): + cdef int label_A_path(self, int e_id) noexcept: """ Labels the incident unused edges as the label_A_step of the algorithm @@ -913,7 +913,7 @@ cdef class GabowEdgeConnectivity: return INT_MAX - cdef bint label_step(self, int e_id, int e_label): + cdef bint label_step(self, int e_id, int e_label) noexcept: """ Label edge e_id with e_label and check whether edge e_id is joining. @@ -935,7 +935,7 @@ cdef class GabowEdgeConnectivity: # The roots are different. Check whether one of them is on the f_tree return root_x == self.augmenting_root or root_y == self.augmenting_root - cdef bint any_unused_is_unlabeled(self, int x): + cdef bint any_unused_is_unlabeled(self, int x) noexcept: """ Check if each unused edge directed to x is unlabeled @@ -955,7 +955,7 @@ cdef class GabowEdgeConnectivity: return True - cdef void augmentation_algorithm(self): + cdef void augmentation_algorithm(self) noexcept: """ Trace the path of the found joining edges @@ -972,7 +972,7 @@ cdef class GabowEdgeConnectivity: self.joining_edges.pop() self.trace_back(e_id, e_state) - cdef void trace_back(self, int e_id, int e_state): + cdef void trace_back(self, int e_id, int e_state) noexcept: """ Trace the path of a joining edge and transfer the edges to the appropriate tree Ti. @@ -1027,7 +1027,7 @@ cdef class GabowEdgeConnectivity: e = ep ep = self.labels[e] - cdef re_init(self, int tree): + cdef re_init(self, int tree) noexcept: """ Make f_trees active (except the f_tree of the root), update depths and parent values, and clear the labels. @@ -1085,7 +1085,7 @@ cdef class GabowEdgeConnectivity: if j != self.root_vertex: self.forests[j] = True - cdef void update_parents_depths(self, int tree): + cdef void update_parents_depths(self, int tree) noexcept: """ Update parents, depths, and, if current_tree is k, the vertex labels to the root of each f_tree. @@ -1115,7 +1115,7 @@ cdef class GabowEdgeConnectivity: self.update_parents_dfs(tree, v) self.root[i] = self.root[v] - cdef void update_parents_dfs(self, int tree, int x): + cdef void update_parents_dfs(self, int tree, int x) noexcept: """ Helper method for ``update_parents_depths``. @@ -1157,7 +1157,7 @@ cdef class GabowEdgeConnectivity: self.my_parent_edge_id[tree][v] = e_id self.my_depth[tree][v] = depth - cdef void save_current_k_intersection(self): + cdef void save_current_k_intersection(self) noexcept: """ Save the current k-intersection. diff --git a/src/sage/graphs/generic_graph.py b/src/sage/graphs/generic_graph.py index eedbc36bef3..a99aa1d5a64 100644 --- a/src/sage/graphs/generic_graph.py +++ b/src/sage/graphs/generic_graph.py @@ -5149,14 +5149,14 @@ def cycle_basis(self, output='vertex'): sage: G = Graph([(0, 2, 'a'), (0, 2, 'b'), (0, 1, 'c'), (1, 2, 'd')], ....: multiedges=True) - sage: G.cycle_basis() # needs networkx - [[0, 2], [2, 1, 0]] - sage: G.cycle_basis(output='edge') # needs networkx - [[(0, 2, 'b'), (2, 0, 'a')], [(2, 1, 'd'), (1, 0, 'c'), (0, 2, 'a')]] + sage: G.cycle_basis() + [[2, 0], [2, 0, 1]] + sage: G.cycle_basis(output='edge') + [[(0, 2, 'b'), (2, 0, 'a')], [(1, 2, 'd'), (2, 0, 'a'), (0, 1, 'c')]] sage: H = Graph([(1, 2), (2, 3), (2, 3), (3, 4), (1, 4), ....: (1, 4), (4, 5), (5, 6), (4, 6), (6, 7)], multiedges=True) - sage: H.cycle_basis() # needs networkx - [[1, 4], [2, 3], [4, 3, 2, 1], [6, 5, 4]] + sage: H.cycle_basis() + [[4, 1], [3, 2], [4, 1, 2, 3], [6, 4, 5]] Disconnected graph:: @@ -5168,19 +5168,19 @@ def cycle_basis(self, output='vertex'): ('Really ?', 'Wuuhuu', None), ('Wuuhuu', 'Hey', None)], [(0, 2, 'a'), (2, 0, 'b')], - [(0, 2, 'b'), (1, 0, 'c'), (2, 1, 'd')]] + [(0, 1, 'c'), (1, 2, 'd'), (2, 0, 'b')]] Graph that allows multiple edges but does not contain any:: sage: G = graphs.CycleGraph(3) sage: G.allow_multiple_edges(True) - sage: G.cycle_basis() # needs networkx - [[2, 1, 0]] + sage: G.cycle_basis() + [[2, 0, 1]] Not yet implemented for directed graphs:: sage: G = DiGraph([(0, 2, 'a'), (0, 1, 'c'), (1, 2, 'd')]) - sage: G.cycle_basis() # needs networkx + sage: G.cycle_basis() Traceback (most recent call last): ... NotImplementedError: not implemented for directed graphs @@ -5191,12 +5191,12 @@ def cycle_basis(self, output='vertex'): sage: G = Graph([(1, 2, 'a'), (2, 3, 'b'), (2, 3, 'c'), ....: (3, 4, 'd'), (3, 4, 'e'), (4, 1, 'f')], multiedges=True) - sage: G.cycle_basis() # needs networkx - [[2, 3], [4, 3, 2, 1], [4, 3, 2, 1]] - sage: G.cycle_basis(output='edge') # needs networkx + sage: G.cycle_basis() + [[3, 2], [4, 1, 2, 3], [4, 1, 2, 3]] + sage: G.cycle_basis(output='edge') [[(2, 3, 'c'), (3, 2, 'b')], - [(4, 3, 'd'), (3, 2, 'b'), (2, 1, 'a'), (1, 4, 'f')], - [(4, 3, 'e'), (3, 2, 'b'), (2, 1, 'a'), (1, 4, 'f')]] + [(3, 4, 'd'), (4, 1, 'f'), (1, 2, 'a'), (2, 3, 'b')], + [(3, 4, 'e'), (4, 1, 'f'), (1, 2, 'a'), (2, 3, 'b')]] """ if output not in ['vertex', 'edge']: raise ValueError('output must be either vertex or edge') @@ -5211,14 +5211,32 @@ def cycle_basis(self, output='vertex'): []) from sage.graphs.graph import Graph + from itertools import pairwise T = Graph(self.min_spanning_tree(), multiedges=True, format='list_of_edges') H = self.copy() H.delete_edges(T.edge_iterator()) + root = next(T.vertex_iterator()) + rank = dict(T.breadth_first_search(root, report_distance=True)) + parent = {v: u for u, v in T.breadth_first_search(root, edges=True)} L = [] for e in H.edge_iterator(): - T.add_edge(e) - L.append(T.is_tree(certificate=True, output=output)[1]) - T.delete_edge(e) + # Search for the nearest common ancestor of e[0] and e[1] in T + P = [e[0]] + Q = [e[1]] + while P[-1] != Q[-1]: + # If rank[P[-1]] > rank[Q[-1]], we extend the path P. + # If rank[P[-1]] < rank[Q[-1]], we extend the path Q. + # In case of equality, we extend both paths. + diff = rank[P[-1]] - rank[Q[-1]] + if diff >= 0: + P.append(parent[P[-1]]) + if diff <= 0: + Q.append(parent[Q[-1]]) + + cycle = Q + P[-2::-1] + if output == 'edge': + cycle = [e] + [(x, y, T.edge_label(x, y)[0]) for x, y in pairwise(cycle)] + L.append(cycle) return L # second case: there are no multiple edges @@ -5289,7 +5307,7 @@ def minimum_cycle_basis(self, algorithm=None, weight_function=None, by_weight=Fa TESTS:: sage: g = Graph([(0, 1, 1), (1, 2, 'a')]) - sage: g.min_spanning_tree(by_weight=True) + sage: g.minimum_cycle_basis(by_weight=True) Traceback (most recent call last): ... ValueError: the weight function cannot find the weight of (1, 2, 'a') @@ -11431,8 +11449,7 @@ def neighbor_iterator(self, vertex, closed=False): if not self.has_edge(vertex, vertex): yield vertex - for u in self._backend.iterator_nbrs(vertex): - yield u + yield from self._backend.iterator_nbrs(vertex) def vertices(self, sort=False, key=None, degree=None, vertex_property=None): r""" diff --git a/src/sage/graphs/generic_graph_pyx.pxd b/src/sage/graphs/generic_graph_pyx.pxd index 23f45e38080..1a472c59a70 100644 --- a/src/sage/graphs/generic_graph_pyx.pxd +++ b/src/sage/graphs/generic_graph_pyx.pxd @@ -8,7 +8,7 @@ ctypedef fused dimension_t: D_TWO D_THREE -cdef run_spring(int, dimension_t, double*, int*, int, int, bint) +cdef run_spring(int, dimension_t, double*, int*, int, int, bint) noexcept cdef class GenericGraph_pyx(SageObject): pass @@ -17,7 +17,7 @@ cdef class GenericGraph_pyx(SageObject): cdef class SubgraphSearch: cdef int ng cdef int nh - cdef (bint) (*is_admissible) (int, int *, int *) + cdef (bint) (*is_admissible) (int, int *, int *) noexcept cdef DenseGraph g cdef DenseGraph h cdef int *busy diff --git a/src/sage/graphs/generic_graph_pyx.pyx b/src/sage/graphs/generic_graph_pyx.pyx index c8777a62f23..613d6c1c4ef 100644 --- a/src/sage/graphs/generic_graph_pyx.pyx +++ b/src/sage/graphs/generic_graph_pyx.pyx @@ -258,7 +258,7 @@ def spring_layout_fast(G, iterations=50, int dim=2, vpos=None, bint rescale=True @cython.cdivision(True) -cdef run_spring(int iterations, dimension_t _dim, double* pos, int* edges, int n, int m, bint height): +cdef run_spring(int iterations, dimension_t _dim, double* pos, int* edges, int n, int m, bint height) noexcept: r""" Find a locally optimal layout for this graph, according to the constraints that neighboring nodes want to be a fixed distance @@ -388,7 +388,7 @@ cdef run_spring(int iterations, dimension_t _dim, double* pos, int* edges, int n @cython.cdivision(True) -cdef inline double sqrt_approx(double x, double y, double xx, double yy): +cdef inline double sqrt_approx(double x, double y, double xx, double yy) noexcept: r""" Approximation of `\sqrt(x^2+y^2)`. @@ -979,7 +979,7 @@ cdef class SubgraphSearch: sig_off() raise StopIteration -cdef inline bint vectors_equal(int n, int *a, int *b): +cdef inline bint vectors_equal(int n, int *a, int *b) noexcept: r""" Tests whether the two given vectors are equal. Two integer vectors `a = (a_1, a_2, \dots, a_n)` and `b = (b_1, b_2, \dots, b_n)` are equal @@ -1002,7 +1002,7 @@ cdef inline bint vectors_equal(int n, int *a, int *b): return False return True -cdef inline bint vectors_inferior(int n, int *a, int *b): +cdef inline bint vectors_inferior(int n, int *a, int *b) noexcept: r""" Tests whether the second vector of integers is inferior to the first. Let `u = (u_1, u_2, \dots, u_k)` and `v = (v_1, v_2, \dots, v_k)` be two @@ -1157,7 +1157,7 @@ def _test_vectors_equal_inferior(): cpdef tuple find_hamiltonian(G, long max_iter=100000, long reset_bound=30000, - long backtrack_bound=1000, find_path=False): + long backtrack_bound=1000, find_path=False) noexcept: r""" Randomized backtracking for finding Hamiltonian cycles and paths. diff --git a/src/sage/graphs/genus.pyx b/src/sage/graphs/genus.pyx index 90fb4bf4c52..4370f3135af 100644 --- a/src/sage/graphs/genus.pyx +++ b/src/sage/graphs/genus.pyx @@ -49,7 +49,7 @@ from sage.graphs.base.dense_graph cimport DenseGraph from sage.graphs.graph import Graph -cdef inline int edge_map(int i): +cdef inline int edge_map(int i) noexcept: """ We might as well make the edge map nice, since the vertex map is so slippery. This is the fastest way I could find to establish the @@ -202,7 +202,7 @@ cdef class simple_connected_genus_backtracker: # print(self.face_map[v], end="") # print(']') - cdef inline void freeze_face(self): + cdef inline void freeze_face(self) noexcept: """ Quickly store the current face_map so we can recover the embedding it corresponds to later. @@ -269,7 +269,7 @@ cdef class simple_connected_genus_backtracker: return embedding - cdef int run_cycle(self, int i): + cdef int run_cycle(self, int i) noexcept: r""" Mark off the orbit of `i` under face_map. @@ -297,7 +297,7 @@ cdef class simple_connected_genus_backtracker: j = self.face_map[j] return 1 - cdef void flip(self, int v, int i): + cdef void flip(self, int v, int i) noexcept: r""" This is where the real work happens. Once cycles have been counted for the initial face_map, we make small local changes, and look at their @@ -389,7 +389,7 @@ cdef class simple_connected_genus_backtracker: w[i] = v2 w[i + 1] = v1 - cdef int count_cycles(self): + cdef int count_cycles(self) noexcept: """ Count all cycles. """ @@ -461,14 +461,14 @@ cdef class simple_connected_genus_backtracker: sig_off() return g - cdef void reset_swap(self, int v): + cdef void reset_swap(self, int v) noexcept: """ Reset the swapper associated with vertex ``v``. """ cdef int d = self.degree[v] - 1 reset_swap(d, self.swappers[v], self.swappers[v] + d) - cdef int next_swap(self, int v): + cdef int next_swap(self, int v) noexcept: """ Compute and return the next swap associated with the vertex ``v``. """ @@ -478,7 +478,7 @@ cdef class simple_connected_genus_backtracker: cdef int genus_backtrack(self, int cutoff, bint record_embedding, - (int (*)(simple_connected_genus_backtracker, int, bint, int))check_embedding): + (int (*)(simple_connected_genus_backtracker, int, bint, int))check_embedding) noexcept: """ Here's the main backtracking routine. @@ -523,7 +523,7 @@ cdef class simple_connected_genus_backtracker: cdef int min_genus_check(simple_connected_genus_backtracker self, int cutoff, bint record_embedding, - int initial): + int initial) noexcept: """ Search for the minimal genus. @@ -543,7 +543,7 @@ cdef int min_genus_check(simple_connected_genus_backtracker self, cdef int max_genus_check(simple_connected_genus_backtracker self, int cutoff, bint record_embedding, - int initial): + int initial) noexcept: """ Same as min_genus_check, but search for a maximum. """ diff --git a/src/sage/graphs/graph.py b/src/sage/graphs/graph.py index 2435bd815b7..b3c845af376 100644 --- a/src/sage/graphs/graph.py +++ b/src/sage/graphs/graph.py @@ -9039,8 +9039,7 @@ def rec(G): # For each unlabeled matching, we yield all its possible labelings for m in rec(G): - for pm in itertools.product(*[edges[frozenset(e)] for e in m]): - yield pm + yield from itertools.product(*[edges[frozenset(e)] for e in m]) @doc_index("Leftovers") def has_perfect_matching(self, algorithm="Edmonds", solver=None, verbose=0, diff --git a/src/sage/graphs/graph_coloring.pyx b/src/sage/graphs/graph_coloring.pyx index d93745b85b5..327435969fe 100644 --- a/src/sage/graphs/graph_coloring.pyx +++ b/src/sage/graphs/graph_coloring.pyx @@ -327,7 +327,7 @@ def all_graph_colorings(G, n, count_only=False, hex_colors=False, raise RuntimeError("too much recursion, Graph coloring failed") -cpdef first_coloring(G, n=0, hex_colors=False): +cpdef first_coloring(G, n=0, hex_colors=False) noexcept: r""" Return the first vertex coloring found. @@ -365,7 +365,7 @@ cpdef first_coloring(G, n=0, hex_colors=False): return C -cpdef number_of_n_colorings(G, n): +cpdef number_of_n_colorings(G, n) noexcept: r""" Compute the number of `n`-colorings of a graph @@ -397,7 +397,7 @@ cpdef number_of_n_colorings(G, n): return m -cpdef numbers_of_colorings(G): +cpdef numbers_of_colorings(G) noexcept: r""" Compute the number of colorings of a graph. @@ -416,7 +416,7 @@ cpdef numbers_of_colorings(G): return answer -cpdef chromatic_number(G): +cpdef chromatic_number(G) noexcept: r""" Return the chromatic number of the graph. diff --git a/src/sage/graphs/graph_decompositions/bandwidth.pyx b/src/sage/graphs/graph_decompositions/bandwidth.pyx index bbd3916ac2b..61bacd2daf5 100644 --- a/src/sage/graphs/graph_decompositions/bandwidth.pyx +++ b/src/sage/graphs/graph_decompositions/bandwidth.pyx @@ -294,7 +294,7 @@ cdef bint bandwidth_C(int n, int k, index_t * left_to_order, # begins with the assigned vertices, ends with the others index_t * index_array_tmp, # tmp space range_t ** ith_range_array, # array of ranges, for every step of the algorithm - range_t * range_array_tmp): # tmp space + range_t * range_array_tmp) noexcept: # tmp space cdef int i, v cdef int pi # the position for which a vertex is being chosen @@ -366,7 +366,7 @@ cdef bint bandwidth_C(int n, int k, # swap back left_to_order[i], left_to_order[current[i]] = left_to_order[current[i]], left_to_order[i] -cdef bint is_matching_feasible(int n, range_t * range_array, range_t * range_array_tmp, index_t * index_array_tmp): +cdef bint is_matching_feasible(int n, range_t * range_array, range_t * range_array_tmp, index_t * index_array_tmp) noexcept: r""" Test if the matching is feasible diff --git a/src/sage/graphs/graph_decompositions/clique_separators.pyx b/src/sage/graphs/graph_decompositions/clique_separators.pyx index b4f92db5172..0989a5a9dae 100644 --- a/src/sage/graphs/graph_decompositions/clique_separators.pyx +++ b/src/sage/graphs/graph_decompositions/clique_separators.pyx @@ -140,7 +140,7 @@ def make_labelled_rooted_tree(atoms, cliques): return to_tree(0, len(cliques)) -cdef inline bint is_clique(short_digraph sd, vector[int] Hx): +cdef inline bint is_clique(short_digraph sd, vector[int] Hx) noexcept: """ Check if the subgraph sd[Hx] is a clique. diff --git a/src/sage/graphs/graph_decompositions/cutwidth.pyx b/src/sage/graphs/graph_decompositions/cutwidth.pyx index ddaf746adac..e4e139084c0 100644 --- a/src/sage/graphs/graph_decompositions/cutwidth.pyx +++ b/src/sage/graphs/graph_decompositions/cutwidth.pyx @@ -530,7 +530,7 @@ def cutwidth_dyn(G, lower_bound=0): sig_free(neighborhoods) -cdef inline int exists(FastDigraph g, uint8_t* neighborhoods, int S, int cost_S, int v, int k): +cdef inline int exists(FastDigraph g, uint8_t* neighborhoods, int S, int cost_S, int v, int k) noexcept: r""" Check whether an ordering with the given cost `k` exists, and updates data in the neighborhoods array at the same time. See the module's documentation. diff --git a/src/sage/graphs/graph_decompositions/fast_digraph.pxd b/src/sage/graphs/graph_decompositions/fast_digraph.pxd index 85466f67ac1..2687f8f974d 100644 --- a/src/sage/graphs/graph_decompositions/fast_digraph.pxd +++ b/src/sage/graphs/graph_decompositions/fast_digraph.pxd @@ -6,7 +6,7 @@ cdef class FastDigraph: cdef list int_to_vertices cdef int * degree -cdef int compute_out_neighborhood_cardinality(FastDigraph, int) +cdef int compute_out_neighborhood_cardinality(FastDigraph, int) noexcept -cdef int popcount32(int) -cdef int slow_popcount32(int) +cdef int popcount32(int) noexcept +cdef int slow_popcount32(int) noexcept diff --git a/src/sage/graphs/graph_decompositions/fast_digraph.pyx b/src/sage/graphs/graph_decompositions/fast_digraph.pyx index 3d7c4b2fea7..2d28ccf4d05 100644 --- a/src/sage/graphs/graph_decompositions/fast_digraph.pyx +++ b/src/sage/graphs/graph_decompositions/fast_digraph.pyx @@ -109,7 +109,7 @@ cdef class FastDigraph: print(((self.graph[i] >> j) & 1), end="") print("") -cdef inline int compute_out_neighborhood_cardinality(FastDigraph g, int S): +cdef inline int compute_out_neighborhood_cardinality(FastDigraph g, int S) noexcept: r""" Return the cardinality of `N^+(S)\S`. @@ -139,7 +139,7 @@ cdef inline int compute_out_neighborhood_cardinality(FastDigraph g, int S): tmp &= (~S) return popcount32(tmp) -cdef inline int popcount32(int i): +cdef inline int popcount32(int i) noexcept: r""" Return the number of '1' bits in a 32-bits integer. @@ -184,7 +184,7 @@ def test_popcount(): i += 1 -cdef inline int slow_popcount32(int i): +cdef inline int slow_popcount32(int i) noexcept: """ Return the number of '1' bits in a 32-bits integer. diff --git a/src/sage/graphs/graph_decompositions/rankwidth.pxd b/src/sage/graphs/graph_decompositions/rankwidth.pxd index d24460b5bb9..a23faceac4f 100644 --- a/src/sage/graphs/graph_decompositions/rankwidth.pxd +++ b/src/sage/graphs/graph_decompositions/rankwidth.pxd @@ -9,4 +9,4 @@ cdef extern from "rw.h": subset_t *cslots subset_t *adjacency_matrix -cdef void print_rank_dec(subset_t s, int l) +cdef void print_rank_dec(subset_t s, int l) noexcept diff --git a/src/sage/graphs/graph_decompositions/rankwidth.pyx b/src/sage/graphs/graph_decompositions/rankwidth.pyx index b08a64b79d3..5be540bafe2 100644 --- a/src/sage/graphs/graph_decompositions/rankwidth.pyx +++ b/src/sage/graphs/graph_decompositions/rankwidth.pyx @@ -200,7 +200,7 @@ def rank_decomposition(G, verbose=False): return (rank_width, g) -cdef int sage_graph_to_matrix(G): +cdef int sage_graph_to_matrix(G) noexcept: r""" Convert the given Sage graph as an adjacency matrix. """ @@ -235,11 +235,11 @@ cdef int sage_graph_to_matrix(G): return 0 -cdef uint_fast32_t bitmask(int i): +cdef uint_fast32_t bitmask(int i) noexcept: return (1ul << i) -cdef void set_am(int i, int j, int val): +cdef void set_am(int i, int j, int val) noexcept: r""" Set/Unset an arc between vertices i and j @@ -255,7 +255,7 @@ cdef void set_am(int i, int j, int val): adjacency_matrix[j] |= bitmask(i) -cdef void print_rank_dec(subset_t s, int l): +cdef void print_rank_dec(subset_t s, int l) noexcept: r""" Print the current rank decomposition as a text @@ -321,7 +321,7 @@ def mkgraph(int num_vertices): return g -cdef bitset_to_vertex_set(subset_t s): +cdef bitset_to_vertex_set(subset_t s) noexcept: """ Return as a Set object the set corresponding to the given subset_t variable. diff --git a/src/sage/graphs/graph_decompositions/tdlib.pyx b/src/sage/graphs/graph_decompositions/tdlib.pyx index ad3ded3e876..90cfa756d00 100644 --- a/src/sage/graphs/graph_decompositions/tdlib.pyx +++ b/src/sage/graphs/graph_decompositions/tdlib.pyx @@ -76,7 +76,7 @@ cdef extern from "sage_tdlib.cpp": # the following will be used implicitly to do the translation # between Sage graph encoding and BGL graph encoding. -cdef make_tdlib_graph(G, vertex_to_int, vector[unsigned int] &V, vector[unsigned int] &E): +cdef make_tdlib_graph(G, vertex_to_int, vector[unsigned int] &V, vector[unsigned int] &E) noexcept: for i in range(G.order()): V.push_back(i) @@ -85,7 +85,7 @@ cdef make_tdlib_graph(G, vertex_to_int, vector[unsigned int] &V, vector[unsigned E.push_back(vertex_to_int[v]) -cdef make_sage_decomp(G, vector[vector[int]] &V, vector[unsigned int] &E, int_to_vertex): +cdef make_sage_decomp(G, vector[vector[int]] &V, vector[unsigned int] &E, int_to_vertex) noexcept: cdef int i, j for i in range(len(V)): G.add_vertex(Set([int_to_vertex[j] for j in V[i]])) diff --git a/src/sage/graphs/graph_decompositions/tree_decomposition.pxd b/src/sage/graphs/graph_decompositions/tree_decomposition.pxd index e8afe048691..2de876e8889 100644 --- a/src/sage/graphs/graph_decompositions/tree_decomposition.pxd +++ b/src/sage/graphs/graph_decompositions/tree_decomposition.pxd @@ -13,4 +13,4 @@ cdef class TreelengthConnected: cdef GenericGraph_pyx tree # The final tree decomposition is stored cdef unsigned int length cdef bint leq_k - cdef bint _treelength(self, g, k) + cdef bint _treelength(self, g, k) noexcept diff --git a/src/sage/graphs/graph_decompositions/tree_decomposition.pyx b/src/sage/graphs/graph_decompositions/tree_decomposition.pyx index 1e364277c8c..90f14298c5a 100644 --- a/src/sage/graphs/graph_decompositions/tree_decomposition.pyx +++ b/src/sage/graphs/graph_decompositions/tree_decomposition.pyx @@ -1048,7 +1048,7 @@ cdef class TreelengthConnected: sig_free(self.c_distances) sig_free(self.distances) - cdef bint _treelength(self, g, k): + cdef bint _treelength(self, g, k) noexcept: r""" Check whether the treelength of `g` is at most `k`. diff --git a/src/sage/graphs/graph_decompositions/vertex_separation.pxd b/src/sage/graphs/graph_decompositions/vertex_separation.pxd index fa757b2c28e..fbadc893436 100644 --- a/src/sage/graphs/graph_decompositions/vertex_separation.pxd +++ b/src/sage/graphs/graph_decompositions/vertex_separation.pxd @@ -1,4 +1,4 @@ from libc.stdint cimport uint8_t from sage.graphs.graph_decompositions.fast_digraph cimport FastDigraph -cdef list find_order(FastDigraph, uint8_t *, int) +cdef list find_order(FastDigraph, uint8_t *, int) noexcept diff --git a/src/sage/graphs/graph_decompositions/vertex_separation.pyx b/src/sage/graphs/graph_decompositions/vertex_separation.pyx index 90fb086e1ae..548229f303b 100644 --- a/src/sage/graphs/graph_decompositions/vertex_separation.pyx +++ b/src/sage/graphs/graph_decompositions/vertex_separation.pyx @@ -1011,7 +1011,7 @@ def vertex_separation_exp(G, verbose=False): # Actual algorithm, breadth-first search and updates of the costs of the sets # ############################################################################### -cdef inline int exists(FastDigraph g, uint8_t* neighborhoods, int current, int cost): +cdef inline int exists(FastDigraph g, uint8_t* neighborhoods, int current, int cost) noexcept: """ Check whether an ordering with the given cost exists, and updates data in the neighborhoods array at the same time. See the module's documentation. @@ -1053,7 +1053,7 @@ cdef inline int exists(FastDigraph g, uint8_t* neighborhoods, int current, int c return neighborhoods[current] -cdef list find_order(FastDigraph g, uint8_t* neighborhoods, int cost): +cdef list find_order(FastDigraph g, uint8_t* neighborhoods, int cost) noexcept: """ Return the ordering once we are sure it exists """ @@ -1083,14 +1083,14 @@ cdef list find_order(FastDigraph g, uint8_t* neighborhoods, int cost): # Min/Max functions -cdef inline int minimum(int a, int b): +cdef inline int minimum(int a, int b) noexcept: if a < b: return a else: return b -cdef inline int maximum(int a, int b): +cdef inline int maximum(int a, int b) noexcept: if a > b: return a else: @@ -1742,7 +1742,7 @@ def vertex_separation_BAB(G, return (width if width < upper_bound else -1), order -cdef inline _my_invert_positions(int *prefix, int *positions, int pos_a, int pos_b): +cdef inline _my_invert_positions(int *prefix, int *positions, int pos_a, int pos_b) noexcept: """ Permute vertices at positions ``pos_a`` and ``pos_b`` in array ``prefix``, and record the new positions in array ``positions``. @@ -1767,7 +1767,7 @@ cdef int vertex_separation_BAB_C(binary_matrix_t H, set prefix_storage, int max_prefix_length, int max_prefix_number, - bint verbose): + bint verbose) noexcept: r""" Branch and Bound algorithm for the process number and the vertex separation. diff --git a/src/sage/graphs/graph_generators.py b/src/sage/graphs/graph_generators.py index e45371bc6d9..b029a9609b2 100644 --- a/src/sage/graphs/graph_generators.py +++ b/src/sage/graphs/graph_generators.py @@ -1192,7 +1192,7 @@ def nauty_genbg(self, options="", debug=False): G = BipartiteGraph(s[:-1], format='graph6', partition=partition) yield G - def cospectral_graphs(self, vertices, matrix_function=lambda g: g.adjacency_matrix(), graphs=None): + def cospectral_graphs(self, vertices, matrix_function=None, graphs=None): r""" Find all sets of graphs on ``vertices`` vertices (with possible restrictions) which are cospectral with respect to a @@ -1288,6 +1288,9 @@ def cospectral_graphs(self, vertices, matrix_function=lambda g: g.adjacency_matr ....: == g[0][1].laplacian_matrix(normalized=True).charpoly()) True """ + if matrix_function is None: + matrix_function = lambda g: g.adjacency_matrix() + from sage.graphs.graph_generators import graphs as graph_gen if graphs is None: graph_list = graph_gen(vertices, property=lambda _: True) @@ -1521,8 +1524,7 @@ def fullerenes(self, order, ipr=False): sp.stdout.reconfigure(newline='') - for G in graphs._read_planar_code(sp.stdout): - yield(G) + yield from graphs._read_planar_code(sp.stdout) def fusenes(self, hexagon_count, benzenoids=False): r""" @@ -1797,8 +1799,7 @@ def plantri_gen(self, options=""): sp.stdout.reconfigure(newline='') try: - for G in graphs._read_planar_code(sp.stdout): - yield(G) + yield from graphs._read_planar_code(sp.stdout) except AssertionError: raise AttributeError("invalid options '{}'".format(options)) diff --git a/src/sage/graphs/hyperbolicity.pyx b/src/sage/graphs/hyperbolicity.pyx index 880fccfc8f9..5361ebbff95 100644 --- a/src/sage/graphs/hyperbolicity.pyx +++ b/src/sage/graphs/hyperbolicity.pyx @@ -236,7 +236,7 @@ def _my_subgraph(G, vertices, relabel=False, return_map=False): # Building blocks ###################################################################### -cdef inline int __hyp__(unsigned short** distances, int a, int b, int c, int d): +cdef inline int __hyp__(unsigned short** distances, int a, int b, int c, int d) noexcept: """ Return the hyperbolicity of the given 4-tuple. """ @@ -263,7 +263,7 @@ cdef inline int __hyp__(unsigned short** distances, int a, int b, int c, int d): cdef tuple hyperbolicity_basic_algorithm(int N, unsigned short** distances, - verbose): + verbose) noexcept: """ Return **twice** the hyperbolicity of a graph, and a certificate. @@ -368,7 +368,7 @@ def _greedy_dominating_set(H, verbose=False): cdef inline distances_and_far_apart_pairs(gg, unsigned short* distances, unsigned short* far_apart_pairs, - list int_to_vertex): + list int_to_vertex) noexcept: """ Compute both distances between all pairs and far-apart pairs. @@ -482,7 +482,7 @@ cdef inline pair** sort_pairs(uint32_t N, unsigned short** values, unsigned short** to_include, uint32_t* nb_p, - uint32_t* nb_pairs_of_length): + uint32_t* nb_pairs_of_length) noexcept: """ Return an array of unordered pairs {i,j} in increasing order of values. @@ -583,7 +583,7 @@ cdef tuple hyperbolicity_BCCM(int N, int h_LB, float approximation_factor, float additive_gap, - verbose=False): + verbose=False) noexcept: """ Return the hyperbolicity of a graph. @@ -841,7 +841,7 @@ cdef tuple hyperbolicity_CCL(int N, int h_LB, float approximation_factor, float additive_gap, - verbose=False): + verbose=False) noexcept: """ Return the hyperbolicity of a graph. @@ -1465,7 +1465,7 @@ def hyperbolicity(G, # Distribution of the hyperbolicity of 4-tuples ###################################################################### -cdef dict __hyperbolicity_distribution__(int N, unsigned short** distances): +cdef dict __hyperbolicity_distribution__(int N, unsigned short** distances) noexcept: """ Return the distribution of the hyperbolicity of the 4-tuples of the graph. @@ -1526,7 +1526,7 @@ cdef extern from "stdlib.h": void c_libc_srandom "srandom"(unsigned int seed) -cdef dict __hyperbolicity_sampling__(int N, unsigned short** distances, uint64_t sampling_size): +cdef dict __hyperbolicity_sampling__(int N, unsigned short** distances, uint64_t sampling_size) noexcept: """ Return a sampling of the hyperbolicity distribution of the graph. diff --git a/src/sage/graphs/independent_sets.pyx b/src/sage/graphs/independent_sets.pyx index f1dc1260c34..c5105df067d 100644 --- a/src/sage/graphs/independent_sets.pyx +++ b/src/sage/graphs/independent_sets.pyx @@ -20,7 +20,7 @@ from sage.misc.cachefunc import cached_method from sage.graphs.base.static_dense_graph cimport dense_graph_init -cdef inline int ismaximal(binary_matrix_t g, int n, bitset_t s): +cdef inline int ismaximal(binary_matrix_t g, int n, bitset_t s) noexcept: cdef int i for i in range(n): if (not bitset_in(s, i)) and bitset_are_disjoint(g.rows[i], s): diff --git a/src/sage/graphs/matchpoly.pyx b/src/sage/graphs/matchpoly.pyx index 10c8d524164..7bd14c38bcd 100644 --- a/src/sage/graphs/matchpoly.pyx +++ b/src/sage/graphs/matchpoly.pyx @@ -348,7 +348,7 @@ def complete_poly(n): return b -cdef void delete_and_add(int **edges, int nverts, int nedges, int totverts, int depth, fmpz_poly_t pol): +cdef void delete_and_add(int **edges, int nverts, int nedges, int totverts, int depth, fmpz_poly_t pol) noexcept: """ Add matching polynomial to pol via recursion. diff --git a/src/sage/graphs/strongly_regular_db.pyx b/src/sage/graphs/strongly_regular_db.pyx index 2c3cecfeed5..dc5f9d960bf 100644 --- a/src/sage/graphs/strongly_regular_db.pyx +++ b/src/sage/graphs/strongly_regular_db.pyx @@ -1738,7 +1738,7 @@ def is_nowhere0_twoweight(int v, int k, int l, int mu): return (Nowhere0WordsTwoWeightCodeGraph, q) -cdef eigenvalues(int v, int k, int l, int mu): +cdef eigenvalues(int v, int k, int l, int mu) noexcept: r""" Return the eigenvalues of a (v,k,l,mu)-strongly regular graph. @@ -1848,7 +1848,7 @@ def eigenmatrix(int v, int k, int l, int mu): return Matrix(ZZ, [[1, k, v-k-1], [1, r, -r-1], [1, s, -s-1]]) -cpdef latin_squares_graph_parameters(int v, int k, int l,int mu): +cpdef latin_squares_graph_parameters(int v, int k, int l,int mu) noexcept: r""" Check whether (v,k,l,mu)-strongly regular graph has parameters of an `L_g(n)` s.r.g. @@ -2690,7 +2690,7 @@ def SRG_1288_792_476_504(): return G -cdef bint seems_feasible(int v, int k, int l, int mu): +cdef bint seems_feasible(int v, int k, int l, int mu) noexcept: r""" Check if the set of parameters seems feasible. @@ -3258,7 +3258,7 @@ def _build_small_srg_database(): _small_srg_database[N, K, l, m] = [strongly_regular_from_two_weight_code, code['M']] -cdef load_brouwer_database(): +cdef load_brouwer_database() noexcept: r""" Loads Andries Brouwer's database into _brouwer_database. """ diff --git a/src/sage/graphs/traversals.pxd b/src/sage/graphs/traversals.pxd index a81c72dcd9d..c9a8444be0c 100644 --- a/src/sage/graphs/traversals.pxd +++ b/src/sage/graphs/traversals.pxd @@ -5,4 +5,4 @@ cdef maximum_cardinality_search_M_short_digraph(short_digraph sd, int* alpha, int* alpha_inv, list F, - bint* X) + bint* X) noexcept diff --git a/src/sage/graphs/traversals.pyx b/src/sage/graphs/traversals.pyx index 8769f14f602..ae8518d3b25 100644 --- a/src/sage/graphs/traversals.pyx +++ b/src/sage/graphs/traversals.pyx @@ -107,7 +107,7 @@ def _is_valid_lex_BFS_order(G, L): return True -cdef lex_BFS_fast_short_digraph(short_digraph sd, uint32_t *sigma, uint32_t *pred): +cdef lex_BFS_fast_short_digraph(short_digraph sd, uint32_t *sigma, uint32_t *pred) noexcept: r""" Perform a lexicographic breadth first search (LexBFS) on the graph. @@ -1735,7 +1735,7 @@ def maximum_cardinality_search(G, reverse=False, tree=False, initial_vertex=None return alpha -cdef inline int swap(int* alpha, int* alpha_inv, int u, int new_pos_u): +cdef inline int swap(int* alpha, int* alpha_inv, int u, int new_pos_u) noexcept: """ Swap positions of u and v in alpha, where v is be the vertex occupying cell new_pos_u in alpha. @@ -1747,7 +1747,7 @@ cdef inline int swap(int* alpha, int* alpha_inv, int u, int new_pos_u): cdef maximum_cardinality_search_M_short_digraph(short_digraph sd, int initial_vertex, - int* alpha, int* alpha_inv, list F, bint* X): + int* alpha, int* alpha_inv, list F, bint* X) noexcept: r""" Compute the ordering and the edges of the triangulation produced by MCS-M. diff --git a/src/sage/graphs/trees.pxd b/src/sage/graphs/trees.pxd index eba4ce1ec1e..f2c81ab49a7 100644 --- a/src/sage/graphs/trees.pxd +++ b/src/sage/graphs/trees.pxd @@ -10,5 +10,5 @@ cdef class TreeIterator: cdef int r cdef int *l cdef int *current_level_sequence - cdef int generate_first_level_sequence(self) - cdef int generate_next_level_sequence(self) + cdef int generate_first_level_sequence(self) noexcept + cdef int generate_next_level_sequence(self) noexcept diff --git a/src/sage/graphs/trees.pyx b/src/sage/graphs/trees.pyx index 8dbf3493435..422fa28baa1 100644 --- a/src/sage/graphs/trees.pyx +++ b/src/sage/graphs/trees.pyx @@ -157,7 +157,7 @@ cdef class TreeIterator: return G - cdef int generate_first_level_sequence(self): + cdef int generate_first_level_sequence(self) noexcept: r""" Generates the level sequence representing the first tree with `n` vertices """ @@ -193,7 +193,7 @@ cdef class TreeIterator: return 0 - cdef int generate_next_level_sequence(self): + cdef int generate_next_level_sequence(self) noexcept: r""" Generates the level sequence representing the next tree with `n` vertices """ diff --git a/src/sage/graphs/weakly_chordal.pyx b/src/sage/graphs/weakly_chordal.pyx index 44c35e39dbe..d1a6b03ae5d 100644 --- a/src/sage/graphs/weakly_chordal.pyx +++ b/src/sage/graphs/weakly_chordal.pyx @@ -43,7 +43,7 @@ from sage.graphs.base.static_sparse_graph cimport free_short_digraph from sage.graphs.base.static_sparse_graph cimport out_degree -cdef inline int has_edge(bitset_t bs, int u, int v, int n): +cdef inline int has_edge(bitset_t bs, int u, int v, int n) noexcept: return bitset_in(bs, u * n + v) @@ -51,7 +51,7 @@ cdef inline is_long_hole_free_process(g, short_digraph sd, bitset_t dense_graph, list id_label, int* path, int* InPath, int* neighbor_index, set VisitedP3, bint certificate, - int a, int b, int c, int n): + int a, int b, int c, int n) noexcept: """ This method is part of method ``is_long_hole_free``. @@ -281,7 +281,7 @@ cdef inline is_long_antihole_free_process(g, short_digraph sd, bitset_t dense_gr list id_label, int* path, int* InPath, int* neighbor_index, set VisitedP3, bint certificate, - int a, int b, int c, int n): + int a, int b, int c, int n) noexcept: """ This method is part of method ``is_long_antihole_free``. diff --git a/src/sage/groups/libgap_wrapper.pxd b/src/sage/groups/libgap_wrapper.pxd index 0c43b098140..25599eea2a8 100644 --- a/src/sage/groups/libgap_wrapper.pxd +++ b/src/sage/groups/libgap_wrapper.pxd @@ -4,5 +4,5 @@ from sage.libs.gap.element cimport GapElement cdef class ElementLibGAP(MultiplicativeGroupElement): cdef GapElement _libgap - cpdef GapElement gap(self) - cpdef _mul_(self, other) + cpdef GapElement gap(self) noexcept + cpdef _mul_(self, other) noexcept diff --git a/src/sage/groups/libgap_wrapper.pyx b/src/sage/groups/libgap_wrapper.pyx index c65afa447e5..edcd50dfa4f 100644 --- a/src/sage/groups/libgap_wrapper.pyx +++ b/src/sage/groups/libgap_wrapper.pyx @@ -485,7 +485,7 @@ cdef class ElementLibGAP(MultiplicativeGroupElement): else: raise TypeError('need a libgap group element or "1" in constructor') - cpdef GapElement gap(self): + cpdef GapElement gap(self) noexcept: """ Return a LibGAP representation of the element. @@ -607,7 +607,7 @@ cdef class ElementLibGAP(MultiplicativeGroupElement): from sage.misc.latex import latex return latex(self._repr_()) - cpdef _mul_(left, right): + cpdef _mul_(left, right) noexcept: """ Multiplication of group elements @@ -629,7 +629,7 @@ cdef class ElementLibGAP(MultiplicativeGroupElement): return P.element_class(P, ( left)._libgap * ( right)._libgap) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ This method implements comparison. @@ -649,7 +649,7 @@ cdef class ElementLibGAP(MultiplicativeGroupElement): return richcmp((left)._libgap, (right)._libgap, op) - cpdef _div_(left, right): + cpdef _div_(left, right) noexcept: """ Division of group elements. diff --git a/src/sage/groups/matrix_gps/coxeter_group.py b/src/sage/groups/matrix_gps/coxeter_group.py index 27d65a55a37..6b865805298 100644 --- a/src/sage/groups/matrix_gps/coxeter_group.py +++ b/src/sage/groups/matrix_gps/coxeter_group.py @@ -253,11 +253,11 @@ def __init__(self, coxeter_matrix, base_ring, index_set): We check that :trac:`16630` is fixed:: sage: CoxeterGroup(['D',4], base_ring=QQ).category() - Category of finite irreducible coxeter groups + Category of finite irreducible Coxeter groups sage: # needs sage.rings.number_field sage: CoxeterGroup(['H',4], base_ring=QQbar).category() - Category of finite irreducible coxeter groups + Category of finite irreducible Coxeter groups sage: F = CoxeterGroups().Finite() sage: all(CoxeterGroup([letter,i]) in F ....: for i in range(2,5) for letter in ['A','B','D']) @@ -265,9 +265,9 @@ def __init__(self, coxeter_matrix, base_ring, index_set): sage: all(CoxeterGroup(['E',i]) in F for i in range(6,9)) True sage: CoxeterGroup(['F',4]).category() - Category of finite irreducible coxeter groups + Category of finite irreducible Coxeter groups sage: CoxeterGroup(['G',2]).category() - Category of finite irreducible coxeter groups + Category of finite irreducible Coxeter groups sage: all(CoxeterGroup(['H',i]) in F for i in range(3,5)) True sage: all(CoxeterGroup(['I',i]) in F for i in range(2,5)) diff --git a/src/sage/groups/matrix_gps/group_element.pxd b/src/sage/groups/matrix_gps/group_element.pxd index 36a5a9fc4ce..1b32eea3602 100644 --- a/src/sage/groups/matrix_gps/group_element.pxd +++ b/src/sage/groups/matrix_gps/group_element.pxd @@ -1,10 +1,10 @@ from sage.structure.element cimport MultiplicativeGroupElement, Element, MonoidElement, Matrix -cpdef is_MatrixGroupElement(x) +cpdef is_MatrixGroupElement(x) noexcept cdef class MatrixGroupElement_generic(MultiplicativeGroupElement): cdef public Matrix _matrix - cpdef _act_on_(self, x, bint self_on_left) - cpdef _mul_(self, other) - cpdef list list(self) + cpdef _act_on_(self, x, bint self_on_left) noexcept + cpdef _mul_(self, other) noexcept + cpdef list list(self) noexcept diff --git a/src/sage/groups/matrix_gps/group_element.pyx b/src/sage/groups/matrix_gps/group_element.pyx index 2764e33a7a8..d95fa0aa086 100644 --- a/src/sage/groups/matrix_gps/group_element.pyx +++ b/src/sage/groups/matrix_gps/group_element.pyx @@ -89,7 +89,7 @@ except ImportError: MatrixGroupElement_gap = () -cpdef is_MatrixGroupElement(x): +cpdef is_MatrixGroupElement(x) noexcept: """ Test whether ``x`` is a matrix group element @@ -222,7 +222,7 @@ cdef class MatrixGroupElement_generic(MultiplicativeGroupElement): """ return self._matrix._latex_() - cpdef _act_on_(self, x, bint self_on_left): + cpdef _act_on_(self, x, bint self_on_left) noexcept: """ EXAMPLES:: @@ -245,7 +245,7 @@ cdef class MatrixGroupElement_generic(MultiplicativeGroupElement): except TypeError: return None - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ EXAMPLES:: @@ -266,7 +266,7 @@ cdef class MatrixGroupElement_generic(MultiplicativeGroupElement): cdef MatrixGroupElement_generic y = other return richcmp(x._matrix, y._matrix, op) - cpdef list list(self): + cpdef list list(self) noexcept: """ Return list representation of this matrix. @@ -327,7 +327,7 @@ cdef class MatrixGroupElement_generic(MultiplicativeGroupElement): """ return self.matrix() - cpdef _mul_(self, other): + cpdef _mul_(self, other) noexcept: """ Return the product of ``self`` and`` other``, which must have identical parents. diff --git a/src/sage/groups/matrix_gps/group_element_gap.pxd b/src/sage/groups/matrix_gps/group_element_gap.pxd index e0ecbefea5c..2633f21892c 100644 --- a/src/sage/groups/matrix_gps/group_element_gap.pxd +++ b/src/sage/groups/matrix_gps/group_element_gap.pxd @@ -1,5 +1,5 @@ from sage.groups.libgap_wrapper cimport ElementLibGAP cdef class MatrixGroupElement_gap(ElementLibGAP): - cpdef _act_on_(self, x, bint self_on_left) - cpdef list list(self) + cpdef _act_on_(self, x, bint self_on_left) noexcept + cpdef list list(self) noexcept diff --git a/src/sage/groups/matrix_gps/group_element_gap.pyx b/src/sage/groups/matrix_gps/group_element_gap.pyx index b07c0f01a44..7c581377f6f 100644 --- a/src/sage/groups/matrix_gps/group_element_gap.pyx +++ b/src/sage/groups/matrix_gps/group_element_gap.pyx @@ -136,7 +136,7 @@ cdef class MatrixGroupElement_gap(ElementLibGAP): """ return self.matrix()._latex_() - cpdef _act_on_(self, x, bint self_on_left): + cpdef _act_on_(self, x, bint self_on_left) noexcept: """ EXAMPLES:: @@ -157,7 +157,7 @@ cdef class MatrixGroupElement_gap(ElementLibGAP): except TypeError: return None - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ EXAMPLES:: @@ -230,7 +230,7 @@ cdef class MatrixGroupElement_gap(ElementLibGAP): """ return self.matrix() - cpdef list list(self): + cpdef list list(self) noexcept: """ Return list representation of this matrix. diff --git a/src/sage/groups/perm_gps/partn_ref/automorphism_group_canonical_label.pxd b/src/sage/groups/perm_gps/partn_ref/automorphism_group_canonical_label.pxd index 5fe1ebd140d..573eeb83f58 100644 --- a/src/sage/groups/perm_gps/partn_ref/automorphism_group_canonical_label.pxd +++ b/src/sage/groups/perm_gps/partn_ref/automorphism_group_canonical_label.pxd @@ -19,9 +19,9 @@ cdef struct aut_gp_and_can_lab: StabilizerChain *group int *relabeling -cdef aut_gp_and_can_lab *allocate_agcl_output(int) +cdef aut_gp_and_can_lab *allocate_agcl_output(int) noexcept -cdef void deallocate_agcl_output(aut_gp_and_can_lab *) +cdef void deallocate_agcl_output(aut_gp_and_can_lab *) noexcept cdef struct agcl_work_space: int degree @@ -39,15 +39,15 @@ cdef struct agcl_work_space: OrbitPartition *orbits_of_permutation # degree n PartitionStack *first_ps # degree n -cdef agcl_work_space *allocate_agcl_work_space(int) +cdef agcl_work_space *allocate_agcl_work_space(int) noexcept -cdef void deallocate_agcl_work_space(agcl_work_space *) +cdef void deallocate_agcl_work_space(agcl_work_space *) noexcept cdef aut_gp_and_can_lab *get_aut_gp_and_can_lab( void *, PartitionStack *, int, - bint (*)(PartitionStack *, void *), - int (*)(PartitionStack *, void *, int *, int), - int (*)(int *, int *, void *, void *, int), bint, StabilizerChain *, + bint (*)(PartitionStack *, void *) noexcept, + int (*)(PartitionStack *, void *, int *, int) noexcept, + int (*)(int *, int *, void *, void *, int) noexcept, bint, StabilizerChain *, agcl_work_space *, aut_gp_and_can_lab *) except NULL diff --git a/src/sage/groups/perm_gps/partn_ref/automorphism_group_canonical_label.pyx b/src/sage/groups/perm_gps/partn_ref/automorphism_group_canonical_label.pyx index 04d978afef3..920ff69c3df 100644 --- a/src/sage/groups/perm_gps/partn_ref/automorphism_group_canonical_label.pyx +++ b/src/sage/groups/perm_gps/partn_ref/automorphism_group_canonical_label.pyx @@ -116,7 +116,7 @@ from cysignals.memory cimport sig_malloc, sig_realloc, sig_free from .data_structures cimport * from sage.data_structures.bitset_base cimport * -cdef inline int agcl_cmp(int a, int b): +cdef inline int agcl_cmp(int a, int b) noexcept: if a < b: return -1 elif a == b: @@ -126,13 +126,13 @@ cdef inline int agcl_cmp(int a, int b): # Functions -cdef bint all_children_are_equivalent_trivial(PartitionStack *PS, void *S): +cdef bint all_children_are_equivalent_trivial(PartitionStack *PS, void *S) noexcept: return 0 -cdef int refine_and_return_invariant_trivial(PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len): +cdef int refine_and_return_invariant_trivial(PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len) noexcept: return 0 -cdef int compare_structures_trivial(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree): +cdef int compare_structures_trivial(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree) noexcept: return 0 def test_get_aut_gp_and_can_lab_trivially(int n=6, @@ -212,7 +212,7 @@ def test_intersect_parabolic_with_alternating(int n=9, list partition=[[0,1,2],[ SC_dealloc(group) deallocate_agcl_output(output) -cdef int compare_perms(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree): +cdef int compare_perms(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree) noexcept: cdef list MS1 = S1 cdef list MS2 = S2 cdef int i, j @@ -293,7 +293,7 @@ def coset_rep(list perm=[0,1,2,3,4,5], list gens=[[1,2,3,4,5,0]]): sig_free(c_perm) return label -cdef aut_gp_and_can_lab *allocate_agcl_output(int n): +cdef aut_gp_and_can_lab *allocate_agcl_output(int n) noexcept: r""" Allocate an instance of the aut_gp_and_can_lab struct of degree n. This can be input to the get_aut_gp_and_can_lab function, and the output will be @@ -313,7 +313,7 @@ cdef aut_gp_and_can_lab *allocate_agcl_output(int n): return NULL return output -cdef void deallocate_agcl_output(aut_gp_and_can_lab *output): +cdef void deallocate_agcl_output(aut_gp_and_can_lab *output) noexcept: r""" Deallocates an aut_gp_and_can_lab struct. """ @@ -323,7 +323,7 @@ cdef void deallocate_agcl_output(aut_gp_and_can_lab *output): sig_free(output.generators) sig_free(output) -cdef agcl_work_space *allocate_agcl_work_space(int n): +cdef agcl_work_space *allocate_agcl_work_space(int n) noexcept: r""" Allocates work space for the get_aut_gp_and_can_lab function. It can be input to the function in which case it must be deallocated after the @@ -375,7 +375,7 @@ cdef agcl_work_space *allocate_agcl_work_space(int n): return NULL return work_space -cdef void deallocate_agcl_work_space(agcl_work_space *work_space): +cdef void deallocate_agcl_work_space(agcl_work_space *work_space) noexcept: r""" Deallocate work space for the get_aut_gp_and_can_lab function. """ @@ -397,11 +397,11 @@ cdef void deallocate_agcl_work_space(agcl_work_space *work_space): cdef aut_gp_and_can_lab *get_aut_gp_and_can_lab(void *S, PartitionStack *partition, int n, - bint (*all_children_are_equivalent)(PartitionStack *PS, void *S), + bint (*all_children_are_equivalent)(PartitionStack *PS, void *S) noexcept, int (*refine_and_return_invariant)(PartitionStack *PS, void *S, - int *cells_to_refine_by, int ctrb_len), + int *cells_to_refine_by, int ctrb_len) noexcept, int (*compare_structures)(int *gamma_1, int *gamma_2, void *S1, void *S2, - int degree), + int degree) noexcept, bint canonical_label, StabilizerChain *input_group, agcl_work_space *work_space_prealloc, aut_gp_and_can_lab *output_prealloc) except NULL: """ diff --git a/src/sage/groups/perm_gps/partn_ref/canonical_augmentation.pxd b/src/sage/groups/perm_gps/partn_ref/canonical_augmentation.pxd index dfcf347df4c..daa7a59b2b6 100644 --- a/src/sage/groups/perm_gps/partn_ref/canonical_augmentation.pxd +++ b/src/sage/groups/perm_gps/partn_ref/canonical_augmentation.pxd @@ -29,7 +29,7 @@ from .double_coset cimport (double_coset, cdef struct iterator: void *data - void *(*next)(void *data, int *degree, bint *mem_err) + void *(*next)(void *data, int *degree, bint *mem_err) noexcept cdef struct canonical_generator_data: StabilizerChain *group @@ -52,33 +52,33 @@ cdef struct canonical_generator_data: bint dealloc bint pr - bint (*all_children_are_equivalent)(PartitionStack *, void *) - int (*refine_and_return_invariant)(PartitionStack *, void *, int *, int) - int (*compare_structures)(int *, int *, void *, void *, int) + bint (*all_children_are_equivalent)(PartitionStack *, void *) noexcept + int (*refine_and_return_invariant)(PartitionStack *, void *, int *, int) noexcept + int (*compare_structures)(int *, int *, void *, void *, int) noexcept - int (*generate_children)(void *, aut_gp_and_can_lab *, iterator *) - void *(*apply_augmentation)(void *, void *, void *, int *, bint *) - void (*free_object)(void *) - void (* free_iter_data)(void *) - void (*free_aug)(void *) - void *(*canonical_parent)(void *child, void *parent, int *permutation, int *degree, bint *) + int (*generate_children)(void *, aut_gp_and_can_lab *, iterator *) noexcept + void *(*apply_augmentation)(void *, void *, void *, int *, bint *) noexcept + void (*free_object)(void *) noexcept + void (* free_iter_data)(void *) noexcept + void (*free_aug)(void *) noexcept + void *(*canonical_parent)(void *child, void *parent, int *permutation, int *degree, bint *) noexcept -cdef canonical_generator_data *allocate_cgd(int, int) +cdef canonical_generator_data *allocate_cgd(int, int) noexcept -cdef void deallocate_cgd(canonical_generator_data *) +cdef void deallocate_cgd(canonical_generator_data *) noexcept -cdef void *canonical_generator_next(void *, int *, bint *) +cdef void *canonical_generator_next(void *, int *, bint *) noexcept cdef iterator *setup_canonical_generator(int degree, - bint (*all_children_are_equivalent)(PartitionStack *, void *), - int (*refine_and_return_invariant)(PartitionStack *, void *, int *, int), - int (*compare_structures)(int *, int *, void *, void *, int), - int (*generate_children)(void *, aut_gp_and_can_lab *, iterator *), - void *(*apply_augmentation)(void *, void *, void *, int *, bint *), - void (*free_object)(void *), - void (* free_iter_data)(void *), - void (*free_aug)(void *), - void *(*canonical_parent)(void *, void *, int *, int *, bint *), + bint (*all_children_are_equivalent)(PartitionStack *, void *) noexcept, + int (*refine_and_return_invariant)(PartitionStack *, void *, int *, int) noexcept, + int (*compare_structures)(int *, int *, void *, void *, int) noexcept, + int (*generate_children)(void *, aut_gp_and_can_lab *, iterator *) noexcept, + void *(*apply_augmentation)(void *, void *, void *, int *, bint *) noexcept, + void (*free_object)(void *) noexcept, + void (* free_iter_data)(void *) noexcept, + void (*free_aug)(void *) noexcept, + void *(*canonical_parent)(void *, void *, int *, int *, bint *) noexcept, int max_depth, bint reduce_children, iterator *cangen_prealloc) except NULL diff --git a/src/sage/groups/perm_gps/partn_ref/canonical_augmentation.pyx b/src/sage/groups/perm_gps/partn_ref/canonical_augmentation.pyx index 680dbf5675d..a8a25050413 100644 --- a/src/sage/groups/perm_gps/partn_ref/canonical_augmentation.pyx +++ b/src/sage/groups/perm_gps/partn_ref/canonical_augmentation.pyx @@ -172,7 +172,7 @@ from cysignals.memory cimport sig_malloc, sig_free from .data_structures cimport* -cdef void *canonical_generator_next(void *can_gen_data, int *degree, bint *mem_err): +cdef void *canonical_generator_next(void *can_gen_data, int *degree, bint *mem_err) noexcept: r""" This function is part of the iterator struct which will iterate over objects. Return value of ``NULL`` indicates termination. @@ -281,7 +281,7 @@ cdef void *canonical_generator_next(void *can_gen_data, int *degree, bint *mem_e cgd.level -= 1 return cgd.object_stack[cgd.level] -cdef canonical_generator_data *allocate_cgd(int max_depth, int degree): +cdef canonical_generator_data *allocate_cgd(int max_depth, int degree) noexcept: r""" Allocate the data part of the canonical generation iterator struct. """ @@ -341,7 +341,7 @@ cdef canonical_generator_data *allocate_cgd(int max_depth, int degree): return cgd -cdef void deallocate_cgd(canonical_generator_data *cgd): +cdef void deallocate_cgd(canonical_generator_data *cgd) noexcept: r""" Deallocate the data part of the canonical generation iterator struct. """ @@ -378,17 +378,17 @@ cdef void deallocate_cgd(canonical_generator_data *cgd): cdef iterator *setup_canonical_generator(int degree, - bint (*all_children_are_equivalent)(PartitionStack *PS, void *S), + bint (*all_children_are_equivalent)(PartitionStack *PS, void *S) noexcept, int (*refine_and_return_invariant)(PartitionStack *PS, void *S, - int *cells_to_refine_by, int ctrb_len), + int *cells_to_refine_by, int ctrb_len) noexcept, int (*compare_structures)(int *gamma_1, int *gamma_2, void *S1, void *S2, - int degree), - int (*generate_children)(void *, aut_gp_and_can_lab *, iterator *), - void *(*apply_augmentation)(void *, void *, void *, int *, bint *), - void (*free_object)(void *), - void (*free_iter_data)(void *), - void (*free_aug)(void *), - void *(*canonical_parent)(void *child, void *parent, int *permutation, int *degree, bint *mem_err), + int degree) noexcept, + int (*generate_children)(void *, aut_gp_and_can_lab *, iterator *) noexcept, + void *(*apply_augmentation)(void *, void *, void *, int *, bint *) noexcept, + void (*free_object)(void *) noexcept, + void (*free_iter_data)(void *) noexcept, + void (*free_aug)(void *) noexcept, + void *(*canonical_parent)(void *child, void *parent, int *permutation, int *degree, bint *mem_err) noexcept, int max_depth, bint reduce_children, iterator *cangen_prealloc) except NULL: """ Canonical generation of isomorphism classes of objects. diff --git a/src/sage/groups/perm_gps/partn_ref/data_structures.pxd b/src/sage/groups/perm_gps/partn_ref/data_structures.pxd index 8c5ae14b5bb..4c7152e5d6d 100644 --- a/src/sage/groups/perm_gps/partn_ref/data_structures.pxd +++ b/src/sage/groups/perm_gps/partn_ref/data_structures.pxd @@ -68,11 +68,11 @@ cdef struct StabilizerChain: # OrbitPartition (OP) -cdef OrbitPartition *OP_new(int n) +cdef OrbitPartition *OP_new(int n) noexcept -cdef void OP_dealloc(OrbitPartition *OP) +cdef void OP_dealloc(OrbitPartition *OP) noexcept -cdef inline int OP_copy_from_to(OrbitPartition *OP, OrbitPartition *OP2): +cdef inline int OP_copy_from_to(OrbitPartition *OP, OrbitPartition *OP2) noexcept: """ Copy all data from OP to OP2, we suppose that @@ -81,7 +81,7 @@ cdef inline int OP_copy_from_to(OrbitPartition *OP, OrbitPartition *OP2): """ memcpy(OP2.parent, OP.parent, 4*OP.degree * sizeof(int) ) -cdef inline OrbitPartition *OP_copy(OrbitPartition *OP): +cdef inline OrbitPartition *OP_copy(OrbitPartition *OP) noexcept: """ Allocate and return a pointer to a copy of a OrbitPartition of degree n. @@ -95,9 +95,9 @@ cdef inline OrbitPartition *OP_copy(OrbitPartition *OP): OP_copy_from_to(OP, OP2) return OP2 -cdef OP_string(OrbitPartition *OP) +cdef OP_string(OrbitPartition *OP) noexcept -cdef inline void OP_clear(OrbitPartition *OP): +cdef inline void OP_clear(OrbitPartition *OP) noexcept: cdef int i, n = OP.degree for i from 0 <= i < n: OP.parent[i] = i @@ -105,7 +105,7 @@ cdef inline void OP_clear(OrbitPartition *OP): OP.mcr[i] = i OP.size[i] = 1 -cdef inline int OP_find(OrbitPartition *OP, int n): +cdef inline int OP_find(OrbitPartition *OP, int n) noexcept: """ Report the representative ("root") of the cell which contains n. """ @@ -115,7 +115,7 @@ cdef inline int OP_find(OrbitPartition *OP, int n): OP.parent[n] = OP_find(OP, OP.parent[n]) return OP.parent[n] -cdef inline int OP_join(OrbitPartition *OP, int m, int n): +cdef inline int OP_join(OrbitPartition *OP, int m, int n) noexcept: """ Join the cells containing m and n, if they are different. """ @@ -137,7 +137,7 @@ cdef inline int OP_join(OrbitPartition *OP, int m, int n): if m_root != n_root: OP.num_cells -= 1 -cdef inline int OP_merge_list_perm(OrbitPartition *OP, int *gamma): +cdef inline int OP_merge_list_perm(OrbitPartition *OP, int *gamma) noexcept: """ Joins the cells of OP which intersect the same orbit of gamma. @@ -162,7 +162,7 @@ cdef inline int OP_merge_list_perm(OrbitPartition *OP, int *gamma): # PartitionStack (PS) -cdef inline int PS_copy_from_to(PartitionStack *PS, PartitionStack *PS2): +cdef inline int PS_copy_from_to(PartitionStack *PS, PartitionStack *PS2) noexcept: """ Copy all data from PS to PS2. """ @@ -170,7 +170,7 @@ cdef inline int PS_copy_from_to(PartitionStack *PS, PartitionStack *PS2): PS2.degree = PS.degree memcpy(PS2.entries, PS.entries, 2*PS.degree * sizeof(int) ) -cdef inline bint PS_is_discrete(PartitionStack *PS): +cdef inline bint PS_is_discrete(PartitionStack *PS) noexcept: """ Returns whether the deepest partition consists only of singleton cells. """ @@ -180,7 +180,7 @@ cdef inline bint PS_is_discrete(PartitionStack *PS): return 0 return 1 -cdef inline int PS_num_cells(PartitionStack *PS): +cdef inline int PS_num_cells(PartitionStack *PS) noexcept: """ Returns the number of cells. """ @@ -190,7 +190,7 @@ cdef inline int PS_num_cells(PartitionStack *PS): ncells += 1 return ncells -cdef inline void PS_move_min_to_front(PartitionStack *PS, int start, int end): +cdef inline void PS_move_min_to_front(PartitionStack *PS, int start, int end) noexcept: """ Makes sure that the first element of the segment of entries i with start <= i <= end is minimal. @@ -204,20 +204,20 @@ cdef inline void PS_move_min_to_front(PartitionStack *PS, int start, int end): PS.entries[min_loc] = PS.entries[start] PS.entries[start] = minimum -cdef inline bint PS_is_mcr(PartitionStack *PS, int m): +cdef inline bint PS_is_mcr(PartitionStack *PS, int m) noexcept: """ Returns whether PS.elements[m] (not m!) is the smallest element of its cell. """ return m == 0 or PS.levels[m-1] <= PS.depth -cdef inline bint PS_is_fixed(PartitionStack *PS, int m): +cdef inline bint PS_is_fixed(PartitionStack *PS, int m) noexcept: """ Returns whether PS.elements[m] (not m!) is in a singleton cell, assuming PS_is_mcr(PS, m) is already true. """ return PS.levels[m] <= PS.depth -cdef inline int PS_clear(PartitionStack *PS): +cdef inline int PS_clear(PartitionStack *PS) noexcept: """ Sets the current partition to the first shallower one, i.e. forgets about boundaries between cells that are new to the current level. @@ -230,7 +230,7 @@ cdef inline int PS_clear(PartitionStack *PS): PS_move_min_to_front(PS, cur_start, i) cur_start = i+1 -cdef inline int PS_move_all_mins_to_front(PartitionStack *PS): +cdef inline int PS_move_all_mins_to_front(PartitionStack *PS) noexcept: """ Move minimal cell elements to the front of each cell. """ @@ -240,7 +240,7 @@ cdef inline int PS_move_all_mins_to_front(PartitionStack *PS): PS_move_min_to_front(PS, cur_start, i) cur_start = i+1 -cdef inline int PS_get_perm_from(PartitionStack *PS1, PartitionStack *PS2, int *gamma): +cdef inline int PS_get_perm_from(PartitionStack *PS1, PartitionStack *PS2, int *gamma) noexcept: """ Store the permutation determined by PS2[i] -> PS1[i] for each i, where PS[i] denotes the entry of the ith cell of the discrete partition PS. @@ -249,25 +249,25 @@ cdef inline int PS_get_perm_from(PartitionStack *PS1, PartitionStack *PS2, int * for i from 0 <= i < PS1.degree: gamma[PS2.entries[i]] = PS1.entries[i] -cdef PartitionStack *PS_new(int n, bint unit_partition) +cdef PartitionStack *PS_new(int n, bint unit_partition) noexcept -cdef PartitionStack *PS_copy(PartitionStack *PS) +cdef PartitionStack *PS_copy(PartitionStack *PS) noexcept -cdef void PS_dealloc(PartitionStack *PS) +cdef void PS_dealloc(PartitionStack *PS) noexcept -cdef PS_print(PartitionStack *PS) +cdef PS_print(PartitionStack *PS) noexcept -cdef void PS_unit_partition(PartitionStack *PS) +cdef void PS_unit_partition(PartitionStack *PS) noexcept -cdef int PS_first_smallest(PartitionStack *PS, bitset_t b, int *second_pos=?) +cdef int PS_first_smallest(PartitionStack *PS, bitset_t b, int *second_pos=?) noexcept -cdef PartitionStack *PS_from_list(list L) +cdef PartitionStack *PS_from_list(list L) noexcept -cdef list PS_singletons(PartitionStack * part) +cdef list PS_singletons(PartitionStack * part) noexcept -cdef int PS_all_new_cells(PartitionStack *PS, bitset_t** nonsingletons_ptr) +cdef int PS_all_new_cells(PartitionStack *PS, bitset_t** nonsingletons_ptr) noexcept -cdef inline bint stacks_are_equivalent(PartitionStack *PS1, PartitionStack *PS2): +cdef inline bint stacks_are_equivalent(PartitionStack *PS1, PartitionStack *PS2) noexcept: cdef int i, j, depth = min(PS1.depth, PS2.depth) for i from 0 <= i < PS1.degree: if PS1.levels[i] == PS2.levels[i]: @@ -277,9 +277,9 @@ cdef inline bint stacks_are_equivalent(PartitionStack *PS1, PartitionStack *PS2) return 0 return 1 -cdef int sort_by_function(PartitionStack *PS, int start, int *degrees) +cdef int sort_by_function(PartitionStack *PS, int start, int *degrees) noexcept -cdef inline int PS_split_point(PartitionStack *PS, int v): +cdef inline int PS_split_point(PartitionStack *PS, int v) noexcept: """ Detaches the point v from the cell it is in, putting the singleton cell of just v in front. Returns the position where v is now located. @@ -312,8 +312,8 @@ cdef inline int PS_split_point(PartitionStack *PS, int v): cdef inline int split_point_and_refine(PartitionStack *PS, int v, void *S, int (*refine_and_return_invariant) - (PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len), - int *cells_to_refine_by): + (PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len) noexcept, + int *cells_to_refine_by) noexcept: """ Make the partition stack one longer by copying the last partition in the stack, split off a given point, and refine. Return the invariant given by @@ -337,24 +337,24 @@ cdef inline int split_point_and_refine(PartitionStack *PS, int v, void *S, # StabilizerChain (SC) -cdef StabilizerChain *SC_new(int n, bint init_gens=?) +cdef StabilizerChain *SC_new(int n, bint init_gens=?) noexcept -cdef int SC_realloc_gens(StabilizerChain *SC, int level, int size) +cdef int SC_realloc_gens(StabilizerChain *SC, int level, int size) noexcept -cdef void SC_dealloc(StabilizerChain *SC) +cdef void SC_dealloc(StabilizerChain *SC) noexcept cdef int SC_copy_nomalloc(StabilizerChain *SC_dest, StabilizerChain *SC, - int level) + int level) noexcept -cdef StabilizerChain *SC_alternating_group(int n) +cdef StabilizerChain *SC_alternating_group(int n) noexcept cdef int SC_insert_and_sift(StabilizerChain *SC, int level, int *pi, - int num_perms, bint sift) + int num_perms, bint sift) noexcept cdef int SC_insert_base_point_nomalloc(StabilizerChain *SC_dest, - StabilizerChain *SC, int level, int p) + StabilizerChain *SC, int level, int p) noexcept -cdef inline int SC_perm_is_identity(int *perm, int degree): +cdef inline int SC_perm_is_identity(int *perm, int degree) noexcept: for i from 0 <= i < degree: if perm[i] != i: break @@ -362,7 +362,7 @@ cdef inline int SC_perm_is_identity(int *perm, int degree): return 1 return 0 -cdef inline void SC_mult_perms(int *out, int *first, int *second, int degree): +cdef inline void SC_mult_perms(int *out, int *first, int *second, int degree) noexcept: """ DON'T DO THIS WITH out == second! """ @@ -370,7 +370,7 @@ cdef inline void SC_mult_perms(int *out, int *first, int *second, int degree): for i from 0 <= i < degree: out[i] = second[first[i]] -cdef inline void SC_invert_perm(int *out, int *input, int degree): +cdef inline void SC_invert_perm(int *out, int *input, int degree) noexcept: """ DON'T DO THIS WITH out == in! """ @@ -378,12 +378,12 @@ cdef inline void SC_invert_perm(int *out, int *input, int degree): for i from 0 <= i < degree: out[input[i]] = i -cdef inline void SC_identify(int *perm, int degree): +cdef inline void SC_identify(int *perm, int degree) noexcept: cdef int i for i from 0 <= i < degree: perm[i] = i -cdef inline void SC_add_base_point(StabilizerChain *SC, int b): +cdef inline void SC_add_base_point(StabilizerChain *SC, int b) noexcept: """ Adds base point b to the end of SC. Assumes b is not already in the base. """ @@ -397,7 +397,7 @@ cdef inline void SC_add_base_point(StabilizerChain *SC, int b): SC.labels[SC.base_size][b] = 0 SC.base_size += 1 -cdef inline int SC_cleanup(StabilizerChain *SC): +cdef inline int SC_cleanup(StabilizerChain *SC) noexcept: """ Remove redundant base elements from SC. @@ -423,7 +423,7 @@ cdef inline int SC_cleanup(StabilizerChain *SC): SC.base_size = new return (old == new) -cdef inline void SC_compose_up_to_base(StabilizerChain *SC, int level, int x, int *perm): +cdef inline void SC_compose_up_to_base(StabilizerChain *SC, int level, int x, int *perm) noexcept: """ Repeatedly compose the given perm by labels on the Schreier tree, starting with x, until the base is reached. The composition is stored to perm. @@ -442,7 +442,7 @@ cdef inline void SC_compose_up_to_base(StabilizerChain *SC, int level, int x, in x = SC.parents[level][x] SC_mult_perms(perm, perm, label, n) -cdef inline void SC_scan(StabilizerChain *SC, int level, int x, int gen_index, int *gen, int sign): +cdef inline void SC_scan(StabilizerChain *SC, int level, int x, int gen_index, int *gen, int sign) noexcept: """ See whether the point x is moved to a point outside the tree by gen, and if so add it to the tree (arc label is gen_inv). @@ -459,7 +459,7 @@ cdef inline void SC_scan(StabilizerChain *SC, int level, int x, int gen_index, i SC.parents[level][y] = x SC.labels[level][y] = sign*(gen_index+1) -cdef inline int SC_insert(StabilizerChain *SC, int level, int *pi, int num_perms): +cdef inline int SC_insert(StabilizerChain *SC, int level, int *pi, int num_perms) noexcept: """ Add permutations in pi to the stabilizer chain. The array pi is a sequence of num_perms permutations, each in list representation, hence pi should be @@ -476,10 +476,10 @@ cdef inline int SC_insert(StabilizerChain *SC, int level, int *pi, int num_perms """ return SC_insert_and_sift(SC, level, pi, num_perms, 1) -cdef inline int SC_update_tree(StabilizerChain *SC, int level, int *pi, int num_perms): +cdef inline int SC_update_tree(StabilizerChain *SC, int level, int *pi, int num_perms) noexcept: return SC_insert_and_sift(SC, level, pi, num_perms, 0) -cdef inline void SC_order(StabilizerChain *SC, int i, mpz_t order): +cdef inline void SC_order(StabilizerChain *SC, int i, mpz_t order) noexcept: """ Gives the order of the stabilizer of base points up to but not including the i-th, storing it to ``order``, which must be already initialized. @@ -491,7 +491,7 @@ cdef inline void SC_order(StabilizerChain *SC, int i, mpz_t order): for k from i <= k < SC.base_size: mpz_mul_si(order, order, SC.orbit_sizes[k]) -cdef inline bint SC_contains(StabilizerChain *SC, int level, int *pi, bint modify): +cdef inline bint SC_contains(StabilizerChain *SC, int level, int *pi, bint modify) noexcept: """ Test whether pi is in the level-th stabilizer. @@ -514,7 +514,7 @@ cdef inline bint SC_contains(StabilizerChain *SC, int level, int *pi, bint modif SC_compose_up_to_base(SC, i, x, perm) return SC_perm_is_identity(perm, n) -cdef inline void SC_random_element(StabilizerChain *SC, int level, int *perm): +cdef inline void SC_random_element(StabilizerChain *SC, int level, int *perm) noexcept: """ Gives a random element of the level-th stabilizer. For a random element of the whole group, set level to 0. Must have level < SC.base_size. @@ -527,10 +527,10 @@ cdef inline void SC_random_element(StabilizerChain *SC, int level, int *perm): cdef int compute_relabeling(StabilizerChain *group, StabilizerChain *scratch_group, - int *permutation, int *relabeling) + int *permutation, int *relabeling) noexcept cdef inline void update_perm_stack(StabilizerChain *group, int level, int point, - int *perm_stack): + int *perm_stack) noexcept: """ Ensure that perm_stack[level] is gamma_0^{-1}...gamma_{level-1}^{-1}, where each gamma_i represents the coset representative at the ith level determined @@ -545,8 +545,8 @@ cdef inline void update_perm_stack(StabilizerChain *group, int level, int point, cdef inline int split_point_and_refine_by_orbits(PartitionStack *PS, int v, void *S, int (*refine_and_return_invariant) - (PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len), - int *cells_to_refine_by, StabilizerChain *SC, int *perm_stack): + (PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len) noexcept, + int *cells_to_refine_by, StabilizerChain *SC, int *perm_stack) noexcept: """ """ PS.depth += 1 PS_clear(PS) @@ -555,12 +555,12 @@ cdef inline int split_point_and_refine_by_orbits(PartitionStack *PS, int v, return refine_also_by_orbits(PS, S, refine_and_return_invariant, cells_to_refine_by, 1, SC, perm_stack) cdef int refine_by_orbits(PartitionStack *PS, StabilizerChain *SC, - int *perm_stack, int *cells_to_refine_by, int *ctrb_len) + int *perm_stack, int *cells_to_refine_by, int *ctrb_len) noexcept cdef inline int refine_also_by_orbits(PartitionStack *PS, void *S, int (*refine_and_return_invariant) - (PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len), - int *cells_to_refine_by, int ctrb_len, StabilizerChain *SC, int *perm_stack): + (PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len) noexcept, + int *cells_to_refine_by, int ctrb_len, StabilizerChain *SC, int *perm_stack) noexcept: """ """ cdef int inv inv = refine_by_orbits(PS, SC, perm_stack, cells_to_refine_by, &ctrb_len) diff --git a/src/sage/groups/perm_gps/partn_ref/data_structures.pyx b/src/sage/groups/perm_gps/partn_ref/data_structures.pyx index 285c1afd1eb..02a74f5c676 100644 --- a/src/sage/groups/perm_gps/partn_ref/data_structures.pyx +++ b/src/sage/groups/perm_gps/partn_ref/data_structures.pyx @@ -40,7 +40,7 @@ from sage.arith.misc import is_prime as n_is_prime # OrbitPartition (OP) -cdef inline OrbitPartition *OP_new(int n): +cdef inline OrbitPartition *OP_new(int n) noexcept: """ Allocate and return a pointer to a new OrbitPartition of degree n. Returns a null pointer in the case of an allocation failure. @@ -61,12 +61,12 @@ cdef inline OrbitPartition *OP_new(int n): OP_clear(OP) return OP -cdef inline void OP_dealloc(OrbitPartition *OP): +cdef inline void OP_dealloc(OrbitPartition *OP) noexcept: if OP is not NULL: sig_free(OP.parent) sig_free(OP) -cdef OP_string(OrbitPartition *OP): +cdef OP_string(OrbitPartition *OP) noexcept: """ Return a string representation of the OrbitPartition. """ @@ -179,7 +179,7 @@ def OP_represent(int n, merges, perm): # PartitionStack (PS) -cdef inline PartitionStack *PS_new(int n, bint unit_partition): +cdef inline PartitionStack *PS_new(int n, bint unit_partition) noexcept: """ Allocate and return a pointer to a new PartitionStack of degree n. Returns a null pointer in the case of an allocation failure. @@ -199,7 +199,7 @@ cdef inline PartitionStack *PS_new(int n, bint unit_partition): PS_unit_partition(PS) return PS -cdef void PS_unit_partition(PartitionStack *PS): +cdef void PS_unit_partition(PartitionStack *PS) noexcept: """ Set partition stack to a single partition with a single cell. """ @@ -211,7 +211,7 @@ cdef void PS_unit_partition(PartitionStack *PS): PS.entries[n-1] = n - 1 PS.levels[n-1] = -1 -cdef inline PartitionStack *PS_copy(PartitionStack *PS): +cdef inline PartitionStack *PS_copy(PartitionStack *PS) noexcept: """ Allocate and return a pointer to a copy of PartitionStack PS. Returns a null pointer in the case of an allocation failure. @@ -230,12 +230,12 @@ cdef inline PartitionStack *PS_copy(PartitionStack *PS): PS_copy_from_to(PS, PS2) return PS2 -cdef inline void PS_dealloc(PartitionStack *PS): +cdef inline void PS_dealloc(PartitionStack *PS) noexcept: if PS is not NULL: sig_free(PS.entries) sig_free(PS) -cdef PartitionStack *PS_from_list(list L): +cdef PartitionStack *PS_from_list(list L) noexcept: """ Allocate and return a pointer to a PartitionStack representing L. Returns a null pointer in the case of an allocation failure. @@ -260,7 +260,7 @@ cdef PartitionStack *PS_from_list(list L): PS.degree = n return PS -cdef PS_print(PartitionStack *PS): +cdef PS_print(PartitionStack *PS) noexcept: """ Print a visual representation of PS. """ @@ -268,7 +268,7 @@ cdef PS_print(PartitionStack *PS): for i in range(PS.depth + 1): PS_print_partition(PS, i) -cdef PS_print_partition(PartitionStack *PS, int k): +cdef PS_print_partition(PartitionStack *PS, int k) noexcept: """ Print the partition at depth k. """ @@ -282,7 +282,7 @@ cdef PS_print_partition(PartitionStack *PS, int k): s = s[:-1] + ')' print(s) -cdef int PS_first_smallest(PartitionStack *PS, bitset_t b, int *second_pos=NULL): +cdef int PS_first_smallest(PartitionStack *PS, bitset_t b, int *second_pos=NULL) noexcept: """ Find the first occurrence of the smallest cell of size greater than one, which is admissible (checked by the function ``test_allowance``). @@ -317,7 +317,7 @@ cdef int PS_first_smallest(PartitionStack *PS, bitset_t b, int *second_pos=NULL) return PS.entries[location] -cdef int PS_all_new_cells(PartitionStack *PS, bitset_t** nonsingletons_ptr): +cdef int PS_all_new_cells(PartitionStack *PS, bitset_t** nonsingletons_ptr) noexcept: """ Suppose a cell ``C`` was split into ``a`` components at ``PS.level``. Set the rows of the matrix ``nonsingletons_ptr`` to the first @@ -381,7 +381,7 @@ cdef int PS_find_element(PartitionStack *PS, bitset_t b, int x) except -1: i += 1 return location -cdef list PS_singletons(PartitionStack * part): +cdef list PS_singletons(PartitionStack * part) noexcept: """ Return the list of all singletons in the PartitionStack. """ @@ -550,7 +550,7 @@ cdef enum: default_num_gens = 8 default_num_bits = 64 -cdef StabilizerChain *SC_new(int n, bint init_gens=True): +cdef StabilizerChain *SC_new(int n, bint init_gens=True) noexcept: """ Allocate and return a pointer to a new StabilizerChain of degree n. Returns a null pointer in the case of an allocation failure. @@ -620,7 +620,7 @@ cdef StabilizerChain *SC_new(int n, bint init_gens=True): return SC -cdef inline int SC_realloc_gens(StabilizerChain *SC, int level, int size): +cdef inline int SC_realloc_gens(StabilizerChain *SC, int level, int size) noexcept: """ Reallocate generator array at level `level` to size `size`. @@ -642,7 +642,7 @@ cdef inline int SC_realloc_gens(StabilizerChain *SC, int level, int size): SC.array_size[level] = size return 0 -cdef inline void SC_dealloc(StabilizerChain *SC): +cdef inline void SC_dealloc(StabilizerChain *SC) noexcept: cdef int i, n if SC is not NULL: n = SC.degree @@ -657,7 +657,7 @@ cdef inline void SC_dealloc(StabilizerChain *SC): OP_dealloc(SC.OP_scratch) sig_free(SC) -cdef StabilizerChain *SC_symmetric_group(int n): +cdef StabilizerChain *SC_symmetric_group(int n) noexcept: """ Returns a stabilizer chain for the symmetric group on {0, 1, ..., n-1}. @@ -698,7 +698,7 @@ cdef StabilizerChain *SC_symmetric_group(int n): memcpy(SC.gen_inverses[i] + n*j, SC.generators[i] + n*j, n * sizeof(int) ) return SC -cdef StabilizerChain *SC_alternating_group(int n): +cdef StabilizerChain *SC_alternating_group(int n) noexcept: """ Returns a stabilizer chain for the alternating group on {0, 1, ..., n-1}. @@ -742,7 +742,7 @@ cdef StabilizerChain *SC_alternating_group(int n): SC_invert_perm(SC.gen_inverses[i] + n*j, SC.generators[i] + n*j, n) return SC -cdef int SC_realloc_bitsets(StabilizerChain *SC, unsigned long size): +cdef int SC_realloc_bitsets(StabilizerChain *SC, unsigned long size) noexcept: """ If size is larger than current allocation, double the size of the bitsets until it is not. @@ -776,7 +776,7 @@ cdef int SC_realloc_bitsets(StabilizerChain *SC, unsigned long size): memset(SC.gen_is_id.bits + (size_old >> index_shift) + 1, 0, (limbs - (size_old >> index_shift) - 1) * sizeof(unsigned long)) return 0 -cdef StabilizerChain *SC_copy(StabilizerChain *SC, int level): +cdef StabilizerChain *SC_copy(StabilizerChain *SC, int level) noexcept: """ Creates a copy of the first `level` levels of SC. Must have 0 < level. @@ -804,7 +804,7 @@ cdef StabilizerChain *SC_copy(StabilizerChain *SC, int level): SC_copy_nomalloc(SCC, SC, level) # no chance for memory error here... return SCC -cdef int SC_copy_nomalloc(StabilizerChain *SC_dest, StabilizerChain *SC, int level): +cdef int SC_copy_nomalloc(StabilizerChain *SC_dest, StabilizerChain *SC, int level) noexcept: cdef int i, n = SC.degree level = min(level, SC.base_size) SC_dest.base_size = level @@ -818,7 +818,7 @@ cdef int SC_copy_nomalloc(StabilizerChain *SC_dest, StabilizerChain *SC, int lev memcpy(SC_dest.gen_inverses[i], SC.gen_inverses[i], SC.num_gens[i]*n * sizeof(int) ) return 0 -cdef SC_print_level(StabilizerChain *SC, int level): +cdef SC_print_level(StabilizerChain *SC, int level) noexcept: cdef int i, j, n = SC.degree if level < SC.base_size: print('/ level {}'.format(level)) @@ -839,7 +839,7 @@ cdef SC_print_level(StabilizerChain *SC, int level): print(r'\ base_size {}'.format(SC.base_size)) -cdef StabilizerChain *SC_new_base(StabilizerChain *SC, int *base, int base_len): +cdef StabilizerChain *SC_new_base(StabilizerChain *SC, int *base, int base_len) noexcept: """ Create a new stabilizer chain whose base starts with the given base, and which represents the same permutation group. Original StabilizerChain is @@ -857,7 +857,7 @@ cdef StabilizerChain *SC_new_base(StabilizerChain *SC, int *base, int base_len): return NULL return NEW -cdef int SC_new_base_nomalloc(StabilizerChain *SC_dest, StabilizerChain *SC, int *base, int base_len): +cdef int SC_new_base_nomalloc(StabilizerChain *SC_dest, StabilizerChain *SC, int *base, int base_len) noexcept: cdef int i SC_dest.base_size = 0 for i in range(base_len): @@ -867,7 +867,7 @@ cdef int SC_new_base_nomalloc(StabilizerChain *SC_dest, StabilizerChain *SC, int return 1 return 0 -cdef int SC_update(StabilizerChain *dest, StabilizerChain *source, int level): +cdef int SC_update(StabilizerChain *dest, StabilizerChain *source, int level) noexcept: cdef mpz_t src_order, dst_order cdef int *perm = dest.perm_scratch mpz_init(src_order) @@ -901,7 +901,7 @@ cdef int SC_update(StabilizerChain *dest, StabilizerChain *source, int level): mpz_clear(dst_order) return 0 -cdef StabilizerChain *SC_insert_base_point(StabilizerChain *SC, int level, int p): +cdef StabilizerChain *SC_insert_base_point(StabilizerChain *SC, int level, int p) noexcept: """ Insert the point ``p`` as a base point on level ``level``. Return a new StabilizerChain with this new base. Original StabilizerChain is unmodified. @@ -928,7 +928,7 @@ cdef StabilizerChain *SC_insert_base_point(StabilizerChain *SC, int level, int p return NULL return NEW -cdef int SC_insert_base_point_nomalloc(StabilizerChain *SC_dest, StabilizerChain *SC, int level, int p): +cdef int SC_insert_base_point_nomalloc(StabilizerChain *SC_dest, StabilizerChain *SC, int level, int p) noexcept: cdef int i, b SC_copy_nomalloc(SC_dest, SC, level) SC_add_base_point(SC_dest, p) @@ -940,7 +940,7 @@ cdef int SC_insert_base_point_nomalloc(StabilizerChain *SC_dest, StabilizerChain return 1 return 0 -cdef int SC_re_tree(StabilizerChain *SC, int level, int *perm, int x): +cdef int SC_re_tree(StabilizerChain *SC, int level, int *perm, int x) noexcept: """ Return values: 0 - No errors. @@ -981,7 +981,7 @@ cdef int SC_re_tree(StabilizerChain *SC, int level, int *perm, int x): i += 1 return 0 -cdef int SC_sift(StabilizerChain *SC, int level, int x, int *gens, int num_gens, int *new_gens): +cdef int SC_sift(StabilizerChain *SC, int level, int x, int *gens, int num_gens, int *new_gens) noexcept: """ Apply Schreier's subgroup lemma[1] as follows. Given a level, a point x, and a generator s, find the coset traversal element r coming from x. @@ -1027,7 +1027,7 @@ cdef int SC_sift(StabilizerChain *SC, int level, int x, int *gens, int num_gens, SC_mult_perms(perm, perm, perm_rep_inv, n) return SC_insert(SC, level+1, new_gens, num_gens) -cdef int SC_insert_and_sift(StabilizerChain *SC, int level, int *pi, int num_perms, bint sift): +cdef int SC_insert_and_sift(StabilizerChain *SC, int level, int *pi, int num_perms, bint sift) noexcept: cdef int i, j, b, n = SC.degree cdef int perm_gen_index if sift: @@ -1134,7 +1134,7 @@ cdef int SC_insert_and_sift(StabilizerChain *SC, int level, int *pi, int num_per section += 1 return 0 -cdef bint SC_is_giant(int n, int num_perms, int *perms, float p, bitset_t support): +cdef bint SC_is_giant(int n, int num_perms, int *perms, float p, bitset_t support) noexcept: """ Test whether the group generated by the input permutations is a giant, i.e., the alternating or symmetric group. @@ -1614,7 +1614,7 @@ def SC_test_list_perms(list L, int n, int limit, bint gap, bint limit_complain, # Functions -cdef int sort_by_function(PartitionStack *PS, int start, int *degrees): +cdef int sort_by_function(PartitionStack *PS, int start, int *degrees) noexcept: """ A simple counting sort, given the degrees of vertices to a certain cell. @@ -1658,7 +1658,7 @@ cdef int sort_by_function(PartitionStack *PS, int start, int *degrees): j += 1 return max_location -cdef int refine_by_orbits(PartitionStack *PS, StabilizerChain *SC, int *perm_stack, int *cells_to_refine_by, int *ctrb_len): +cdef int refine_by_orbits(PartitionStack *PS, StabilizerChain *SC, int *perm_stack, int *cells_to_refine_by, int *ctrb_len) noexcept: """ Given a stabilizer chain SC, refine the partition stack PS so that each cell contains elements from at most one orbit, and sort the refined cells by @@ -1699,7 +1699,7 @@ cdef int refine_by_orbits(PartitionStack *PS, StabilizerChain *SC, int *perm_sta return invariant cdef int compute_relabeling(StabilizerChain *group, StabilizerChain *scratch_group, - int *permutation, int *relabeling): + int *permutation, int *relabeling) noexcept: """ Technically, compute the INVERSE of the relabeling """ diff --git a/src/sage/groups/perm_gps/partn_ref/double_coset.pxd b/src/sage/groups/perm_gps/partn_ref/double_coset.pxd index 7db1b7764c3..1ca972a8e33 100644 --- a/src/sage/groups/perm_gps/partn_ref/double_coset.pxd +++ b/src/sage/groups/perm_gps/partn_ref/double_coset.pxd @@ -12,7 +12,7 @@ from .data_structures cimport * from sage.data_structures.bitset cimport bitset_t from sage.rings.integer cimport Integer -cdef inline int int_cmp(int a, int b): +cdef inline int int_cmp(int a, int b) noexcept: if a < b: return -1 elif a == b: @@ -33,12 +33,12 @@ cdef struct dc_work_space: bitset_t *bitset_array # (n + 2*len_of_fp_and_mcr + 1) bitset_t's, each of size n OrbitPartition *orbits_of_subgroup # degree n -cdef dc_work_space *allocate_dc_work_space(int) +cdef dc_work_space *allocate_dc_work_space(int) noexcept -cdef void deallocate_dc_work_space(dc_work_space *) +cdef void deallocate_dc_work_space(dc_work_space *) noexcept cdef int double_coset( void *, void *, PartitionStack *, int *, int, - bint (*)(PartitionStack *, void *), - int (*)(PartitionStack *, void *, int *, int), - int (*)(int *, int *, void *, void *, int), + bint (*)(PartitionStack *, void *) noexcept, + int (*)(PartitionStack *, void *, int *, int) noexcept, + int (*)(int *, int *, void *, void *, int) noexcept, StabilizerChain *, dc_work_space *, int *) except -1 diff --git a/src/sage/groups/perm_gps/partn_ref/double_coset.pyx b/src/sage/groups/perm_gps/partn_ref/double_coset.pyx index e3c7bc75f05..b29abddd20a 100644 --- a/src/sage/groups/perm_gps/partn_ref/double_coset.pyx +++ b/src/sage/groups/perm_gps/partn_ref/double_coset.pyx @@ -101,13 +101,13 @@ from sage.data_structures.bitset_base cimport * # Functions -cdef bint all_children_are_equivalent_trivial(PartitionStack *PS, void *S): +cdef bint all_children_are_equivalent_trivial(PartitionStack *PS, void *S) noexcept: return 0 -cdef int refine_and_return_invariant_trivial(PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len): +cdef int refine_and_return_invariant_trivial(PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len) noexcept: return 0 -cdef int compare_perms(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree): +cdef int compare_perms(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree) noexcept: cdef list MS1 = S1 cdef list MS2 = S2 cdef int i, j @@ -199,7 +199,7 @@ def coset_eq(list perm1=[0,1,2,3,4,5], list perm2=[1,2,3,4,5,0], list gens=[[1,2 sig_free(isomorphism) return x -cdef dc_work_space *allocate_dc_work_space(int n): +cdef dc_work_space *allocate_dc_work_space(int n) noexcept: r""" Allocates work space for the double_coset function. It can be input to the function in which case it must be deallocated after the @@ -249,7 +249,7 @@ cdef dc_work_space *allocate_dc_work_space(int n): return NULL return work_space -cdef void deallocate_dc_work_space(dc_work_space *work_space): +cdef void deallocate_dc_work_space(dc_work_space *work_space) noexcept: r""" Deallocates work space for the double_coset function. """ @@ -269,11 +269,11 @@ cdef void deallocate_dc_work_space(dc_work_space *work_space): sig_free(work_space) cdef int double_coset(void *S1, void *S2, PartitionStack *partition1, int *ordering2, - int n, bint (*all_children_are_equivalent)(PartitionStack *PS, void *S), + int n, bint (*all_children_are_equivalent)(PartitionStack *PS, void *S) noexcept, int (*refine_and_return_invariant)(PartitionStack *PS, void *S, - int *cells_to_refine_by, int ctrb_len), + int *cells_to_refine_by, int ctrb_len) noexcept, int (*compare_structures)(int *gamma_1, int *gamma_2, void *S1, void *S2, - int degree), + int degree) noexcept, StabilizerChain *input_group, dc_work_space *work_space_prealloc, int *isom) except -1: """ diff --git a/src/sage/groups/perm_gps/partn_ref/refinement_binary.pxd b/src/sage/groups/perm_gps/partn_ref/refinement_binary.pxd index 005142f8bc7..a06c9fc8532 100644 --- a/src/sage/groups/perm_gps/partn_ref/refinement_binary.pxd +++ b/src/sage/groups/perm_gps/partn_ref/refinement_binary.pxd @@ -24,17 +24,17 @@ cdef class BinaryCodeStruct: cdef int *alpha # length nwords + degree cdef int *scratch # length 3*nwords + 3*degree + 2 cdef aut_gp_and_can_lab *output - cdef int (*ith_word)(BinaryCodeStruct self, int, bitset_s *) + cdef int (*ith_word)(BinaryCodeStruct self, int, bitset_s *) noexcept cdef class LinearBinaryCodeStruct(BinaryCodeStruct): cdef bitset_s *basis cdef bitset_s *scratch_bitsets # length 2*dimension + 2 cdef int dimension -cdef int ith_word_linear(BinaryCodeStruct, int, bitset_s *) +cdef int ith_word_linear(BinaryCodeStruct, int, bitset_s *) noexcept cdef class NonlinearBinaryCodeStruct(BinaryCodeStruct): cdef bitset_s *words cdef bitset_s *scratch_bitsets # length 4*nwords + 1 -cdef int ith_word_nonlinear(BinaryCodeStruct, int, bitset_s *) +cdef int ith_word_nonlinear(BinaryCodeStruct, int, bitset_s *) noexcept -cdef int refine_by_bip_degree(PartitionStack *, void *, int *, int) +cdef int refine_by_bip_degree(PartitionStack *, void *, int *, int) noexcept diff --git a/src/sage/groups/perm_gps/partn_ref/refinement_binary.pyx b/src/sage/groups/perm_gps/partn_ref/refinement_binary.pyx index 06f548f4b7c..6339dbbd2e5 100644 --- a/src/sage/groups/perm_gps/partn_ref/refinement_binary.pyx +++ b/src/sage/groups/perm_gps/partn_ref/refinement_binary.pyx @@ -360,7 +360,7 @@ cdef class LinearBinaryCodeStruct(BinaryCodeStruct): if self.output is not NULL: deallocate_agcl_output(self.output) -cdef int ith_word_linear(BinaryCodeStruct self, int i, bitset_s *word): +cdef int ith_word_linear(BinaryCodeStruct self, int i, bitset_s *word) noexcept: cdef LinearBinaryCodeStruct LBCS = self cdef int j bitset_zero(word) @@ -621,12 +621,12 @@ cdef class NonlinearBinaryCodeStruct(BinaryCodeStruct): sig_free(output) return output_py -cdef int ith_word_nonlinear(BinaryCodeStruct self, int i, bitset_s *word): +cdef int ith_word_nonlinear(BinaryCodeStruct self, int i, bitset_s *word) noexcept: cdef NonlinearBinaryCodeStruct NBCS = self bitset_copy(word, &NBCS.words[i]) return 0 -cdef int refine_by_bip_degree(PartitionStack *col_ps, void *S, int *cells_to_refine_by, int ctrb_len): +cdef int refine_by_bip_degree(PartitionStack *col_ps, void *S, int *cells_to_refine_by, int ctrb_len) noexcept: r""" Refines the input partition by checking degrees of vertices to the given cells in the associated bipartite graph (vertices split into columns and @@ -750,7 +750,7 @@ cdef int refine_by_bip_degree(PartitionStack *col_ps, void *S, int *cells_to_ref current_cell_against += 1 return invariant -cdef int compare_linear_codes(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree): +cdef int compare_linear_codes(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree) noexcept: r""" Compare gamma_1(S1) and gamma_2(S2). @@ -826,7 +826,7 @@ cdef int compare_linear_codes(int *gamma_1, int *gamma_2, void *S1, void *S2, in return bitset_check(&basis_2[i], gamma_2[cur_col]) - bitset_check(&basis_1[i], gamma_1[cur_col]) return 0 -cdef int compare_nonlinear_codes(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree): +cdef int compare_nonlinear_codes(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree) noexcept: r""" Compare gamma_1(S1) and gamma_2(S2). @@ -912,7 +912,7 @@ cdef int compare_nonlinear_codes(int *gamma_1, int *gamma_2, void *S1, void *S2, return 0 -cdef bint all_children_are_equivalent(PartitionStack *col_ps, void *S): +cdef bint all_children_are_equivalent(PartitionStack *col_ps, void *S) noexcept: """ Returns True if any refinement of the current partition results in the same structure. @@ -955,7 +955,7 @@ cdef bint all_children_are_equivalent(PartitionStack *col_ps, void *S): return 1 return 0 -cdef inline int word_degree(PartitionStack *word_ps, BinaryCodeStruct BCS, int entry, int cell_index, PartitionStack *col_ps): +cdef inline int word_degree(PartitionStack *word_ps, BinaryCodeStruct BCS, int entry, int cell_index, PartitionStack *col_ps) noexcept: """ Returns the number of edges from the vertex corresponding to entry to vertices in the cell corresponding to cell_index. @@ -985,7 +985,7 @@ cdef inline int word_degree(PartitionStack *word_ps, BinaryCodeStruct BCS, int e bitset_free(word) return h -cdef inline int col_degree(PartitionStack *col_ps, BinaryCodeStruct BCS, int entry, int cell_index, PartitionStack *word_ps): +cdef inline int col_degree(PartitionStack *col_ps, BinaryCodeStruct BCS, int entry, int cell_index, PartitionStack *word_ps) noexcept: """ Returns the number of edges from the vertex corresponding to entry to vertices in the cell corresponding to cell_index. @@ -1011,7 +1011,7 @@ cdef inline int col_degree(PartitionStack *col_ps, BinaryCodeStruct BCS, int ent bitset_free(word) return degree -cdef inline int sort_by_function_codes(PartitionStack *PS, int start, int *degrees, int *counts, int *output, int count_max): +cdef inline int sort_by_function_codes(PartitionStack *PS, int start, int *degrees, int *counts, int *output, int count_max) noexcept: """ A simple counting sort, given the degrees of vertices to a certain cell. diff --git a/src/sage/groups/perm_gps/partn_ref/refinement_graphs.pyx b/src/sage/groups/perm_gps/partn_ref/refinement_graphs.pyx index cafe8a26c75..83c91f3296d 100644 --- a/src/sage/groups/perm_gps/partn_ref/refinement_graphs.pyx +++ b/src/sage/groups/perm_gps/partn_ref/refinement_graphs.pyx @@ -506,7 +506,7 @@ def search_tree(G_in, partition, lab=True, dig=False, dict_rep=False, certificat else: return tuple(return_tuple) -cdef int refine_by_degree(PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len): +cdef int refine_by_degree(PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len) noexcept: r""" Refine the input partition by checking degrees of vertices to the given cells. @@ -643,7 +643,7 @@ cdef int refine_by_degree(PartitionStack *PS, void *S, int *cells_to_refine_by, else: return 0 -cdef int compare_graphs(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree): +cdef int compare_graphs(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree) noexcept: r""" Compare gamma_1(S1) and gamma_2(S2). @@ -674,7 +674,7 @@ cdef int compare_graphs(int *gamma_1, int *gamma_2, void *S1, void *S2, int degr return -1 return 0 -cdef bint all_children_are_equivalent(PartitionStack *PS, void *S): +cdef bint all_children_are_equivalent(PartitionStack *PS, void *S) noexcept: """ Return True if every refinement of the current partition results in the same structure. @@ -712,7 +712,7 @@ cdef bint all_children_are_equivalent(PartitionStack *PS, void *S): return 1 return 0 -cdef inline int degree(PartitionStack *PS, CGraph G, int entry, int cell_index, bint reverse): +cdef inline int degree(PartitionStack *PS, CGraph G, int entry, int cell_index, bint reverse) noexcept: """ Return the number of edges from the vertex corresponding to entry to vertices in the cell corresponding to cell_index. @@ -1065,7 +1065,7 @@ from cpython.ref cimport * # * Seed objects are graphs with n vertices and no edges. # * Augmentations consist of adding a single edge, or a loop. -cdef void *dg_edge_gen_next(void *data, int *degree, bint *mem_err): +cdef void *dg_edge_gen_next(void *data, int *degree, bint *mem_err) noexcept: r""" The ``next`` function in an edge iterator. The iterator generates unique representatives under the action of the automorphism group of the parent @@ -1099,7 +1099,7 @@ cdef void *dg_edge_gen_next(void *data, int *degree, bint *mem_err): mem_err[0] = 1 return edge_candidate -cdef void *allocate_degd(int degree): +cdef void *allocate_degd(int degree) noexcept: r""" Allocate the data part of the iterator over edges to add to the graph. """ @@ -1116,7 +1116,7 @@ cdef void *allocate_degd(int degree): degd.edge_iterator = edge_iterator return degd -cdef void deallocate_degd(void *data): +cdef void deallocate_degd(void *data) noexcept: r""" Deallocate the data part of the iterator over edges to add to the graph. """ @@ -1124,7 +1124,7 @@ cdef void deallocate_degd(void *data): free_subset_gen(degd.edge_iterator) sig_free(degd) -cdef int gen_children_dg_edge(void *S, aut_gp_and_can_lab *group, iterator *it): +cdef int gen_children_dg_edge(void *S, aut_gp_and_can_lab *group, iterator *it) noexcept: r""" Setup an iterator over edges to be added. """ @@ -1136,7 +1136,7 @@ cdef int gen_children_dg_edge(void *S, aut_gp_and_can_lab *group, iterator *it): start_canonical_generator(group.group, NULL, n, edge_iterator) return (edge_iterator is NULL) -cdef void *apply_dg_edge_aug(void *parent, void *aug, void *child, int *degree, bint *mem_err): +cdef void *apply_dg_edge_aug(void *parent, void *aug, void *child, int *degree, bint *mem_err) noexcept: r""" Apply the augmentation to ``parent`` storing the result in ``child``. Here ``aug`` represents an edge to be added. @@ -1161,7 +1161,7 @@ cdef void *apply_dg_edge_aug(void *parent, void *aug, void *child, int *degree, degree[0] = DG.num_verts return GS_child -cdef void *allocate_dg_edge(int n, bint loops): +cdef void *allocate_dg_edge(int n, bint loops) noexcept: r""" Allocates an object for this augmentation scheme. """ @@ -1185,7 +1185,7 @@ cdef void *allocate_dg_edge(int n, bint loops): GS.scratch = scratch return GS -cdef void free_dg_edge(void *child): +cdef void free_dg_edge(void *child) noexcept: r""" Deallocates an object for this augmentation scheme. """ @@ -1194,7 +1194,7 @@ cdef void free_dg_edge(void *child): Py_DECREF(GS.G) Py_DECREF(GS) -cdef void *canonical_dg_edge_parent(void *child, void *parent, int *permutation, int *degree, bint *mem_err): +cdef void *canonical_dg_edge_parent(void *child, void *parent, int *permutation, int *degree, bint *mem_err) noexcept: r""" Applies ``permutation`` to ``child``, determines an arbitrary parent by deleting the lexicographically largest edge, applies the inverse of @@ -1224,7 +1224,7 @@ cdef void *canonical_dg_edge_parent(void *child, void *parent, int *permutation, degree[0] = n return GS_par -cdef iterator *allocate_dg_edge_gen(int degree, int depth, bint loops): +cdef iterator *allocate_dg_edge_gen(int degree, int depth, bint loops) noexcept: r""" Allocates the iterator for generating graphs. """ @@ -1254,7 +1254,7 @@ cdef iterator *allocate_dg_edge_gen(int degree, int depth, bint loops): dg_edge_gen.next = canonical_generator_next return dg_edge_gen -cdef void free_dg_edge_gen(iterator *dg_edge_gen): +cdef void free_dg_edge_gen(iterator *dg_edge_gen) noexcept: r""" Deallocates the iterator for generating graphs. """ @@ -1394,7 +1394,7 @@ def generate_dense_graphs_edge_addition(int n, bint loops, G=None, depth=None, # * Augmentations consist of adding a single vertex connected to some subset of # the previous vertices. -cdef int gen_children_dg_vert(void *S, aut_gp_and_can_lab *group, iterator *it): +cdef int gen_children_dg_vert(void *S, aut_gp_and_can_lab *group, iterator *it) noexcept: r""" Setup an iterator over subsets to join a new vertex to. """ @@ -1405,7 +1405,7 @@ cdef int gen_children_dg_vert(void *S, aut_gp_and_can_lab *group, iterator *it): start_canonical_generator(group.group, NULL, n, subset_iterator) return (subset_iterator is NULL) -cdef void *apply_dg_vert_aug(void *parent, void *aug, void *child, int *degree, bint *mem_err): +cdef void *apply_dg_vert_aug(void *parent, void *aug, void *child, int *degree, bint *mem_err) noexcept: r""" Apply the augmentation to ``parent`` storing the result in ``child``. Here ``aug`` represents a subset to join to a new vertex. @@ -1429,7 +1429,7 @@ cdef void *apply_dg_vert_aug(void *parent, void *aug, void *child, int *degree, degree[0] = n+1 return GS_child -cdef void *allocate_dg_vert(int n, int depth): +cdef void *allocate_dg_vert(int n, int depth) noexcept: r""" Allocates an object for this augmentation scheme. """ @@ -1455,7 +1455,7 @@ cdef void *allocate_dg_vert(int n, int depth): GS.scratch = scratch return GS -cdef void free_dg_vert(void *child): +cdef void free_dg_vert(void *child) noexcept: r""" Deallocates an object for this augmentation scheme. """ @@ -1464,7 +1464,7 @@ cdef void free_dg_vert(void *child): Py_DECREF(GS.G) Py_DECREF(GS) -cdef void *canonical_dg_vert_parent(void *child, void *parent, int *permutation, int *degree, bint *mem_err): +cdef void *canonical_dg_vert_parent(void *child, void *parent, int *permutation, int *degree, bint *mem_err) noexcept: r""" Applies ``permutation`` to ``child``, determines an arbitrary parent by deleting the lexicographically largest vertex, applies the inverse of @@ -1486,7 +1486,7 @@ cdef void *canonical_dg_vert_parent(void *child, void *parent, int *permutation, degree[0] = n return GS_par -cdef iterator *allocate_dg_vert_gen(int degree, int depth): +cdef iterator *allocate_dg_vert_gen(int degree, int depth) noexcept: r""" Allocates the iterator for generating graphs. """ @@ -1527,7 +1527,7 @@ cdef iterator *allocate_dg_vert_gen(int degree, int depth): dg_vert_gen.next = canonical_generator_next return dg_vert_gen -cdef void free_dg_vert_gen(iterator *dg_vert_gen): +cdef void free_dg_vert_gen(iterator *dg_vert_gen) noexcept: r""" Deallocates the iterator for generating graphs. """ @@ -1535,7 +1535,7 @@ cdef void free_dg_vert_gen(iterator *dg_vert_gen): deallocate_cgd(cgd) sig_free(dg_vert_gen) -cdef void free_cgd_2(void *data): +cdef void free_cgd_2(void *data) noexcept: r""" A simpler alternative to ``free_cgd``. """ diff --git a/src/sage/groups/perm_gps/partn_ref/refinement_lists.pxd b/src/sage/groups/perm_gps/partn_ref/refinement_lists.pxd index 898dfa97528..faabab4024e 100644 --- a/src/sage/groups/perm_gps/partn_ref/refinement_lists.pxd +++ b/src/sage/groups/perm_gps/partn_ref/refinement_lists.pxd @@ -13,6 +13,6 @@ from .data_structures cimport * # name of the three functions to customize -cdef int refine_list(PartitionStack *, void *, int *, int) -cdef int compare_lists(int *, int *, void *, void *, int) -cdef bint all_list_children_are_equivalent(PartitionStack *, void *) +cdef int refine_list(PartitionStack *, void *, int *, int) noexcept +cdef int compare_lists(int *, int *, void *, void *, int) noexcept +cdef bint all_list_children_are_equivalent(PartitionStack *, void *) noexcept diff --git a/src/sage/groups/perm_gps/partn_ref/refinement_lists.pyx b/src/sage/groups/perm_gps/partn_ref/refinement_lists.pyx index 5942edd5438..462f96bef00 100644 --- a/src/sage/groups/perm_gps/partn_ref/refinement_lists.pyx +++ b/src/sage/groups/perm_gps/partn_ref/refinement_lists.pyx @@ -62,13 +62,13 @@ def is_isomorphic(self, other): sig_free(output) return output_py -cdef bint all_list_children_are_equivalent(PartitionStack *PS, void *S): +cdef bint all_list_children_are_equivalent(PartitionStack *PS, void *S) noexcept: return 0 -cdef int refine_list(PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len): +cdef int refine_list(PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len) noexcept: return 0 -cdef int compare_lists(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree): +cdef int compare_lists(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree) noexcept: r""" Compare two lists according to the lexicographic order. """ diff --git a/src/sage/groups/perm_gps/partn_ref/refinement_matrices.pxd b/src/sage/groups/perm_gps/partn_ref/refinement_matrices.pxd index 0273291f014..7799111e457 100644 --- a/src/sage/groups/perm_gps/partn_ref/refinement_matrices.pxd +++ b/src/sage/groups/perm_gps/partn_ref/refinement_matrices.pxd @@ -25,7 +25,7 @@ cdef class MatrixStruct: cdef PartitionStack *temp_col_ps cdef aut_gp_and_can_lab *output -cdef int refine_matrix(PartitionStack *, void *, int *, int) -cdef int compare_matrices(int *, int *, void *, void *, int) -cdef bint all_matrix_children_are_equivalent(PartitionStack *, void *) +cdef int refine_matrix(PartitionStack *, void *, int *, int) noexcept +cdef int compare_matrices(int *, int *, void *, void *, int) noexcept +cdef bint all_matrix_children_are_equivalent(PartitionStack *, void *) noexcept diff --git a/src/sage/groups/perm_gps/partn_ref/refinement_matrices.pyx b/src/sage/groups/perm_gps/partn_ref/refinement_matrices.pyx index e2388616a34..4d55e2a09a2 100644 --- a/src/sage/groups/perm_gps/partn_ref/refinement_matrices.pyx +++ b/src/sage/groups/perm_gps/partn_ref/refinement_matrices.pyx @@ -269,7 +269,7 @@ cdef class MatrixStruct: sig_free(output) return output_py -cdef int refine_matrix(PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len): +cdef int refine_matrix(PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len) noexcept: cdef MatrixStruct M = S cdef int temp_inv, invariant = 1 cdef bint changed = 1 @@ -282,7 +282,7 @@ cdef int refine_matrix(PartitionStack *PS, void *S, int *cells_to_refine_by, int changed = 0 return invariant -cdef int compare_matrices(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree): +cdef int compare_matrices(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree) noexcept: cdef MatrixStruct MS1 = S1 cdef MatrixStruct MS2 = S2 M1 = MS1.matrix @@ -299,7 +299,7 @@ cdef int compare_matrices(int *gamma_1, int *gamma_2, void *S1, void *S2, int de return 0 return -1 if rows1 < rows2 else 1 -cdef bint all_matrix_children_are_equivalent(PartitionStack *PS, void *S): +cdef bint all_matrix_children_are_equivalent(PartitionStack *PS, void *S) noexcept: return 0 def random_tests(n=10, nrows_max=50, ncols_max=50, nsymbols_max=10, perms_per_matrix=5, density_range=(.1,.9)): diff --git a/src/sage/groups/perm_gps/partn_ref/refinement_python.pyx b/src/sage/groups/perm_gps/partn_ref/refinement_python.pyx index 4d53f3a0332..0a7de54bc4f 100644 --- a/src/sage/groups/perm_gps/partn_ref/refinement_python.pyx +++ b/src/sage/groups/perm_gps/partn_ref/refinement_python.pyx @@ -388,7 +388,7 @@ class PythonObjectWrapper: self.rari_fn = rari_fn self.cs_fn = cs_fn -cdef bint all_children_are_equivalent_python(PartitionStack *PS, void *S): +cdef bint all_children_are_equivalent_python(PartitionStack *PS, void *S) noexcept: """ Python conversion of all_children_are_equivalent function. """ @@ -397,7 +397,7 @@ cdef bint all_children_are_equivalent_python(PartitionStack *PS, void *S): PS_copy_from_to(PS, Py_PS.c_ps) return S_obj.acae_fn(Py_PS, S_obj.obj) -cdef int refine_and_return_invariant_python(PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len): +cdef int refine_and_return_invariant_python(PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len) noexcept: """ Python conversion of refine_and_return_invariant function. """ @@ -408,7 +408,7 @@ cdef int refine_and_return_invariant_python(PartitionStack *PS, void *S, int *ce cdef list ctrb_py = [cells_to_refine_by[i] for i from 0 <= i < ctrb_len] return S_obj.rari_fn(Py_PS, S_obj.obj, ctrb_py) -cdef int compare_structures_python(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree): +cdef int compare_structures_python(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree) noexcept: """ Python conversion of compare_structures function. """ diff --git a/src/sage/groups/perm_gps/partn_ref/refinement_sets.pxd b/src/sage/groups/perm_gps/partn_ref/refinement_sets.pxd index 19f60c7f153..9a1d0da4bf2 100644 --- a/src/sage/groups/perm_gps/partn_ref/refinement_sets.pxd +++ b/src/sage/groups/perm_gps/partn_ref/refinement_sets.pxd @@ -32,29 +32,29 @@ cdef struct subset: bitset_s bits int *scratch # must be of size 3*n + 1 -cdef int refine_set(PartitionStack *, void *, int *, int) -cdef int compare_sets(int *, int *, void *, void *, int) -cdef bint all_set_children_are_equivalent(PartitionStack *, void *) +cdef int refine_set(PartitionStack *, void *, int *, int) noexcept +cdef int compare_sets(int *, int *, void *, void *, int) noexcept +cdef bint all_set_children_are_equivalent(PartitionStack *, void *) noexcept -cdef void *allocate_subset(int) +cdef void *allocate_subset(int) noexcept cdef struct subset_generator_data: OrbitPartition *orbits int cur_point bitset_s bits -cdef void *allocate_sgd(int) -cdef void deallocate_sgd(void *) +cdef void *allocate_sgd(int) noexcept +cdef void deallocate_sgd(void *) noexcept -cdef void *subset_generator_next(void *, int *, bint *) +cdef void *subset_generator_next(void *, int *, bint *) noexcept -cdef int generate_child_subsets(void *S, aut_gp_and_can_lab *group, iterator *it) -cdef void *apply_subset_aug(void *parent, void *aug, void *child, int *degree, bint *mem_err) -cdef void free_subset(void *child) -cdef void free_subset_aug(void *) -cdef void *canonical_set_parent(void *child, void *parent, int *permutation, int *degree, bint *mem_err) +cdef int generate_child_subsets(void *S, aut_gp_and_can_lab *group, iterator *it) noexcept +cdef void *apply_subset_aug(void *parent, void *aug, void *child, int *degree, bint *mem_err) noexcept +cdef void free_subset(void *child) noexcept +cdef void free_subset_aug(void *) noexcept +cdef void *canonical_set_parent(void *child, void *parent, int *permutation, int *degree, bint *mem_err) noexcept -cdef iterator *allocate_subset_gen(int degree, int max_size) -cdef int allocate_subset_gen_2(int degree, int max_size, iterator *it) -cdef void free_subset_gen(iterator *subset_gen) -cdef iterator *setup_set_gen(iterator *subset_gen, int degree, int max_size) +cdef iterator *allocate_subset_gen(int degree, int max_size) noexcept +cdef int allocate_subset_gen_2(int degree, int max_size, iterator *it) noexcept +cdef void free_subset_gen(iterator *subset_gen) noexcept +cdef iterator *setup_set_gen(iterator *subset_gen, int degree, int max_size) noexcept diff --git a/src/sage/groups/perm_gps/partn_ref/refinement_sets.pyx b/src/sage/groups/perm_gps/partn_ref/refinement_sets.pyx index 7affe0cd965..cf8dd1b8c40 100644 --- a/src/sage/groups/perm_gps/partn_ref/refinement_sets.pyx +++ b/src/sage/groups/perm_gps/partn_ref/refinement_sets.pyx @@ -181,7 +181,7 @@ def set_stab_py(generators, sett, relab=False): return stab_gens, relabeling return stab_gens -cdef aut_gp_and_can_lab *set_stab(StabilizerChain *supergroup, subset *sett, bint relab): +cdef aut_gp_and_can_lab *set_stab(StabilizerChain *supergroup, subset *sett, bint relab) noexcept: r""" Computes the set stabilizer of ``sett`` within ``supergroup``. (Note that ``set`` is a reserved Python keyword.) If ``relab`` is specified then @@ -439,10 +439,10 @@ cdef int sets_isom(StabilizerChain *supergroup, subset *set1, subset *set2, int PS_dealloc(part) return x -cdef bint all_set_children_are_equivalent(PartitionStack *PS, void *S): +cdef bint all_set_children_are_equivalent(PartitionStack *PS, void *S) noexcept: return 0 -cdef int refine_set(PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len): +cdef int refine_set(PartitionStack *PS, void *S, int *cells_to_refine_by, int ctrb_len) noexcept: """ Given a set S, refine the partition stack PS so that each cell contains elements which are all either in the set or not in the set. If the depth is @@ -466,10 +466,10 @@ cdef int refine_set(PartitionStack *PS, void *S, int *cells_to_refine_by, int ct start += i + 1 return 0 -cdef inline int _bint_cmp(bint a, bint b): +cdef inline int _bint_cmp(bint a, bint b) noexcept: return ( b) - ( a) -cdef int compare_sets(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree): +cdef int compare_sets(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree) noexcept: r""" Compare two sets according to the lexicographic order. """ @@ -484,7 +484,7 @@ cdef int compare_sets(int *gamma_1, int *gamma_2, void *S1, void *S2, int degree return j return 0 -cdef void *allocate_subset(int n): +cdef void *allocate_subset(int n) noexcept: r""" Allocates a subset struct of degree n. """ @@ -503,7 +503,7 @@ cdef void *allocate_subset(int n): set1.scratch = scratch return set1 -cdef void free_subset(void *child): +cdef void free_subset(void *child) noexcept: r""" Deallocates a subset struct. """ @@ -513,7 +513,7 @@ cdef void free_subset(void *child): bitset_free(&set1.bits) sig_free(set1) -cdef void *allocate_sgd(int degree): +cdef void *allocate_sgd(int degree) noexcept: r""" Allocates the data part of an iterator which generates augmentations, i.e., elements to add to the set. @@ -525,7 +525,7 @@ cdef void *allocate_sgd(int degree): return NULL return sgd -cdef void deallocate_sgd(void *data): +cdef void deallocate_sgd(void *data) noexcept: r""" Deallocates the data part of the augmentation iterator. """ @@ -534,7 +534,7 @@ cdef void deallocate_sgd(void *data): OP_dealloc(sgd.orbits) sig_free(sgd) -cdef void *subset_generator_next(void *data, int *degree, bint *mem_err): +cdef void *subset_generator_next(void *data, int *degree, bint *mem_err) noexcept: r""" Returns the next element to consider adding to the set. """ @@ -550,7 +550,7 @@ cdef void *subset_generator_next(void *data, int *degree, bint *mem_err): return NULL return &sgd.cur_point -cdef int generate_child_subsets(void *S, aut_gp_and_can_lab *group, iterator *child_iterator): +cdef int generate_child_subsets(void *S, aut_gp_and_can_lab *group, iterator *child_iterator) noexcept: r""" Sets up an iterator of augmentations, i.e., elements to add to the given set. """ @@ -570,7 +570,7 @@ cdef int generate_child_subsets(void *S, aut_gp_and_can_lab *group, iterator *ch sgd.bits = subset1.bits return 0 -cdef void *apply_subset_aug(void *parent, void *aug, void *child, int *degree, bint *mem_err): +cdef void *apply_subset_aug(void *parent, void *aug, void *child, int *degree, bint *mem_err) noexcept: r""" Adds the element represented by ``aug`` to ``parent``, storing the result to ``child``. @@ -584,10 +584,10 @@ cdef void *apply_subset_aug(void *parent, void *aug, void *child, int *degree, b degree[0] = n return set1 -cdef void free_subset_aug(void *aug): +cdef void free_subset_aug(void *aug) noexcept: return -cdef void *canonical_set_parent(void *child, void *parent, int *permutation, int *degree, bint *mem_err): +cdef void *canonical_set_parent(void *child, void *parent, int *permutation, int *degree, bint *mem_err) noexcept: r""" Determines the canonical parent of the set ``child`` by applying ``permutation``, deleting the largest element in lexicographic order, and @@ -617,7 +617,7 @@ cdef void *canonical_set_parent(void *child, void *parent, int *permutation, int degree[0] = n return par -cdef iterator *allocate_subset_gen(int degree, int max_size): +cdef iterator *allocate_subset_gen(int degree, int max_size) noexcept: r""" Allocates the generator of subsets. """ @@ -628,7 +628,7 @@ cdef iterator *allocate_subset_gen(int degree, int max_size): subset_gen = NULL return subset_gen -cdef int allocate_subset_gen_2(int degree, int max_size, iterator *it): +cdef int allocate_subset_gen_2(int degree, int max_size, iterator *it) noexcept: r""" Given an already allocated iterator, allocates the generator of subsets. """ @@ -654,7 +654,7 @@ cdef int allocate_subset_gen_2(int degree, int max_size, iterator *it): it.next = canonical_generator_next return 0 -cdef void free_subset_gen(iterator *subset_gen): +cdef void free_subset_gen(iterator *subset_gen) noexcept: r""" Frees the iterator of subsets. """ @@ -664,7 +664,7 @@ cdef void free_subset_gen(iterator *subset_gen): deallocate_cgd(cgd) sig_free(subset_gen) -cdef iterator *setup_set_gen(iterator *subset_gen, int degree, int max_size): +cdef iterator *setup_set_gen(iterator *subset_gen, int degree, int max_size) noexcept: r""" Initiates the iterator of subsets. """ diff --git a/src/sage/groups/perm_gps/partn_ref2/refinement_generic.pxd b/src/sage/groups/perm_gps/partn_ref2/refinement_generic.pxd index df300e4e0ce..cf964bfd17c 100644 --- a/src/sage/groups/perm_gps/partn_ref2/refinement_generic.pxd +++ b/src/sage/groups/perm_gps/partn_ref2/refinement_generic.pxd @@ -23,13 +23,13 @@ cdef extern from *: cdef tuple PS_refinement(PartitionStack * part, long *refine_vals, long *best, int begin, int end, - bint * cand_initialized, bint *changed_partition) + bint * cand_initialized, bint *changed_partition) noexcept cdef class _BestValStore: cdef int default_data_length cdef int storage_length cdef long *values - cdef long * get_row(self, int i) + cdef long * get_row(self, int i) noexcept cdef class LabelledBranching: cdef int n @@ -38,8 +38,8 @@ cdef class LabelledBranching: cdef int *act_perm cdef GapElement group, ClosureGroup cdef Parent sym_gp - cdef bint has_empty_intersection(self, PartitionStack * part) - cpdef add_gen(self, GapElement_Permutation gen) + cdef bint has_empty_intersection(self, PartitionStack * part) noexcept + cpdef add_gen(self, GapElement_Permutation gen) noexcept cdef class PartitionRefinement_generic: cdef PartitionStack * _part @@ -57,33 +57,33 @@ cdef class PartitionRefinement_generic: # the following allow us to debug the program via latex cdef object _latex_debug_string - cdef void _init_latex(self) - cdef void _finish_latex(self) - cdef void _latex_new_lvl(self) - cdef void _latex_finish_lvl(self) + cdef void _init_latex(self) noexcept + cdef void _finish_latex(self) noexcept + cdef void _latex_new_lvl(self) noexcept + cdef void _latex_finish_lvl(self) noexcept # methods which have to be implemented in derived classes - cdef bint _inner_min_(self, int pos, bint* inner_group_changed) - cdef bint _refine(self, bint *part_changed, bint inner_group_changed, bint first_step) - cdef tuple _store_state_(self) - cdef void _restore_state_(self, tuple act_state) - cdef void _store_best_(self) - cdef bint _minimization_allowed_on_col(self, int pos) - cdef void _latex_act_node(self, str comment=*, int printlvl=*) # only if you want to allow + cdef bint _inner_min_(self, int pos, bint* inner_group_changed) noexcept + cdef bint _refine(self, bint *part_changed, bint inner_group_changed, bint first_step) noexcept + cdef tuple _store_state_(self) noexcept + cdef void _restore_state_(self, tuple act_state) noexcept + cdef void _store_best_(self) noexcept + cdef bint _minimization_allowed_on_col(self, int pos) noexcept + cdef void _latex_act_node(self, str comment=*, int printlvl=*) noexcept # only if you want to allow # some debugging output # methods used in the main algorithm - cdef void _init_partition_stack(self, list partition) - cdef void _start_Sn_backtrack(self) - cdef void _backtrack(self, bint first_step=?) - cdef void _leaf_computations(self) - cdef bint _cut_by_known_automs(self) - cdef bint _inner_min_unminimized(self, bint *inner_group_changed) + cdef void _init_partition_stack(self, list partition) noexcept + cdef void _start_Sn_backtrack(self) noexcept + cdef void _backtrack(self, bint first_step=?) noexcept + cdef void _leaf_computations(self) noexcept + cdef bint _cut_by_known_automs(self) noexcept + cdef bint _inner_min_unminimized(self, bint *inner_group_changed) noexcept cdef bint _one_refinement(self, long *best, int begin, int end, bint* inner_group_changed, bint* changed_partition, - str refine_name) - cdef int len(self) + str refine_name) noexcept + cdef int len(self) noexcept cdef int PS_first_smallest_PR(PartitionStack *PS, bitset_t b, int *second_pos=?, - PartitionRefinement_generic partn_ref_alg=?) + PartitionRefinement_generic partn_ref_alg=?) noexcept diff --git a/src/sage/groups/perm_gps/partn_ref2/refinement_generic.pyx b/src/sage/groups/perm_gps/partn_ref2/refinement_generic.pyx index 6e4e2b27eeb..4a723873ae7 100644 --- a/src/sage/groups/perm_gps/partn_ref2/refinement_generic.pyx +++ b/src/sage/groups/perm_gps/partn_ref2/refinement_generic.pyx @@ -191,7 +191,7 @@ from sage.data_structures.bitset_base cimport * cdef tuple PS_refinement(PartitionStack * part, long *refine_vals, long *best, int begin, int end, - bint * cand_initialized, bint *changed_partition): + bint * cand_initialized, bint *changed_partition) noexcept: """ Refine the partition stack by the values given by ``refine_vals``. We also compare our actual refinement result with the vector ``best`` in the @@ -281,7 +281,7 @@ cdef class _BestValStore: """ sig_free(self.values) - cdef long * get_row(self, int i): + cdef long * get_row(self, int i) noexcept: r""" Return the i-th row. @@ -356,7 +356,7 @@ cdef class LabelledBranching: sig_free(self.father) sig_free(self.act_perm) - cpdef add_gen(self, GapElement_Permutation gen): + cpdef add_gen(self, GapElement_Permutation gen) noexcept: r""" Add a further generator to the group and update the complete labeled branching. @@ -390,7 +390,7 @@ cdef class LabelledBranching: if libgap.IsTrivial(h).sage(): break - cdef bint has_empty_intersection(self, PartitionStack * part): + cdef bint has_empty_intersection(self, PartitionStack * part) noexcept: r""" Pruning by automorphisms. @@ -493,7 +493,7 @@ cdef class PartitionRefinement_generic: ##################################################################### # The following functions have to be implemented by derived classes ##################################################################### - cdef bint _inner_min_(self, int pos, bint * inner_group_changed): + cdef bint _inner_min_(self, int pos, bint * inner_group_changed) noexcept: """ Minimize the node by the action of the inner group on the i-th position. @@ -509,7 +509,7 @@ cdef class PartitionRefinement_generic: """ raise NotImplementedError - cdef bint _refine(self, bint *part_changed, bint inner_group_changed, bint first_step): + cdef bint _refine(self, bint *part_changed, bint inner_group_changed, bint first_step) noexcept: r""" Refine the partition ``self._part``. @@ -524,26 +524,26 @@ cdef class PartitionRefinement_generic: """ raise NotImplementedError - cdef tuple _store_state_(self): + cdef tuple _store_state_(self) noexcept: r""" Store the current state of the node to a tuple, such that it can be restored by :meth:`_restore_state_`. """ raise NotImplementedError - cdef void _restore_state_(self, tuple act_state): + cdef void _restore_state_(self, tuple act_state) noexcept: r""" The inverse of :meth:`_store_state_`. """ raise NotImplementedError - cdef void _store_best_(self): + cdef void _store_best_(self) noexcept: r""" Store this leaf node as the actual best candidate for the canonical form. """ raise NotImplementedError - cdef bint _minimization_allowed_on_col(self, int pos): + cdef bint _minimization_allowed_on_col(self, int pos) noexcept: r""" Decide if we are allowed to perform the inner minimization on position ``pos`` which is supposed to be a singleton. @@ -611,7 +611,7 @@ cdef class PartitionRefinement_generic: ############################################### # THE BACKTRACK ALGORITHM: ############################################### - cdef void _init_partition_stack(self, list partition): + cdef void _init_partition_stack(self, list partition) noexcept: r""" Initialize the partition stack. @@ -631,7 +631,7 @@ cdef class PartitionRefinement_generic: sig_free(self._refine_vals_scratch) raise MemoryError('initializing the partition stack') - cdef void _start_Sn_backtrack(self): + cdef void _start_Sn_backtrack(self) noexcept: r""" Start the partition refinement algorithm. """ @@ -639,7 +639,7 @@ cdef class PartitionRefinement_generic: self._backtrack(True) self._finish_latex() - cdef void _backtrack(self, bint first_step=False): + cdef void _backtrack(self, bint first_step=False) noexcept: r""" Backtracking with pruning. @@ -718,7 +718,7 @@ cdef class PartitionRefinement_generic: bitset_free(b) self._latex_finish_lvl() - cdef bint _inner_min_unminimized(self, bint *inner_group_changed): + cdef bint _inner_min_unminimized(self, bint *inner_group_changed) noexcept: r""" Compute a subsequence `J = (j_0, \ldots, j_{l-1})` of fixed coordinates, which were not yet used in @@ -785,7 +785,7 @@ cdef class PartitionRefinement_generic: return True cdef bint _one_refinement(self, long * best, int begin, int end, bint *inner_group_changed, - bint *changed_partition, str refine_name): + bint *changed_partition, str refine_name) noexcept: r""" Let ``self._refine_vals_scratch`` contain the result of the `(S_n)_C`-homomorphism `\omega` and ``best`` be the result of `\omega` applied to the candidate. @@ -818,13 +818,13 @@ cdef class PartitionRefinement_generic: self._latex_act_node(refine_name) return False - cdef int len(self): + cdef int len(self) noexcept: r""" Return the degree of the acting symmetric group. """ return self._n - cdef void _leaf_computations(self): + cdef void _leaf_computations(self) noexcept: r""" All necessary computations which have to be performed in a leaf. @@ -855,7 +855,7 @@ cdef class PartitionRefinement_generic: self._store_best_() self._latex_act_node("NEW") - cdef bint _cut_by_known_automs(self): + cdef bint _cut_by_known_automs(self) noexcept: r""" Return ``True`` if the subtree below this node does not contain any *interesting* information. @@ -871,7 +871,7 @@ cdef class PartitionRefinement_generic: # BACKTRACK_WITHLATEX_DEBUG = 1 in the setup.py script when # building this module! ########################################################################### - cdef void _latex_act_node(self, str comment="", int printlvl=0): + cdef void _latex_act_node(self, str comment="", int printlvl=0) noexcept: r""" Append the actual node as a string of latex-commands to ``self._latex_debug_string`` @@ -900,7 +900,7 @@ cdef class PartitionRefinement_generic: print("sorry, no debug output was written. " + "Set BACKTRACK_WITHLATEX_DEBUG to True if interested in this information") - cdef void _init_latex(self): + cdef void _init_latex(self) noexcept: r""" Add some initial commands to the string ``self._latex_debug_string``. @@ -916,7 +916,7 @@ cdef class PartitionRefinement_generic: self._latex_debug_string += "[." self._latex_act_node() - cdef void _finish_latex(self): + cdef void _finish_latex(self) noexcept: r""" Add some final commands to the string ``self._latex_debug_string``. @@ -925,7 +925,7 @@ cdef class PartitionRefinement_generic: self._latex_debug_string += "]\n" self._latex_debug_string += "\\end{tikzpicture} }\n" - cdef void _latex_new_lvl(self): + cdef void _latex_new_lvl(self) noexcept: r""" Add some commands to the string ``self._latex_debug_string``, in the case that the depth was increased during the backtracking. @@ -933,7 +933,7 @@ cdef class PartitionRefinement_generic: if BACKTRACK_WITHLATEX_DEBUG: self._latex_debug_string += "[." - cdef void _latex_finish_lvl(self): + cdef void _latex_finish_lvl(self) noexcept: r""" Add some commands to the string ``self._latex_debug_string``, in the case that we return to a node in the backtracking. @@ -943,7 +943,7 @@ cdef class PartitionRefinement_generic: cdef int PS_first_smallest_PR(PartitionStack *PS, bitset_t b, int *second_pos=NULL, - PartitionRefinement_generic partn_ref_alg=None): + PartitionRefinement_generic partn_ref_alg=None) noexcept: """ Find the first occurrence of the smallest cell of size greater than one, which is admissible (checked by the function ``test_allowance``). diff --git a/src/sage/groups/perm_gps/permgroup_element.pxd b/src/sage/groups/perm_gps/permgroup_element.pxd index 0a584745f96..c0cab01c706 100644 --- a/src/sage/groups/perm_gps/permgroup_element.pxd +++ b/src/sage/groups/perm_gps/permgroup_element.pxd @@ -8,21 +8,21 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): cdef int n cdef int perm_buf[15] # to avoid malloc for small elements cdef GapElement _libgap - cdef PermutationGroupElement _new_c(self) - cdef _alloc(self, int) - cpdef _set_identity(self) - cpdef _set_list_images(self, v, bint convert) - cpdef _set_libgap(self, GapElement p) - cpdef _set_list_cycles(self, c, bint convert) - cpdef _set_string(self, str s) - cpdef _set_permutation_group_element(self, PermutationGroupElement p, bint convert) + cdef PermutationGroupElement _new_c(self) noexcept + cdef _alloc(self, int) noexcept + cpdef _set_identity(self) noexcept + cpdef _set_list_images(self, v, bint convert) noexcept + cpdef _set_libgap(self, GapElement p) noexcept + cpdef _set_list_cycles(self, c, bint convert) noexcept + cpdef _set_string(self, str s) noexcept + cpdef _set_permutation_group_element(self, PermutationGroupElement p, bint convert) noexcept - cpdef _mul_(self, other) - cpdef PermutationGroupElement _generate_new(self, list new_list) - cpdef PermutationGroupElement _generate_new_GAP(self, old) - cpdef _gap_list(self) - cpdef domain(self) + cpdef _mul_(self, other) noexcept + cpdef PermutationGroupElement _generate_new(self, list new_list) noexcept + cpdef PermutationGroupElement _generate_new_GAP(self, old) noexcept + cpdef _gap_list(self) noexcept + cpdef domain(self) noexcept cdef public _SageObject__custom_name - cpdef list _act_on_list_on_position(self, list x) - cpdef ClonableIntArray _act_on_array_on_position(self, ClonableIntArray x) - cpdef ETuple _act_on_etuple_on_position(self, ETuple x) + cpdef list _act_on_list_on_position(self, list x) noexcept + cpdef ClonableIntArray _act_on_array_on_position(self, ClonableIntArray x) noexcept + cpdef ETuple _act_on_etuple_on_position(self, ETuple x) noexcept diff --git a/src/sage/groups/perm_gps/permgroup_element.pyx b/src/sage/groups/perm_gps/permgroup_element.pyx index 2522b5c346d..29eae266c53 100644 --- a/src/sage/groups/perm_gps/permgroup_element.pyx +++ b/src/sage/groups/perm_gps/permgroup_element.pyx @@ -149,7 +149,7 @@ cdef arith_llong arith = arith_llong() cdef extern from *: long long LLONG_MAX -cdef int etuple_index_cmp(const void * a, const void * b) nogil: +cdef int etuple_index_cmp(const void * a, const void * b) noexcept nogil: return (( a)[0] > ( b)[0]) - (( a)[0] < ( b)[0]) def make_permgroup_element(G, x): @@ -513,7 +513,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): if p not in P: raise ValueError('permutation %s not in %s' % (g, parent)) - cpdef _set_identity(self): + cpdef _set_identity(self) noexcept: r""" TESTS:: @@ -532,7 +532,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): for i in range(self.n): self.perm[i] = i - cpdef _set_list_images(self, v, bint convert): + cpdef _set_list_images(self, v, bint convert) noexcept: r""" TESTS:: @@ -566,7 +566,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): for i in range(vn, self.n): self.perm[i] = i - cpdef _set_libgap(self, GapElement p): + cpdef _set_libgap(self, GapElement p) noexcept: r""" TESTS:: @@ -615,7 +615,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): self._libgap = p - cpdef _set_permutation_group_element(self, PermutationGroupElement p, bint convert): + cpdef _set_permutation_group_element(self, PermutationGroupElement p, bint convert) noexcept: r""" TESTS:: @@ -669,7 +669,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): for i in range(p.n, self.n): self.perm[i] = i - cpdef _set_list_cycles(self, c, bint convert): + cpdef _set_list_cycles(self, c, bint convert) noexcept: r""" TESTS:: @@ -716,7 +716,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): raise ValueError("invalid list of cycles to initialize a permutation") self.perm[j] = t[0] - 1 - cpdef _set_string(self, str s): + cpdef _set_string(self, str s) noexcept: r""" TESTS:: @@ -807,7 +807,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): """ return make_permgroup_element_v2, (self._parent, self.domain(), self._parent.domain()) - cdef _alloc(self, int n): + cdef _alloc(self, int n) noexcept: if n < 16 and self.perm == NULL: self.perm = self.perm_buf elif self.perm == NULL: @@ -817,7 +817,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): self.n = n - cdef PermutationGroupElement _new_c(self): + cdef PermutationGroupElement _new_c(self) noexcept: cdef type t = type(self) cdef PermutationGroupElement other = t.__new__(t) if HAS_DICTIONARY(self): @@ -977,7 +977,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): """ return self.cycles()[i] - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: r""" Compare group elements ``self`` and ``other``. @@ -1086,7 +1086,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): else: return from_gap[i] - cpdef list _act_on_list_on_position(self, list x): + cpdef list _act_on_list_on_position(self, list x) noexcept: r""" Returns the right action of ``self`` on the list ``x``. This is the action on positions. @@ -1114,7 +1114,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): assert len(x) == self.n, '%s and %s should have the same length'%(self, x) return [ x[self.perm[i]] for i in range(self.n) ] - cpdef ClonableIntArray _act_on_array_on_position(self, ClonableIntArray x): + cpdef ClonableIntArray _act_on_array_on_position(self, ClonableIntArray x) noexcept: r""" Returns the right action of ``self`` on the ClonableIntArray ``x``. This is the action on positions. @@ -1138,7 +1138,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): y.set_immutable() return y - cpdef ETuple _act_on_etuple_on_position(self, ETuple x): + cpdef ETuple _act_on_etuple_on_position(self, ETuple x) noexcept: r""" Return the right action of this permutation on the ETuple ``x``. @@ -1178,7 +1178,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): qsort(result._data, result._nonzero, 2 * sizeof(int), etuple_index_cmp) return result - cpdef _act_on_(self, x, bint self_on_left): + cpdef _act_on_(self, x, bint self_on_left) noexcept: r""" Return the result of the action of ``self`` on ``x``. @@ -1298,7 +1298,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): return coercion_model.bin_op(left, right, operator.mul) - cpdef _mul_(left, _right): + cpdef _mul_(left, _right) noexcept: r""" EXAMPLES:: @@ -1315,7 +1315,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): prod.perm[i] = right.perm[left.perm[i]] return prod - cpdef PermutationGroupElement _generate_new(self, list v): + cpdef PermutationGroupElement _generate_new(self, list v) noexcept: r""" Generate a new permutation group element with the same parent as ``self`` from ``v``. @@ -1333,7 +1333,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): new._set_list_images(v, False) return new - cpdef PermutationGroupElement _generate_new_GAP(self, lst_in): + cpdef PermutationGroupElement _generate_new_GAP(self, lst_in) noexcept: r""" Generate a new permutation group element with the same parent as ``self`` from the GAP list ``lst_in``. @@ -1384,7 +1384,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): inv.perm[self.perm[i]] = i return inv - cpdef _gap_list(self): + cpdef _gap_list(self) noexcept: r""" Returns this permutation in list notation compatible with the GAP numbering. @@ -1432,7 +1432,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement): from sage.combinat.permutation import Permutation return Permutation(self._gap_list()).cycle_string() - cpdef domain(self): + cpdef domain(self) noexcept: r""" Return the domain of ``self``. @@ -2086,7 +2086,7 @@ cdef class SymmetricGroupElement(PermutationGroupElement): return self.has_descent(i, side='left') -cdef bint is_valid_permutation(int* perm, int n): +cdef bint is_valid_permutation(int* perm, int n) noexcept: r""" This is used in the __init__ method. diff --git a/src/sage/groups/perm_gps/permgroup_named.py b/src/sage/groups/perm_gps/permgroup_named.py index cc49efd505c..5052880e99e 100644 --- a/src/sage/groups/perm_gps/permgroup_named.py +++ b/src/sage/groups/perm_gps/permgroup_named.py @@ -640,7 +640,7 @@ def algebra(self, base_ring, category=None): We illustrate the choice of the category:: sage: A.category() # needs sage.combinat - Join of Category of coxeter group algebras over Rational Field + Join of Category of Coxeter group algebras over Rational Field and Category of finite group algebras over Rational Field and Category of finite dimensional cellular algebras with basis over Rational Field diff --git a/src/sage/groups/semimonomial_transformations/semimonomial_transformation.pxd b/src/sage/groups/semimonomial_transformations/semimonomial_transformation.pxd index bd4f62d497f..1808129c4b7 100644 --- a/src/sage/groups/semimonomial_transformations/semimonomial_transformation.pxd +++ b/src/sage/groups/semimonomial_transformations/semimonomial_transformation.pxd @@ -4,5 +4,5 @@ cdef class SemimonomialTransformation(MultiplicativeGroupElement): cdef tuple v cdef object perm, alpha - cdef _new_c(self) - cpdef _mul_(self, other) + cdef _new_c(self) noexcept + cpdef _mul_(self, other) noexcept diff --git a/src/sage/groups/semimonomial_transformations/semimonomial_transformation.pyx b/src/sage/groups/semimonomial_transformations/semimonomial_transformation.pyx index ae9ce18efb1..453f2be85f0 100644 --- a/src/sage/groups/semimonomial_transformations/semimonomial_transformation.pyx +++ b/src/sage/groups/semimonomial_transformations/semimonomial_transformation.pyx @@ -135,7 +135,7 @@ cdef class SemimonomialTransformation(MultiplicativeGroupElement): self.perm = perm self.alpha = alpha - cdef _new_c(self): + cdef _new_c(self) noexcept: # Create a copy of self. cdef SemimonomialTransformation x x = SemimonomialTransformation.__new__(SemimonomialTransformation) @@ -173,7 +173,7 @@ cdef class SemimonomialTransformation(MultiplicativeGroupElement): """ return hash(self.v) + hash(self.perm) + hash(self.get_autom()) - cpdef _mul_(left, _right): + cpdef _mul_(left, _right) noexcept: r""" Multiplication of elements. @@ -247,7 +247,7 @@ cdef class SemimonomialTransformation(MultiplicativeGroupElement): return "(%s; %s, %s)"%(self.v, self.perm.cycle_string(), self.get_autom()) - cpdef _richcmp_(left, _right, int op): + cpdef _richcmp_(left, _right, int op) noexcept: """ Compare group elements ``self`` and ``right``. diff --git a/src/sage/homology/chain_complex.py b/src/sage/homology/chain_complex.py index 7a56cf3fc4b..16f2a78c7db 100644 --- a/src/sage/homology/chain_complex.py +++ b/src/sage/homology/chain_complex.py @@ -353,7 +353,7 @@ def __init__(self, parent, vectors, check=True): and v.base_ring() is parent.base_ring() for v in vectors.values()) self._vec = vectors - super(Chain_class, self).__init__(parent) + super().__init__(parent) def vector(self, degree): """ @@ -688,7 +688,7 @@ def __init__(self, grading_group, degree_of_differential, base_ring, differentia from sage.categories.chain_complexes import ChainComplexes category = ChainComplexes(base_ring) - super(ChainComplex_class, self).__init__(base=base_ring, category=category) + super().__init__(base=base_ring, category=category) Element = Chain_class diff --git a/src/sage/homology/koszul_complex.py b/src/sage/homology/koszul_complex.py index a8b050e09bc..22a1ceb5d80 100644 --- a/src/sage/homology/koszul_complex.py +++ b/src/sage/homology/koszul_complex.py @@ -115,7 +115,7 @@ def __classcall_private__(cls, R=None, elements=None): R = elements[0].parent() elif R is None: # elements is not None R = elements[0].parent() - return super(KoszulComplex, cls).__classcall__(cls, R, tuple(elements)) + return super().__classcall__(cls, R, tuple(elements)) def __init__(self, R, elements): """ diff --git a/src/sage/interacts/library_cython.pyx b/src/sage/interacts/library_cython.pyx index 37e75a16e7d..a2b36489165 100644 --- a/src/sage/interacts/library_cython.pyx +++ b/src/sage/interacts/library_cython.pyx @@ -16,7 +16,7 @@ AUTHORS: #***************************************************************************** -cpdef julia(ff_j, z, int iterations): +cpdef julia(ff_j, z, int iterations) noexcept: """ Helper function for the Julia Fractal interact example. @@ -44,7 +44,7 @@ cpdef julia(ff_j, z, int iterations): return z -cpdef mandel(ff_m, z, int iterations): +cpdef mandel(ff_m, z, int iterations) noexcept: """ Helper function for the Mandelbrot Fractal interact example. @@ -73,7 +73,7 @@ cpdef mandel(ff_m, z, int iterations): return z -cpdef cellular(rule, int N): +cpdef cellular(rule, int N) noexcept: """ Cythonized helper function for the cellular_automata fractal. diff --git a/src/sage/interfaces/gp.py b/src/sage/interfaces/gp.py index 49b1a8a06fb..e5c77833cca 100644 --- a/src/sage/interfaces/gp.py +++ b/src/sage/interfaces/gp.py @@ -615,7 +615,7 @@ def _next_var_name(self): The vector of results is correctly resized when the stack has to be enlarged during this operation:: - sage: g = Gp(stacksize=10^4,init_list_length=12000) # long time + sage: g = Gp(stacksize=3*10^6,init_list_length=12000) # long time sage: for n in [1..13000]: # long time ....: a = g(n) sage: g('length(sage)') # long time diff --git a/src/sage/interfaces/maple.py b/src/sage/interfaces/maple.py index 42f680e001b..7ba21a66cf6 100644 --- a/src/sage/interfaces/maple.py +++ b/src/sage/interfaces/maple.py @@ -24,15 +24,16 @@ EXAMPLES:: - sage: maple('3 * 5') # optional - maple + sage: # optional - maple + sage: maple('3 * 5') 15 - sage: maple.eval('ifactor(2005)') # optional - maple + sage: maple.eval('ifactor(2005)') '``(5)*``(401)' - sage: maple.ifactor(2005) # optional - maple + sage: maple.ifactor(2005) ``(5)*``(401) - sage: maple.fsolve('x^2=cos(x)+4', 'x=0..5') # optional - maple + sage: maple.fsolve('x^2=cos(x)+4', 'x=0..5') 1.914020619 - sage: maple.factor('x^5 - y^5') # optional - maple + sage: maple.factor('x^5 - y^5') (x-y)*(x^4+x^3*y+x^2*y^2+x*y^3+y^4) If the string "error" (case insensitive) occurs in the output of @@ -192,12 +193,13 @@ :: - sage: alpha = maple('(1+sqrt(5))/2') # optional - maple - sage: beta = maple('(1-sqrt(5))/2') # optional - maple - sage: f19 = alpha^19 - beta^19/maple('sqrt(5)') # optional - maple - sage: f19 # optional - maple + sage: # optional - maple + sage: alpha = maple('(1+sqrt(5))/2') + sage: beta = maple('(1-sqrt(5))/2') + sage: f19 = alpha^19 - beta^19/maple('sqrt(5)') + sage: f19 (1/2+1/2*5^(1/2))^19-1/5*(1/2-1/2*5^(1/2))^19*5^(1/2) - sage: f19.simplify() # somewhat randomly ordered output; optional - maple + sage: f19.simplify() # somewhat randomly ordered output 6765+5778/5*5^(1/2) Let's say we want to write a maple program now that squares a @@ -244,6 +246,7 @@ from sage.interfaces.tab_completion import ExtraTabCompletion from sage.misc.instancedoc import instancedoc from sage.structure.richcmp import rich_to_bool +from sage.cpython.string import bytes_to_str COMMANDS_CACHE = '%s/maple_commandlist_cache.sobj' % DOT_SAGE @@ -356,14 +359,15 @@ def _read_in_file_command(self, filename): :: - sage: filename = tmp_filename() # optional - maple - sage: with open(filename, 'w') as f: # optional - maple + sage: # optional - maple + sage: filename = tmp_filename() + sage: with open(filename, 'w') as f: ....: _ = f.write('xx := 22;\n') - sage: maple.read(filename) # optional - maple - sage: maple.get('xx').strip() # optional - maple + sage: maple.read(filename) + sage: maple.get('xx').strip() '22' """ - return 'read "%s"' % filename + return f'read "{filename}"' def _quit_string(self): """ @@ -374,12 +378,13 @@ def _quit_string(self): :: - sage: m = Maple() # optional - maple - sage: a = m(2) # optional - maple - sage: m.is_running() # optional - maple + sage: # optional - maple + sage: m = Maple() + sage: a = m(2) + sage: m.is_running() True - sage: m.quit() # optional - maple - sage: m.is_running() # optional - maple + sage: m.quit() + sage: m.is_running() False """ return 'quit' @@ -418,8 +423,7 @@ def _install_hints(self): chmod +x maple * WINDOWS: - You must install Maple-for-Linux into the VMware machine (sorry, that's - the only way at present). + You must install Maple-for-Linux into the Linux subsystem. """ def expect(self): @@ -428,13 +432,14 @@ def expect(self): EXAMPLES:: - sage: m = Maple() # optional - maple - sage: m.expect() is None # optional - maple + sage: # optional - maple + sage: m = Maple() + sage: m.expect() is None True - sage: m._start() # optional - maple - sage: m.expect() # optional - maple + sage: m._start() + sage: m.expect() Maple with PID ... - sage: m.quit() # optional - maple + sage: m.quit() """ return self._expect @@ -444,13 +449,12 @@ def console(self): EXAMPLES:: - sage: maple.console() # not tested - |^/| Maple 11 (IBM INTEL LINUX) - ._|\| |/|_. Copyright (c) Maplesoft, a division of Waterloo Maple Inc. 2007 + sage: maple.console() # not tested + |\^/| Maple 2019 (X86 64 LINUX) + ._|\| |/|_. Copyright (c) Maplesoft, a division of Waterloo Maple Inc. 2019 \ MAPLE / All rights reserved. Maple is a trademark of <____ ____> Waterloo Maple Inc. | Type ? for help. - > """ maple_console() @@ -476,7 +480,10 @@ def console(self): def completions(self, s): """ Return all commands that complete the command starting with the - string s. This is like typing s[Ctrl-T] in the maple interpreter. + string ``s``. + + This is like typing ``s`` + :kbd:`Ctrl` + :kbd:`T` + in the Maple interpreter. EXAMPLES:: @@ -500,7 +507,8 @@ def completions(self, s): v = E.before E.expect(self._prompt) E.expect(self._prompt) - return v.split()[2:] + E.expect(self._prompt) + return [bytes_to_str(l) for l in v.split()[2:]] def _commands(self): """ @@ -519,9 +527,10 @@ def _commands(self): sum([self.completions(chr(97 + n)) for n in range(26)], []) except RuntimeError: print("\n" * 3) - print("*" * 70) - print("WARNING: You do not have a working version of Maple installed!") - print("*" * 70) + txt = "WARNING: You do not have a working version of Maple installed!" + print("═" * len(txt)) + print(txt) + print("═" * len(txt)) v = [] v.sort() return v @@ -587,29 +596,30 @@ def _eval_line_using_file(self, line, *args, **kwargs): def cputime(self, t=None): r""" - Return the amount of CPU time that the Maple session has used. If - ``t`` is not None, then it returns the difference + Return the amount of CPU time that the Maple session has used. + + If ``t`` is not None, then it returns the difference between the current CPU time and ``t``. EXAMPLES:: - sage: t = maple.cputime() # optional - maple - sage: t # random; optional - maple + sage: # optional - maple + sage: t = maple.cputime() + sage: t # random 0.02 - sage: x = maple('x') # optional - maple - sage: maple.diff(x^2, x) # optional - maple + sage: x = maple('x') + sage: maple.diff(x^2, x) 2*x - sage: maple.cputime(t) # random; optional - maple + sage: maple.cputime(t) # random 0.0 """ if t is None: return float(self('time()')) - else: - return float(self('time() - %s' % float(t))) + return float(self('time() - %s' % float(t))) def set(self, var, value): """ - Set the variable var to the given value. + Set the variable ``var`` to the given ``value``. EXAMPLES:: @@ -624,7 +634,7 @@ def set(self, var, value): def get(self, var): """ - Get the value of the variable var. + Get the value of the variable ``var``. EXAMPLES:: @@ -711,14 +721,13 @@ def _assign_symbol(self): def _source(self, s): """ - Tries to return the source code of a Maple function str as a - string. + Try to return the source code of a Maple function ``s`` as a string. EXAMPLES:: sage: print(maple._source('curry').strip()) # optional - maple - p -> subs('_X' = args[2 .. nargs], () -> p(_X, args)) - sage: maple._source('ZZZ') #not tested + ... -> subs('_X' = _passed[2 .. _npassed],() -> ...(_X, _passed)) + sage: maple._source('ZZZ') # not tested Traceback (most recent call last): ... Exception: no source code could be found @@ -727,12 +736,14 @@ def _source(self, s): src = os.popen(cmd).read() if src.strip() == s: raise RuntimeError("no source code could be found") - else: - return src + it = (line.strip() for line in src.splitlines()) + return ''.join(l for l in it if l) def source(self, s): """ - Display the Maple source (if possible) about s. This is the same as + Display the Maple source (if possible) about ``s``. + + This is the same as returning the output produced by the following Maple commands: interface(verboseproc=2): print(s) @@ -746,8 +757,8 @@ def source(self, s): EXAMPLES:: - sage: maple.source('curry') #not tested - p -> subs('_X' = args[2 .. nargs], () -> p(_X, args)) + sage: maple.source('curry') # not tested + ... -> subs('_X' = _passed[2 .. _npassed],() -> ...(_X, _passed)) """ try: pager()(self._source(s)) @@ -760,11 +771,11 @@ def _help(self, string): EXAMPLES:: - sage: txt = maple._help('gcd') # optional - maple - sage: txt.find('gcd - greatest common divisor') > 0 # optional - maple + sage: txt = maple._help('igcd') # optional - maple + sage: txt.find('igcd - greatest common divisor') >= 0 # optional - maple True """ - return os.popen('echo "?%s" | maple -q' % string).read() + return bytes_to_str(os.popen(f'echo "?{string}" | maple -q').read()) def help(self, string): """ @@ -791,26 +802,25 @@ def with_package(self, package): INPUT: - - - ``package`` - string - + - ``package`` -- string EXAMPLES: Some functions are unknown to Maple until you use with to include the appropriate package. :: - sage: maple.quit() # reset maple; optional -- maple - sage: maple('partition(10)') # optional - maple + sage: # optional - maple + sage: maple.quit() # reset maple + sage: maple('partition(10)') partition(10) - sage: maple('bell(10)') # optional - maple + sage: maple('bell(10)') bell(10) - sage: maple.with_package('combinat') # optional - maple - sage: maple('partition(10)') # optional - maple + sage: maple.with_package('combinat') + sage: maple('partition(10)') [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 1, 1, 2, 2], [1, 1, 1, 1, 2, 2, 2], [1, 1, 2, 2, 2, 2], [2, 2, 2, 2, 2], [1, 1, 1, 1, 1, 1, 1, 3], [1, 1, 1, 1, 1, 2, 3], [1, 1, 1, 2, 2, 3], [1, 2, 2, 2, 3], [1, 1, 1, 1, 3, 3], [1, 1, 2, 3, 3], [2, 2, 3, 3], [1, 3, 3, 3], [1, 1, 1, 1, 1, 1, 4], [1, 1, 1, 1, 2, 4], [1, 1, 2, 2, 4], [2, 2, 2, 4], [1, 1, 1, 3, 4], [1, 2, 3, 4], [3, 3, 4], [1, 1, 4, 4], [2, 4, 4], [1, 1, 1, 1, 1, 5], [1, 1, 1, 2, 5], [1, 2, 2, 5], [1, 1, 3, 5], [2, 3, 5], [1, 4, 5], [5, 5], [1, 1, 1, 1, 6], [1, 1, 2, 6], [2, 2, 6], [1, 3, 6], [4, 6], [1, 1, 1, 7], [1, 2, 7], [3, 7], [1, 1, 8], [2, 8], [1, 9], [10]] - sage: maple('bell(10)') # optional - maple + sage: maple('bell(10)') 115975 - sage: maple('fibonacci(10)') # optional - maple + sage: maple('fibonacci(10)') 55 """ self.eval('with(%s)' % package) @@ -826,27 +836,28 @@ def clear(self, var): EXAMPLES:: - sage: maple.set('xx', '2') # optional - maple - sage: maple.get('xx') # optional - maple + sage: # optional - maple + sage: maple.set('xx', '2') + sage: maple.get('xx') '2' - sage: maple.clear('xx') # optional - maple - sage: maple.get('xx') # optional - maple + sage: maple.clear('xx') + sage: maple.get('xx') 'xx' """ - self.set(var, "'{}'".format(var)) + self.set(var, f"'{var}'") @instancedoc class MapleFunction(ExpectFunction): - def _instancedoc(self): + def _instancedoc_(self): """ Return the Maple help for this function. This gets called when doing "?" on self. EXAMPLES:: - sage: txt = maple.gcd.__doc__ # optional - maple - sage: txt.find('gcd - greatest common divisor') > 0 # optional - maple + sage: txt = maple.igcd._instancedoc_() # optional - maple + sage: txt.find('igcd - greatest common divisor') >= 0 # optional - maple True """ M = self._parent @@ -862,8 +873,8 @@ def _sage_src_(self): EXAMPLES:: sage: print(maple.curry._sage_src_().strip()) # optional - maple - p -> subs('_X' = args[2 .. nargs], () -> p(_X, args)) - sage: maple.ZZZ._sage_src_() #not tested + ... -> subs('_X' = _passed[2 .. _npassed],() -> ...(_X, _passed)) + sage: maple.ZZZ._sage_src_() # not tested Traceback (most recent call last): ... Exception: no source code could be found @@ -883,23 +894,23 @@ def _instancedoc_(self): EXAMPLES:: sage: two = maple(2) # optional - maple - sage: txt = two.gcd.__doc__ # optional - maple - sage: txt.find('gcd - greatest common divisor') > 0 # optional - maple + sage: txt = two.igcd._instancedoc_() # optional - maple + sage: txt.find('igcd - greatest common divisor') >= 0 # optional - maple True """ return self._obj.parent()._help(self._name) def _sage_src_(self): """ - Return the source code of self. + Return the source code of ``self``. EXAMPLES:: - sage: g = maple('gcd') # optional - maple + sage: g = maple('gcd') # optional - maple sage: print(g.curry._sage_src_().strip()) # optional - maple - p -> subs('_X' = args[2 .. nargs], () -> p(_X, args)) - sage: m = maple('2') # optional - maple - sage: m.ZZZ._sage_src_() #not tested + ... -> subs('_X' = _passed[2 .. _npassed],() -> ...(_X, _passed)) + sage: m = maple('2') # optional - maple + sage: m.ZZZ._sage_src_() # not tested Traceback (most recent call last): ... Exception: no source code could be found @@ -934,15 +945,16 @@ def __hash__(self): EXAMPLES:: - sage: m = maple('x^2+y^2') # optional - maple - sage: m.__hash__() # optional - maple + sage: # optional - maple + sage: m = maple('x^2+y^2') + sage: m.__hash__() # random 188724254834261060184983038723355865733 - sage: hash(m) # random # optional - maple + sage: hash(m) # random 5035731711831192733 - sage: m = maple('x^2+y^3') # optional - maple - sage: m.__hash__() # random # optional - maple + sage: m = maple('x^2+y^3') + sage: m.__hash__() # random 264835029579301191531663246434344770556 - sage: hash(m) # random # optional - maple + sage: hash(m) # random -2187277978252104690 """ return int(maple.eval('StringTools:-Hash(convert(%s, string))' % self.name())[1:-1], 16) @@ -956,40 +968,44 @@ def _richcmp_(self, other, op): EXAMPLES:: - sage: a = maple(5) # optional - maple - sage: b = maple(5) # optional - maple - sage: a == b # optional - maple + sage: # optional - maple + sage: a = maple(5) + sage: b = maple(5) + sage: a == b True - sage: a == 5 # optional - maple + sage: a == 5 True :: - sage: c = maple(3) # optional - maple - sage: a == c # optional - maple + sage: # optional - maple + sage: c = maple(3) + sage: a == c False - sage: a < c # optional - maple + sage: a < c False - sage: a < 6 # optional - maple + sage: a < 6 True - sage: c <= a # optional - maple + sage: c <= a True :: - sage: M = matrix(ZZ, 2, range(1,5)) # optional - maple - sage: Mm = maple(M) # optional - maple - sage: Mm == Mm # optional - maple + sage: # optional - maple + sage: M = matrix(ZZ, 2, range(1,5)) + sage: Mm = maple(M) + sage: Mm == Mm True TESTS:: + sage: # optional - maple sage: x = var('x') - sage: t = maple((x+1)^2) # optional - maple - sage: u = maple(x^2+2*x+1) # optional - maple + sage: t = maple((x+1)^2) + sage: u = maple(x^2+2*x+1) sage: u == t # todo: not implemented True # returns False, should use 'testeq' in maple - sage: maple.eval('testeq(%s = %s)' % (t.name(),u.name())) # optional - maple + sage: maple.eval('testeq(%s = %s)' % (t.name(),u.name())) 'true' """ P = self.parent() @@ -1024,21 +1040,23 @@ def _mul_(self, right): EXAMPLES:: - sage: t = maple(5); u = maple(3) # optional - maple - sage: t*u # optional - maple + sage: # optional - maple + sage: t = maple(5); u = maple(3) + sage: t*u 15 - sage: t._mul_(u) # optional - maple + sage: t._mul_(u) 15 - sage: M = matrix(ZZ,2,range(4)) # optional - maple - sage: Mm = maple(M) # optional - maple - sage: Mm*Mm # optional - maple + sage: M = matrix(ZZ,2,range(4)) + sage: Mm = maple(M) + sage: Mm*Mm Matrix(2, 2, [[2,3],[6,11]]) :: - sage: v = vector(ZZ,2,[2,3]) # optional - maple - sage: vm = maple(v) # optional - maple - sage: vm*Mm # optional - maple + sage: # optional - maple + sage: v = vector(ZZ,2,[2,3]) + sage: vm = maple(v) + sage: vm*Mm Vector[row](2, [6,11]) :: diff --git a/src/sage/interfaces/polymake.py b/src/sage/interfaces/polymake.py index c857d14daf9..9161ebd5377 100644 --- a/src/sage/interfaces/polymake.py +++ b/src/sage/interfaces/polymake.py @@ -341,7 +341,7 @@ def to_str(x): except NotImplementedError: pass - return super(PolymakeAbstract, self)._coerce_impl(x, use_special=use_special) + return super()._coerce_impl(x, use_special=use_special) def console(self): """ @@ -1587,7 +1587,7 @@ def str_to_base_ring(s): from sage.geometry.polyhedron.backend_polymake import Polyhedron_polymake return Polyhedron_polymake._from_polymake_polytope(None, self) else: - return super(PolymakeElement, self)._sage_() + return super()._sage_() def _sage_doc_(self): """ diff --git a/src/sage/interfaces/r.py b/src/sage/interfaces/r.py index 068e65a2096..bdf50dbfed9 100644 --- a/src/sage/interfaces/r.py +++ b/src/sage/interfaces/r.py @@ -560,7 +560,7 @@ def _coerce_impl(self, x, use_special=True): # cannot be used as input if isinstance(x, bool): return self('TRUE' if x else 'FALSE') - return super(R, self)._coerce_impl(x, use_special=use_special) + return super()._coerce_impl(x, use_special=use_special) def set_seed(self, seed=None): """ diff --git a/src/sage/interfaces/singular.py b/src/sage/interfaces/singular.py index f4e5c6a9158..331d698d3ab 100644 --- a/src/sage/interfaces/singular.py +++ b/src/sage/interfaces/singular.py @@ -1398,7 +1398,7 @@ def _repr_(self): """ - s = super(SingularElement, self)._repr_() + s = super()._repr_() if self._name in s: if self.get_custom_name() is None and self.type() == 'matrix': s = self.parent().eval('pmat(%s,20)' % (self.name())) diff --git a/src/sage/lfunctions/zero_sums.pyx b/src/sage/lfunctions/zero_sums.pyx index 75ee990b1fc..46f84d6f12d 100644 --- a/src/sage/lfunctions/zero_sums.pyx +++ b/src/sage/lfunctions/zero_sums.pyx @@ -1066,7 +1066,7 @@ cdef class LFunctionZeroSum_EllipticCurve(LFunctionZeroSum_abstract): double logq, double thetaq, double sqrtq, - double z): + double z) noexcept: r""" Private cdef method to compute the logarithmic derivative summand for the sinc^2 sum at prime values for when @@ -1096,7 +1096,7 @@ cdef class LFunctionZeroSum_EllipticCurve(LFunctionZeroSum_abstract): double t, int ap, double p, - double logp): + double logp) noexcept: r""" Private cdef method to compute the logarithmic derivative summand for the sinc^2 sum at prime values for when @@ -1109,7 +1109,7 @@ cdef class LFunctionZeroSum_EllipticCurve(LFunctionZeroSum_abstract): logp = c_log(p) return -(t - logp) * (logp / p) * ap - cpdef _zerosum_sincsquared_fast(self, Delta=1, bad_primes=None): + cpdef _zerosum_sincsquared_fast(self, Delta=1, bad_primes=None) noexcept: r""" A faster cythonized implementation of self._zerosum_sincsquared(). diff --git a/src/sage/libs/coxeter3/coxeter.pxd b/src/sage/libs/coxeter3/coxeter.pxd index dbd2b8a61c6..c30ca1925b8 100644 --- a/src/sage/libs/coxeter3/coxeter.pxd +++ b/src/sage/libs/coxeter3/coxeter.pxd @@ -21,11 +21,11 @@ cdef class CoxGroup(SageObject): cdef object cartan_type cdef dict in_ordering cdef dict out_ordering - cpdef object full_context(self) + cpdef object full_context(self) noexcept cdef class CoxGroupElement: cdef c_CoxWord word cdef c_CoxGroup* group cdef CoxGroup _parent_group - cdef CoxGroupElement _new(self) - cpdef CoxGroup parent_group(self) + cdef CoxGroupElement _new(self) noexcept + cpdef CoxGroup parent_group(self) noexcept diff --git a/src/sage/libs/coxeter3/coxeter.pyx b/src/sage/libs/coxeter3/coxeter.pyx index 492afca2768..1b21b010481 100644 --- a/src/sage/libs/coxeter3/coxeter.pyx +++ b/src/sage/libs/coxeter3/coxeter.pyx @@ -540,7 +540,7 @@ cdef class CoxGroup(SageObject): """ return isFiniteType(self.x) - cpdef full_context(self): + cpdef full_context(self) noexcept: """ Make all of the elements of a finite Coxeter group available. @@ -741,7 +741,7 @@ cdef class CoxGroupElement: inverse = __invert__ - cpdef CoxGroup parent_group(self): + cpdef CoxGroup parent_group(self) noexcept: """ Return the parent Coxeter group for this element. @@ -959,7 +959,7 @@ cdef class CoxGroupElement: cdef Generator ss = self._parent_group.in_ordering[s] return self.group.isDescent(self.word, s) - cdef CoxGroupElement _new(self): + cdef CoxGroupElement _new(self) noexcept: """ Return a new copy of this element. """ @@ -1130,7 +1130,7 @@ cdef class CoxGroupElement: cdef CoxNbr y = self.group.extendContext(vv.word) return ZZ(self.group.mu(x,y)) -cdef LFlags_to_list(CoxGroup parent, LFlags f): +cdef LFlags_to_list(CoxGroup parent, LFlags f) noexcept: """ Return the right descent set of this element. diff --git a/src/sage/libs/ecl.pyx b/src/sage/libs/ecl.pyx index a8e73e57b52..a4942781c5e 100644 --- a/src/sage/libs/ecl.pyx +++ b/src/sage/libs/ecl.pyx @@ -28,20 +28,20 @@ from cpython.object cimport Py_EQ, Py_NE #it would be preferrable to let bint_symbolp wrap an efficient macro #but the macro provided in object.h doesn't seem to work -cdef bint bint_symbolp(cl_object obj): +cdef bint bint_symbolp(cl_object obj) noexcept: return not(cl_symbolp(obj) == ECL_NIL) #these type predicates are only provided in "cl_*" form, so we wrap them #with the proper type cast. -cdef bint bint_numberp(cl_object obj): +cdef bint bint_numberp(cl_object obj) noexcept: return not(cl_numberp(obj) == ECL_NIL) -cdef bint bint_integerp(cl_object obj): +cdef bint bint_integerp(cl_object obj) noexcept: return not(cl_integerp(obj) == ECL_NIL) -cdef bint bint_rationalp(cl_object obj): +cdef bint bint_rationalp(cl_object obj) noexcept: return not(cl_rationalp(obj) == ECL_NIL) -cdef bint bint_base_string_p(cl_object obj): +cdef bint bint_base_string_p(cl_object obj) noexcept: return not(si_base_string_p(obj) == ECL_NIL) cdef extern from "eclsig.h": @@ -60,7 +60,7 @@ cdef extern from "eclsig.h": cl_object safe_cl_eval(cl_object *error, cl_object form) -cdef cl_object string_to_object(char * s): +cdef cl_object string_to_object(char * s) noexcept: return ecl_read_from_cstring(s) # We need to keep a list of objects bound to python, to protect them from being @@ -77,7 +77,7 @@ cdef cl_object string_to_object(char * s): # chained in a "free list" for quick allocation (and if the free list is empty # upon allocating a node, the array needs to be extended) -cdef cl_object insert_node_after(cl_object node,cl_object value): +cdef cl_object insert_node_after(cl_object node,cl_object value) noexcept: cdef cl_object next,newnode next=cl_cadr(node) @@ -87,7 +87,7 @@ cdef cl_object insert_node_after(cl_object node,cl_object value): cl_rplacd(cl_cdr(next),newnode) return newnode -cdef void remove_node(cl_object node): +cdef void remove_node(cl_object node) noexcept: cdef cl_object next, prev next=cl_cadr(node) prev=cl_cddr(node) @@ -284,7 +284,7 @@ def init_ecl(): ecl_has_booted = 1 -cdef ecl_string_to_python(cl_object s): +cdef ecl_string_to_python(cl_object s) noexcept: if bint_base_string_p(s): return char_to_str(ecl_base_string_pointer_safe(s)) else: @@ -484,7 +484,7 @@ cdef cl_object python_to_ecl(pyobj, bint read_strings) except NULL: raise TypeError("Unimplemented type for python_to_ecl") -cdef ecl_to_python(cl_object o): +cdef ecl_to_python(cl_object o) noexcept: cdef cl_object s cdef Integer N # conversions from an ecl object to a python object. @@ -663,7 +663,7 @@ cdef class EclObject: cdef cl_object obj #the wrapped object cdef cl_object node #linked list pointer: car(node) == obj - cdef void set_obj(EclObject self, cl_object o): + cdef void set_obj(EclObject self, cl_object o) noexcept: if self.node: remove_node(self.node) self.node=NULL @@ -1341,13 +1341,13 @@ cdef class EclListIterator: return r #input: a cl-object. Output: EclObject wrapping that. -cdef EclObject ecl_wrap(cl_object o): +cdef EclObject ecl_wrap(cl_object o) noexcept: cdef EclObject obj = EclObject.__new__(EclObject) obj.set_obj(o) return obj #convenience routine to more easily evaluate strings -cpdef EclObject ecl_eval(str s): +cpdef EclObject ecl_eval(str s) noexcept: r""" Read and evaluate string in Lisp and return the result diff --git a/src/sage/libs/eclib/mat.pxd b/src/sage/libs/eclib/mat.pxd index 41b0cc628c1..0bba3eb62d5 100644 --- a/src/sage/libs/eclib/mat.pxd +++ b/src/sage/libs/eclib/mat.pxd @@ -4,7 +4,7 @@ cdef class Matrix: cdef mat* M cdef class MatrixFactory: - cdef new_matrix(self, mat M) + cdef new_matrix(self, mat M) noexcept diff --git a/src/sage/libs/eclib/mat.pyx b/src/sage/libs/eclib/mat.pyx index 39dee4afc94..24c5ce55fb2 100644 --- a/src/sage/libs/eclib/mat.pyx +++ b/src/sage/libs/eclib/mat.pyx @@ -240,11 +240,11 @@ cdef class Matrix: cdef class MatrixFactory: - cdef new_matrix(self, mat M): + cdef new_matrix(self, mat M) noexcept: return new_Matrix(M) -cdef Matrix new_Matrix(mat M): +cdef Matrix new_Matrix(mat M) noexcept: cdef Matrix A = Matrix() A.M = new mat(M) return A diff --git a/src/sage/libs/eclib/mwrank.pyx b/src/sage/libs/eclib/mwrank.pyx index 11219ddefa6..49b20a33c0e 100644 --- a/src/sage/libs/eclib/mwrank.pyx +++ b/src/sage/libs/eclib/mwrank.pyx @@ -68,7 +68,7 @@ cdef extern from "wrap.cpp": long two_descent_get_selmer_rank(two_descent* t) void two_descent_saturate(two_descent* t, long sat_bd, long sat_low_bd) -cdef object string_sigoff(char* s): +cdef object string_sigoff(char* s) noexcept: sig_off() # Makes a python string and deletes what is pointed to by s. t = char_to_str(s) @@ -238,7 +238,7 @@ cdef class _bigint: return string_sigoff(bigint_to_str(self.x)) -cdef make_bigint(bigint* x): +cdef make_bigint(bigint* x) noexcept: cdef _bigint y sig_off() y = _bigint.__new__(_bigint) diff --git a/src/sage/libs/flint/fmpq_poly.pxd b/src/sage/libs/flint/fmpq_poly.pxd index 20a797c0197..6050c487835 100644 --- a/src/sage/libs/flint/fmpq_poly.pxd +++ b/src/sage/libs/flint/fmpq_poly.pxd @@ -187,5 +187,5 @@ cdef extern from "flint_wrap.h": void fmpq_poly_tanh_series(fmpq_poly_t, const fmpq_poly_t, slong) # since the fmpq_poly header seems to be lacking this inline function -cdef inline sage_fmpq_poly_max_limbs(const fmpq_poly_t poly): +cdef inline sage_fmpq_poly_max_limbs(const fmpq_poly_t poly) noexcept: return _fmpz_vec_max_limbs(fmpq_poly_numref(poly), fmpq_poly_length(poly)) diff --git a/src/sage/libs/flint/fmpz_factor.pxd b/src/sage/libs/flint/fmpz_factor.pxd index b596e0c04b6..7d28c2795b4 100644 --- a/src/sage/libs/flint/fmpz_factor.pxd +++ b/src/sage/libs/flint/fmpz_factor.pxd @@ -9,4 +9,4 @@ cdef extern from "flint_wrap.h": void fmpz_factor_init(fmpz_factor_t) void fmpz_factor(fmpz_factor_t, const fmpz_t) -cdef fmpz_factor_to_pairlist(const fmpz_factor_t) +cdef fmpz_factor_to_pairlist(const fmpz_factor_t) noexcept diff --git a/src/sage/libs/flint/fmpz_factor.pyx b/src/sage/libs/flint/fmpz_factor.pyx index 330ba3d4d4e..aeb9c76f9e3 100644 --- a/src/sage/libs/flint/fmpz_factor.pyx +++ b/src/sage/libs/flint/fmpz_factor.pyx @@ -2,7 +2,7 @@ from cysignals.signals cimport sig_check from sage.libs.flint.fmpz cimport fmpz_get_mpz from sage.rings.integer cimport Integer -cdef fmpz_factor_to_pairlist(const fmpz_factor_t factors): +cdef fmpz_factor_to_pairlist(const fmpz_factor_t factors) noexcept: r""" Helper function that converts a fmpz_factor_t into a list of (factor, exponent) pairs. The factors are Integers, and the diff --git a/src/sage/libs/flint/nmod_poly_linkage.pxi b/src/sage/libs/flint/nmod_poly_linkage.pxi index 45f4410d785..32087acf9dc 100644 --- a/src/sage/libs/flint/nmod_poly_linkage.pxi +++ b/src/sage/libs/flint/nmod_poly_linkage.pxi @@ -24,16 +24,16 @@ from sage.libs.flint.nmod_poly cimport * from sage.libs.flint.ulong_extras cimport * from sage.structure.factorization import Factorization -cdef inline celement *celement_new(unsigned long n): +cdef inline celement *celement_new(unsigned long n) noexcept: cdef celement *g = sig_malloc(sizeof(nmod_poly_t)) nmod_poly_init(g, n) return g -cdef inline int celement_delete(nmod_poly_t e, unsigned long n): +cdef inline int celement_delete(nmod_poly_t e, unsigned long n) noexcept: nmod_poly_clear(e) sig_free(e) -cdef inline int celement_construct(nmod_poly_t e, unsigned long n): +cdef inline int celement_construct(nmod_poly_t e, unsigned long n) noexcept: """ EXAMPLES:: @@ -43,7 +43,7 @@ cdef inline int celement_construct(nmod_poly_t e, unsigned long n): """ nmod_poly_init(e, n) -cdef inline int celement_destruct(nmod_poly_t e, unsigned long n): +cdef inline int celement_destruct(nmod_poly_t e, unsigned long n) noexcept: """ EXAMPLES:: @@ -66,7 +66,7 @@ cdef inline int celement_gen(nmod_poly_t e, long i, unsigned long n) except -2: nmod_poly_zero(e) nmod_poly_set_coeff_ui(e, 1, 1) -cdef object celement_repr(nmod_poly_t e, unsigned long n): +cdef object celement_repr(nmod_poly_t e, unsigned long n) noexcept: raise NotImplementedError cdef inline int celement_set(nmod_poly_t res, nmod_poly_t a, unsigned long n) except -2: @@ -617,7 +617,7 @@ cdef inline int celement_xgcd(nmod_poly_t res, nmod_poly_t s, nmod_poly_t t, nmo nmod_poly_xgcd(res, s, t, a, b) -cdef factor_helper(Polynomial_zmod_flint poly, bint squarefree=False): +cdef factor_helper(Polynomial_zmod_flint poly, bint squarefree=False) noexcept: """ EXAMPLES:: diff --git a/src/sage/libs/gap/element.pxd b/src/sage/libs/gap/element.pxd index d6bf4f8b3ff..7882414df20 100644 --- a/src/sage/libs/gap/element.pxd +++ b/src/sage/libs/gap/element.pxd @@ -18,20 +18,20 @@ cdef Obj make_gap_record(sage_dict) except NULL cdef Obj make_gap_integer(sage_int) except NULL cdef Obj make_gap_string(sage_string) except NULL -cdef GapElement make_any_gap_element(parent, Obj obj) -cdef GapElement make_GapElement(parent, Obj obj) -cdef GapElement_List make_GapElement_List(parent, Obj obj) -cdef GapElement_Record make_GapElement_Record(parent, Obj obj) -cdef GapElement_Integer make_GapElement_Integer(parent, Obj obj) -cdef GapElement_Rational make_GapElement_Rational(parent, Obj obj) -cdef GapElement_String make_GapElement_String(parent, Obj obj) -cdef GapElement_Boolean make_GapElement_Boolean(parent, Obj obj) -cdef GapElement_Function make_GapElement_Function(parent, Obj obj) -cdef GapElement_Permutation make_GapElement_Permutation(parent, Obj obj) - -cdef char *capture_stdout(Obj, Obj) -cdef char *gap_element_str(Obj) -cdef char *gap_element_repr(Obj) +cdef GapElement make_any_gap_element(parent, Obj obj) noexcept +cdef GapElement make_GapElement(parent, Obj obj) noexcept +cdef GapElement_List make_GapElement_List(parent, Obj obj) noexcept +cdef GapElement_Record make_GapElement_Record(parent, Obj obj) noexcept +cdef GapElement_Integer make_GapElement_Integer(parent, Obj obj) noexcept +cdef GapElement_Rational make_GapElement_Rational(parent, Obj obj) noexcept +cdef GapElement_String make_GapElement_String(parent, Obj obj) noexcept +cdef GapElement_Boolean make_GapElement_Boolean(parent, Obj obj) noexcept +cdef GapElement_Function make_GapElement_Function(parent, Obj obj) noexcept +cdef GapElement_Permutation make_GapElement_Permutation(parent, Obj obj) noexcept + +cdef char *capture_stdout(Obj, Obj) noexcept +cdef char *gap_element_str(Obj) noexcept +cdef char *gap_element_repr(Obj) noexcept cdef class GapElement(RingElement): @@ -43,18 +43,18 @@ cdef class GapElement(RingElement): cdef bint _compare_by_id cdef bint _compare_equal(self, Element other) except -2 cdef bint _compare_less(self, Element other) except -2 - cpdef _set_compare_by_id(self) - cpdef _assert_compare_by_id(self) + cpdef _set_compare_by_id(self) noexcept + cpdef _assert_compare_by_id(self) noexcept - cdef _initialize(self, parent, Obj obj) - cpdef _type_number(self) - cpdef is_bool(self) - cpdef _add_(self, other) - cpdef _mul_(self, other) - cpdef _mod_(self, other) - cpdef _pow_(self, other) + cdef _initialize(self, parent, Obj obj) noexcept + cpdef _type_number(self) noexcept + cpdef is_bool(self) noexcept + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept + cpdef _mod_(self, other) noexcept + cpdef _pow_(self, other) noexcept - cpdef GapElement deepcopy(self, bint mut) + cpdef GapElement deepcopy(self, bint mut) noexcept cdef class GapElement_Integer(GapElement): pass @@ -63,10 +63,10 @@ cdef class GapElement_Rational(GapElement): pass cdef class GapElement_IntegerMod(GapElement): - cpdef GapElement_Integer lift(self) + cpdef GapElement_Integer lift(self) noexcept cdef class GapElement_FiniteField(GapElement): - cpdef GapElement_Integer lift(self) + cpdef GapElement_Integer lift(self) noexcept cdef class GapElement_Cyclotomic(GapElement): pass @@ -87,7 +87,7 @@ cdef class GapElement_MethodProxy(GapElement_Function): cdef GapElement first_argument cdef class GapElement_Record(GapElement): - cpdef UInt record_name_to_index(self, name) + cpdef UInt record_name_to_index(self, name) noexcept cdef class GapElement_RecordIterator(): cdef GapElement_Record rec diff --git a/src/sage/libs/gap/element.pyx b/src/sage/libs/gap/element.pyx index 363024ae281..a5f0dfcd24c 100644 --- a/src/sage/libs/gap/element.pyx +++ b/src/sage/libs/gap/element.pyx @@ -110,7 +110,7 @@ cdef Obj make_gap_matrix(sage_list, gap_ring) except NULL: GAP_Leave() -cdef char *capture_stdout(Obj func, Obj obj): +cdef char *capture_stdout(Obj func, Obj obj) noexcept: """ Call a single-argument GAP function ``func`` with the argument ``obj`` and return the stdout from that function call. @@ -145,7 +145,7 @@ cdef char *capture_stdout(Obj func, Obj obj): GAP_Leave() -cdef char *gap_element_repr(Obj obj): +cdef char *gap_element_repr(Obj obj) noexcept: """ Implement ``repr()`` of ``GapElement``s using the ``ViewObj()`` function, which is by default closest to what you get when displaying an object in @@ -161,7 +161,7 @@ cdef char *gap_element_repr(Obj obj): GAP_Leave() -cdef char *gap_element_str(Obj obj): +cdef char *gap_element_str(Obj obj) noexcept: """ Implement ``str()`` of ``GapElement``s using the ``Print()`` function. @@ -266,7 +266,7 @@ cdef Obj make_gap_string(sage_string) except NULL: ### generic construction of GapElements #################################### ############################################################################ -cdef GapElement make_any_gap_element(parent, Obj obj): +cdef GapElement make_any_gap_element(parent, Obj obj) noexcept: """ Return the GAP element wrapper of ``obj`` @@ -354,7 +354,7 @@ cdef GapElement make_any_gap_element(parent, Obj obj): ### GapElement ############################################################# ############################################################################ -cdef GapElement make_GapElement(parent, Obj obj): +cdef GapElement make_GapElement(parent, Obj obj) noexcept: r""" Turn a Gap C object (of type ``Obj``) into a Cython ``GapElement``. @@ -387,7 +387,7 @@ cdef GapElement make_GapElement(parent, Obj obj): return r -cpdef _from_sage(elem): +cpdef _from_sage(elem) noexcept: """ Currently just used for unpickling; equivalent to calling ``libgap(elem)`` to convert a Sage object to a `GapElement` where possible. @@ -460,7 +460,7 @@ cdef class GapElement(RingElement): """ raise TypeError('this class cannot be instantiated from Python') - cdef _initialize(self, parent, Obj obj): + cdef _initialize(self, parent, Obj obj) noexcept: r""" Initialize the GapElement. @@ -544,7 +544,7 @@ cdef class GapElement(RingElement): else: return self - cpdef GapElement deepcopy(self, bint mut): + cpdef GapElement deepcopy(self, bint mut) noexcept: r""" Return a deepcopy of this Gap object @@ -647,7 +647,7 @@ cdef class GapElement(RingElement): GAP_IN = libgap.eval(r'\in') return GAP_IN(other, self).sage() - cpdef _type_number(self): + cpdef _type_number(self) noexcept: """ Return the GAP internal type number. @@ -776,7 +776,7 @@ cdef class GapElement(RingElement): s = char_to_str(gap_element_repr(self.value)) return s.strip() - cpdef _set_compare_by_id(self): + cpdef _set_compare_by_id(self) noexcept: """ Set comparison to compare by ``id`` @@ -814,7 +814,7 @@ cdef class GapElement(RingElement): """ self._compare_by_id = True - cpdef _assert_compare_by_id(self): + cpdef _assert_compare_by_id(self) noexcept: """ Ensure that comparison is by ``id`` @@ -851,7 +851,7 @@ cdef class GapElement(RingElement): """ return hash(str(self)) - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ Compare ``self`` with ``other``. @@ -973,7 +973,7 @@ cdef class GapElement(RingElement): GAP_Leave() sig_off() - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: r""" Add two GapElement objects. @@ -1002,7 +1002,7 @@ cdef class GapElement(RingElement): GAP_Leave() return make_any_gap_element(self.parent(), result) - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: r""" Subtract two GapElement objects. @@ -1031,7 +1031,7 @@ cdef class GapElement(RingElement): return make_any_gap_element(self.parent(), result) - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: r""" Multiply two GapElement objects. @@ -1060,7 +1060,7 @@ cdef class GapElement(RingElement): GAP_Leave() return make_any_gap_element(self.parent(), result) - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: r""" Divide two GapElement objects. @@ -1094,7 +1094,7 @@ cdef class GapElement(RingElement): GAP_Leave() return make_any_gap_element(self.parent(), result) - cpdef _mod_(self, right): + cpdef _mod_(self, right) noexcept: r""" Modulus of two GapElement objects. @@ -1121,7 +1121,7 @@ cdef class GapElement(RingElement): GAP_Leave() return make_any_gap_element(self.parent(), result) - cpdef _pow_(self, other): + cpdef _pow_(self, other) noexcept: r""" Exponentiation of two GapElement objects. @@ -1170,7 +1170,7 @@ cdef class GapElement(RingElement): GAP_Leave() return make_any_gap_element(self._parent, result) - cpdef _pow_int(self, other): + cpdef _pow_int(self, other) noexcept: """ TESTS:: @@ -1232,7 +1232,7 @@ cdef class GapElement(RingElement): """ return GAP_IsRecord(self.value) - cpdef is_bool(self): + cpdef is_bool(self) noexcept: r""" Return whether the wrapped GAP object is a GAP boolean. @@ -1401,7 +1401,7 @@ cdef class GapElement(RingElement): ### GapElement_Integer ##################################################### ############################################################################ -cdef GapElement_Integer make_GapElement_Integer(parent, Obj obj): +cdef GapElement_Integer make_GapElement_Integer(parent, Obj obj) noexcept: r""" Turn a Gap integer object into a GapElement_Integer Sage object @@ -1555,7 +1555,7 @@ cdef class GapElement_Integer(GapElement): ### GapElement_Float ##################################################### ########################################################################## -cdef GapElement_Float make_GapElement_Float(parent, Obj obj): +cdef GapElement_Float make_GapElement_Float(parent, Obj obj) noexcept: r""" Turn a Gap macfloat object into a GapElement_Float Sage object @@ -1628,7 +1628,7 @@ cdef class GapElement_Float(GapElement): ### GapElement_IntegerMod ##################################################### ############################################################################ -cdef GapElement_IntegerMod make_GapElement_IntegerMod(parent, Obj obj): +cdef GapElement_IntegerMod make_GapElement_IntegerMod(parent, Obj obj) noexcept: r""" Turn a Gap integer object into a :class:`GapElement_IntegerMod` Sage object @@ -1656,7 +1656,7 @@ cdef class GapElement_IntegerMod(GapElement): """ - cpdef GapElement_Integer lift(self): + cpdef GapElement_Integer lift(self) noexcept: """ Return an integer lift. @@ -1709,7 +1709,7 @@ cdef class GapElement_IntegerMod(GapElement): ### GapElement_FiniteField ##################################################### ############################################################################ -cdef GapElement_FiniteField make_GapElement_FiniteField(parent, Obj obj): +cdef GapElement_FiniteField make_GapElement_FiniteField(parent, Obj obj) noexcept: r""" Turn a GAP finite field object into a :class:`GapElement_FiniteField` Sage object @@ -1737,7 +1737,7 @@ cdef class GapElement_FiniteField(GapElement): """ - cpdef GapElement_Integer lift(self): + cpdef GapElement_Integer lift(self) noexcept: """ Return an integer lift. @@ -1876,7 +1876,7 @@ cdef class GapElement_FiniteField(GapElement): ### GapElement_Cyclotomic ##################################################### ############################################################################ -cdef GapElement_Cyclotomic make_GapElement_Cyclotomic(parent, Obj obj): +cdef GapElement_Cyclotomic make_GapElement_Cyclotomic(parent, Obj obj) noexcept: r""" Turn a Gap cyclotomic object into a :class:`GapElement_Cyclotomic` Sage object. @@ -1964,7 +1964,7 @@ cdef class GapElement_Cyclotomic(GapElement): ### GapElement_Rational #################################################### ############################################################################ -cdef GapElement_Rational make_GapElement_Rational(parent, Obj obj): +cdef GapElement_Rational make_GapElement_Rational(parent, Obj obj) noexcept: r""" Turn a Gap Rational number (of type ``Obj``) into a Cython ``GapElement_Rational``. @@ -2036,7 +2036,7 @@ cdef class GapElement_Rational(GapElement): ### GapElement_Ring ##################################################### ############################################################################ -cdef GapElement_Ring make_GapElement_Ring(parent, Obj obj): +cdef GapElement_Ring make_GapElement_Ring(parent, Obj obj) noexcept: r""" Turn a Gap integer object into a :class:`GapElement_Ring` Sage object. @@ -2200,7 +2200,7 @@ cdef class GapElement_Ring(GapElement): ### GapElement_Boolean ##################################################### ############################################################################ -cdef GapElement_Boolean make_GapElement_Boolean(parent, Obj obj): +cdef GapElement_Boolean make_GapElement_Boolean(parent, Obj obj) noexcept: r""" Turn a Gap Boolean number (of type ``Obj``) into a Cython ``GapElement_Boolean``. @@ -2292,7 +2292,7 @@ cdef class GapElement_Boolean(GapElement): ### GapElement_String #################################################### ############################################################################ -cdef GapElement_String make_GapElement_String(parent, Obj obj): +cdef GapElement_String make_GapElement_String(parent, Obj obj) noexcept: r""" Turn a Gap String (of type ``Obj``) into a Cython ``GapElement_String``. @@ -2352,7 +2352,7 @@ cdef class GapElement_String(GapElement): ### GapElement_Function #################################################### ############################################################################ -cdef GapElement_Function make_GapElement_Function(parent, Obj obj): +cdef GapElement_Function make_GapElement_Function(parent, Obj obj) noexcept: r""" Turn a Gap C function object (of type ``Obj``) into a Cython ``GapElement_Function``. @@ -2562,7 +2562,7 @@ cdef class GapElement_Function(GapElement): ### GapElement_MethodProxy ################################################# ############################################################################ -cdef GapElement_MethodProxy make_GapElement_MethodProxy(parent, Obj function, GapElement base_object): +cdef GapElement_MethodProxy make_GapElement_MethodProxy(parent, Obj function, GapElement base_object) noexcept: r""" Turn a Gap C rec object (of type ``Obj``) into a Cython ``GapElement_Record``. @@ -2652,7 +2652,7 @@ cdef class GapElement_MethodProxy(GapElement_Function): ### GapElement_List ######################################################## ############################################################################ -cdef GapElement_List make_GapElement_List(parent, Obj obj): +cdef GapElement_List make_GapElement_List(parent, Obj obj) noexcept: r""" Turn a Gap C List object (of type ``Obj``) into a Cython ``GapElement_List``. @@ -2990,7 +2990,7 @@ cdef class GapElement_List(GapElement): ############################################################################ -cdef GapElement_Permutation make_GapElement_Permutation(parent, Obj obj): +cdef GapElement_Permutation make_GapElement_Permutation(parent, Obj obj) noexcept: r""" Turn a Gap C permutation object (of type ``Obj``) into a Cython ``GapElement_Permutation``. @@ -3055,7 +3055,7 @@ cdef class GapElement_Permutation(GapElement): ### GapElement_Record ###################################################### ############################################################################ -cdef GapElement_Record make_GapElement_Record(parent, Obj obj): +cdef GapElement_Record make_GapElement_Record(parent, Obj obj) noexcept: r""" Turn a Gap C rec object (of type ``Obj``) into a Cython ``GapElement_Record``. @@ -3135,7 +3135,7 @@ cdef class GapElement_Record(GapElement): """ return GapElement_RecordIterator(self) - cpdef UInt record_name_to_index(self, name): + cpdef UInt record_name_to_index(self, name) noexcept: r""" Convert string to GAP record index. diff --git a/src/sage/libs/gap/util.pxd b/src/sage/libs/gap/util.pxd index 118146133f4..e7b499a7b5a 100644 --- a/src/sage/libs/gap/util.pxd +++ b/src/sage/libs/gap/util.pxd @@ -17,25 +17,25 @@ from .gap_includes cimport Obj cdef class ObjWrapper(): cdef Obj value -cdef ObjWrapper wrap_obj(Obj obj) +cdef ObjWrapper wrap_obj(Obj obj) noexcept # returns the refcount dictionary for debugging purposes -cpdef get_owned_objects() +cpdef get_owned_objects() noexcept # Reference count GAP objects that you want to prevent from being # garbage collected -cdef void reference_obj(Obj obj) -cdef void dereference_obj(Obj obj) +cdef void reference_obj(Obj obj) noexcept +cdef void dereference_obj(Obj obj) noexcept # callback from the GAP memory manager so we can mark all_gap_elements.values() -cdef void gasman_callback() with gil +cdef void gasman_callback() noexcept with gil ############################################################################ ### Initialization of GAP ################################################## ############################################################################ -cdef initialize() +cdef initialize() noexcept ############################################################################ diff --git a/src/sage/libs/gap/util.pyx b/src/sage/libs/gap/util.pyx index 3c286d2020d..f4f18589e14 100644 --- a/src/sage/libs/gap/util.pyx +++ b/src/sage/libs/gap/util.pyx @@ -103,7 +103,7 @@ cdef class ObjWrapper(): return (self.value) -cdef ObjWrapper wrap_obj(Obj obj): +cdef ObjWrapper wrap_obj(Obj obj) noexcept: """ Constructor function for :class:`ObjWrapper` """ @@ -120,14 +120,14 @@ cdef dict owned_objects_refcount = dict() # # used in Sage's libgap.Gap.count_GAP_objects # -cpdef get_owned_objects(): +cpdef get_owned_objects() noexcept: """ Helper to access the refcount dictionary from Python code """ return owned_objects_refcount -cdef void reference_obj(Obj obj): +cdef void reference_obj(Obj obj) noexcept: """ Reference ``obj`` """ @@ -140,7 +140,7 @@ cdef void reference_obj(Obj obj): owned_objects_refcount[wrapped] = 1 -cdef void dereference_obj(Obj obj): +cdef void dereference_obj(Obj obj) noexcept: """ Reference ``obj`` """ @@ -151,7 +151,7 @@ cdef void dereference_obj(Obj obj): owned_objects_refcount[wrapped] = refcount - 1 -cdef void gasman_callback() with gil: +cdef void gasman_callback() noexcept with gil: """ Callback before each GAP garbage collection """ @@ -184,7 +184,7 @@ MakeImmutable(libgap_errout); """ -cdef initialize(): +cdef initialize() noexcept: """ Initialize the GAP library, if it hasn't already been initialized. It is safe to call this multiple times. One can set @@ -404,7 +404,7 @@ class GAPError(ValueError): # ValueError for historical reasons """ -cdef str extract_libgap_errout(): +cdef str extract_libgap_errout() noexcept: """ Reads the global variable libgap_errout and returns a Python string containing the error message (with some boilerplate removed). @@ -428,7 +428,7 @@ cdef str extract_libgap_errout(): return msg_py -cdef void error_handler() with gil: +cdef void error_handler() noexcept with gil: """ The libgap error handler. diff --git a/src/sage/libs/glpk/error.pyx b/src/sage/libs/glpk/error.pyx index 2e3ac1c386a..1d265f3ef65 100644 --- a/src/sage/libs/glpk/error.pyx +++ b/src/sage/libs/glpk/error.pyx @@ -41,7 +41,7 @@ class GLPKError(MIPSolverException): cdef error_message = "" -cdef int sage_glpk_term_hook(void *info, const char *s) with gil: +cdef int sage_glpk_term_hook(void *info, const char *s) noexcept with gil: """ A hook to intercept all output written by GLPK. """ @@ -56,7 +56,7 @@ cdef int sage_glpk_term_hook(void *info, const char *s) with gil: return 0 -cdef void sage_glpk_error_hook(void *info) with gil: +cdef void sage_glpk_error_hook(void *info) noexcept with gil: """ A hook to intercept GLPK errors. """ diff --git a/src/sage/libs/gmp/binop.pxd b/src/sage/libs/gmp/binop.pxd index 8ff7aee190d..983e6de5214 100644 --- a/src/sage/libs/gmp/binop.pxd +++ b/src/sage/libs/gmp/binop.pxd @@ -6,17 +6,17 @@ from .types cimport mpz_t, mpq_t from .mpz cimport mpz_set, mpz_add, mpz_mul from .mpq cimport mpq_canonicalize, mpq_numref, mpq_denref, mpq_add -cdef inline void mpq_add_z(mpq_t res, mpq_t op1, mpz_t op2): +cdef inline void mpq_add_z(mpq_t res, mpq_t op1, mpz_t op2) noexcept: mpz_mul(mpq_numref(res), mpq_denref(op1), op2) mpz_add(mpq_numref(res), mpq_numref(res), mpq_numref(op1)) mpz_set(mpq_denref(res), mpq_denref(op1)) -cdef inline void mpq_div_zz(mpq_t res, mpz_t op1, mpz_t op2): +cdef inline void mpq_div_zz(mpq_t res, mpz_t op1, mpz_t op2) noexcept: mpz_set(mpq_numref(res), op1) mpz_set(mpq_denref(res), op2) mpq_canonicalize(res) -cdef inline void mpq_mul_z(mpq_t res, mpq_t op1, mpz_t op2): +cdef inline void mpq_mul_z(mpq_t res, mpq_t op1, mpz_t op2) noexcept: # (A/B) * C = (C/B) * A mpq_div_zz(res, op2, mpq_denref(op1)) mpz_mul(mpq_numref(res), mpq_numref(res), mpq_numref(op1)) diff --git a/src/sage/libs/gmp/pylong.pxd b/src/sage/libs/gmp/pylong.pxd index 84e1bb8cd87..846444d2082 100644 --- a/src/sage/libs/gmp/pylong.pxd +++ b/src/sage/libs/gmp/pylong.pxd @@ -5,7 +5,7 @@ Various functions to deal with conversion mpz <-> Python int/long from cpython.longintrepr cimport py_long from sage.libs.gmp.types cimport * -cdef mpz_get_pylong(mpz_srcptr z) -cdef mpz_get_pyintlong(mpz_srcptr z) +cdef mpz_get_pylong(mpz_srcptr z) noexcept +cdef mpz_get_pyintlong(mpz_srcptr z) noexcept cdef int mpz_set_pylong(mpz_ptr z, py_long L) except -1 -cdef Py_hash_t mpz_pythonhash(mpz_srcptr z) +cdef Py_hash_t mpz_pythonhash(mpz_srcptr z) noexcept diff --git a/src/sage/libs/gmp/pylong.pyx b/src/sage/libs/gmp/pylong.pyx index 1a36c29d3fa..833d44c9bc9 100644 --- a/src/sage/libs/gmp/pylong.pyx +++ b/src/sage/libs/gmp/pylong.pyx @@ -56,7 +56,7 @@ cdef extern from *: cdef size_t PyLong_nails = 8*sizeof(digit) - PyLong_SHIFT -cdef mpz_get_pylong_large(mpz_srcptr z): +cdef mpz_get_pylong_large(mpz_srcptr z) noexcept: """ Convert a non-zero ``mpz`` to a Python ``long``. """ @@ -68,7 +68,7 @@ cdef mpz_get_pylong_large(mpz_srcptr z): return L -cdef mpz_get_pylong(mpz_srcptr z): +cdef mpz_get_pylong(mpz_srcptr z) noexcept: """ Convert an ``mpz`` to a Python ``long``. """ @@ -77,7 +77,7 @@ cdef mpz_get_pylong(mpz_srcptr z): return mpz_get_pylong_large(z) -cdef mpz_get_pyintlong(mpz_srcptr z): +cdef mpz_get_pyintlong(mpz_srcptr z) noexcept: """ Convert an ``mpz`` to a Python ``int`` if possible, or a ``long`` if the value is too large. @@ -97,7 +97,7 @@ cdef int mpz_set_pylong(mpz_ptr z, py_long L) except -1: mpz_neg(z, z) -cdef Py_hash_t mpz_pythonhash(mpz_srcptr z): +cdef Py_hash_t mpz_pythonhash(mpz_srcptr z) noexcept: """ Hash an ``mpz``, where the hash value is the same as the hash value of the corresponding Python ``int`` or ``long``, except that we do diff --git a/src/sage/libs/gmp/randomize.pxd b/src/sage/libs/gmp/randomize.pxd index cdbef70f2c7..3876c0dda13 100644 --- a/src/sage/libs/gmp/randomize.pxd +++ b/src/sage/libs/gmp/randomize.pxd @@ -8,7 +8,7 @@ from sage.misc.randstate cimport randstate, current_randstate, SAGE_RAND_MAX ########################### -cdef inline void mpq_randomize_entry(mpq_t x, mpz_t num_bound, mpz_t den_bound): +cdef inline void mpq_randomize_entry(mpq_t x, mpz_t num_bound, mpz_t den_bound) noexcept: cdef randstate rstate = current_randstate() mpz_urandomm(mpq_numref(x), rstate.gmp_state, num_bound) mpz_urandomm(mpq_denref(x), rstate.gmp_state, den_bound) @@ -18,24 +18,24 @@ cdef inline void mpq_randomize_entry(mpq_t x, mpz_t num_bound, mpz_t den_bound): mpz_mul_si(mpq_numref(x), mpq_numref(x), -1) mpq_canonicalize(x) -cdef inline void mpq_randomize_entry_nonzero(mpq_t x, mpz_t num_bound, mpz_t den_bound): +cdef inline void mpq_randomize_entry_nonzero(mpq_t x, mpz_t num_bound, mpz_t den_bound) noexcept: mpq_randomize_entry(x, num_bound, den_bound) while mpq_sgn(x) == 0: mpq_randomize_entry(x, num_bound, den_bound) -cdef inline void mpq_randomize_entry_as_int(mpq_t x, mpz_t bound): +cdef inline void mpq_randomize_entry_as_int(mpq_t x, mpz_t bound) noexcept: cdef randstate rstate = current_randstate() mpz_urandomm(mpq_numref(x), rstate.gmp_state, bound) mpz_set_si(mpq_denref(x), 1) if rstate.c_random() % 2: mpz_mul_si(mpq_numref(x), mpq_numref(x), -1) -cdef inline void mpq_randomize_entry_as_int_nonzero(mpq_t x, mpz_t bound): +cdef inline void mpq_randomize_entry_as_int_nonzero(mpq_t x, mpz_t bound) noexcept: mpq_randomize_entry_as_int(x, bound) while mpq_sgn(x) == 0: mpq_randomize_entry_as_int(x, bound) -cdef inline void mpq_randomize_entry_recip_uniform(mpq_t x): +cdef inline void mpq_randomize_entry_recip_uniform(mpq_t x) noexcept: cdef randstate rstate = current_randstate() # Numerator is selected the same way as ZZ.random_element(); # denominator is selected in a similar way, but @@ -52,7 +52,7 @@ cdef inline void mpq_randomize_entry_recip_uniform(mpq_t x): mpz_set_si(mpq_denref(x), SAGE_RAND_MAX / den) mpq_canonicalize(x) -cdef inline void mpq_randomize_entry_recip_uniform_nonzero(mpq_t x): +cdef inline void mpq_randomize_entry_recip_uniform_nonzero(mpq_t x) noexcept: mpq_randomize_entry_recip_uniform(x) while mpq_sgn(x) == 0: mpq_randomize_entry_recip_uniform(x) diff --git a/src/sage/libs/lcalc/lcalc_Lfunction.pxd b/src/sage/libs/lcalc/lcalc_Lfunction.pxd index 1d595180a6f..715fa46bba0 100644 --- a/src/sage/libs/lcalc/lcalc_Lfunction.pxd +++ b/src/sage/libs/lcalc/lcalc_Lfunction.pxd @@ -104,14 +104,14 @@ ctypedef double Double cdef class Lfunction: cdef void *thisptr - cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q, c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r) - cdef c_Complex _value(self,c_Complex s,int derivative) - cdef c_Complex _hardy_z_function(self,c_Complex s) - cdef int _compute_rank(self) + cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q, c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r) noexcept + cdef c_Complex _value(self,c_Complex s,int derivative) noexcept + cdef c_Complex _hardy_z_function(self,c_Complex s) noexcept + cdef int _compute_rank(self) noexcept #strange bug, replacing Double with double gives me a compile error - cdef Double _typedN(self, double T) - cdef void _find_zeros_v(self, double T1, double T2, double stepsize,doublevec *result) - cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec* result) + cdef Double _typedN(self, double T) noexcept + cdef void _find_zeros_v(self, double T1, double T2, double stepsize,doublevec *result) noexcept + cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec* result) noexcept cdef str _repr diff --git a/src/sage/libs/lcalc/lcalc_Lfunction.pyx b/src/sage/libs/lcalc/lcalc_Lfunction.pyx index 7b871ed049f..4950ed1d97f 100644 --- a/src/sage/libs/lcalc/lcalc_Lfunction.pyx +++ b/src/sage/libs/lcalc/lcalc_Lfunction.pyx @@ -408,25 +408,25 @@ cdef class Lfunction: return returnvalue # Needs to be overriden - cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q, c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r): + cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q, c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r) noexcept: raise NotImplementedError - cdef c_Complex _value(self,c_Complex s,int derivative): + cdef c_Complex _value(self,c_Complex s,int derivative) noexcept: raise NotImplementedError - cdef c_Complex _hardy_z_function(self,c_Complex s): + cdef c_Complex _hardy_z_function(self,c_Complex s) noexcept: raise NotImplementedError - cdef int _compute_rank(self): + cdef int _compute_rank(self) noexcept: raise NotImplementedError - cdef double _typedN(self,double T): + cdef double _typedN(self,double T) noexcept: raise NotImplementedError - cdef void _find_zeros_v(self,double T1, double T2, double stepsize, doublevec *result): + cdef void _find_zeros_v(self,double T1, double T2, double stepsize, doublevec *result) noexcept: raise NotImplementedError - cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result): + cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result) noexcept: raise NotImplementedError ############################################################################## @@ -497,7 +497,7 @@ cdef class Lfunction_I(Lfunction): self._repr += " with integer Dirichlet coefficients" # override - cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q, c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r): + cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q, c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r) noexcept: cdef int N = len(dirichlet_coeff) cdef Integer tmpi cdef int * coeffs = new_ints(N+1) #lcalc ignores 0the coefficient @@ -507,22 +507,22 @@ cdef class Lfunction_I(Lfunction): self.thisptr=new_c_Lfunction_I(NAME, what_type, N, coeffs, Period, q, w, A, g, l, n_poles, p, r) del_ints(coeffs) - cdef inline c_Complex _value(self,c_Complex s,int derivative): + cdef inline c_Complex _value(self,c_Complex s,int derivative) noexcept: return ((self.thisptr)).value(s, derivative, "pure") - cdef inline c_Complex _hardy_z_function(self,c_Complex s): + cdef inline c_Complex _hardy_z_function(self,c_Complex s) noexcept: return ((self.thisptr)).value(s, 0, "rotated pure") - cdef int _compute_rank(self): + cdef int _compute_rank(self) noexcept: return ((self.thisptr)).compute_rank() - cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result): + cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result) noexcept: (self.thisptr).find_zeros_v(T1,T2,stepsize,result[0]) - cdef double _typedN(self, double T): + cdef double _typedN(self, double T) noexcept: return (self.thisptr).N(T) - cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result): + cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result) noexcept: (self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result) # debug tools @@ -633,7 +633,7 @@ cdef class Lfunction_D(Lfunction): self._repr += " with real Dirichlet coefficients" # override - cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q, c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r): + cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q, c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r) noexcept: cdef int i cdef RealNumber tmpr cdef int N = len(dirichlet_coeff) @@ -644,23 +644,23 @@ cdef class Lfunction_D(Lfunction): self.thisptr=new_c_Lfunction_D(NAME, what_type, N, coeffs, Period, q, w, A, g, l, n_poles, p, r) del_doubles(coeffs) - cdef inline c_Complex _value(self,c_Complex s,int derivative): + cdef inline c_Complex _value(self,c_Complex s,int derivative) noexcept: return ((self.thisptr)).value(s, derivative, "pure") - cdef inline c_Complex _hardy_z_function(self,c_Complex s): + cdef inline c_Complex _hardy_z_function(self,c_Complex s) noexcept: return ((self.thisptr)).value(s, 0, "rotated pure") - cdef inline int _compute_rank(self): + cdef inline int _compute_rank(self) noexcept: return ((self.thisptr)).compute_rank() - cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result): + cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result) noexcept: (self.thisptr).find_zeros_v(T1,T2,stepsize,result[0]) - cdef double _typedN(self, double T): + cdef double _typedN(self, double T) noexcept: return (self.thisptr).N(T) - cdef int _find_zeros(self, long count, long start,double max_refine, int rank, const char* message_stamp, doublevec *result): + cdef int _find_zeros(self, long count, long start,double max_refine, int rank, const char* message_stamp, doublevec *result) noexcept: (self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result) # debug tools @@ -773,7 +773,7 @@ cdef class Lfunction_C: self._repr += " with complex Dirichlet coefficients" # override - cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q, c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r): + cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q, c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r) noexcept: cdef int i cdef int N = len(dirichlet_coeff) cdef ComplexNumber tmpc @@ -788,24 +788,24 @@ cdef class Lfunction_C: del_Complexes(coeffs) - cdef inline c_Complex _value(self,c_Complex s,int derivative): + cdef inline c_Complex _value(self,c_Complex s,int derivative) noexcept: return ((self.thisptr)).value(s, derivative, "pure") - cdef inline c_Complex _hardy_z_function(self,c_Complex s): + cdef inline c_Complex _hardy_z_function(self,c_Complex s) noexcept: return ((self.thisptr)).value(s, 0,"rotated pure") - cdef inline int _compute_rank(self): + cdef inline int _compute_rank(self) noexcept: return ((self.thisptr)).compute_rank() - cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result): + cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result) noexcept: (self.thisptr).find_zeros_v(T1,T2,stepsize,result[0]) - cdef double _typedN(self, double T): + cdef double _typedN(self, double T) noexcept: return (self.thisptr).N(T) - cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result): + cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result) noexcept: (self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result) # debug tools @@ -873,24 +873,24 @@ cdef class Lfunction_Zeta(Lfunction): self.thisptr = new_c_Lfunction_Zeta() self._repr = "The Riemann zeta function" - cdef inline c_Complex _value(self,c_Complex s,int derivative): + cdef inline c_Complex _value(self,c_Complex s,int derivative) noexcept: return ((self.thisptr)).value(s, derivative, "pure") - cdef inline c_Complex _hardy_z_function(self,c_Complex s): + cdef inline c_Complex _hardy_z_function(self,c_Complex s) noexcept: return ((self.thisptr)).value(s, 0, "rotated pure") - cdef inline int _compute_rank(self): + cdef inline int _compute_rank(self) noexcept: return ((self.thisptr)).compute_rank() - cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result): + cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result) noexcept: (self.thisptr).find_zeros_v(T1,T2,stepsize,result[0]) - cdef double _typedN(self, double T): + cdef double _typedN(self, double T) noexcept: return (self.thisptr).N(T) - cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result): + cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result) noexcept: (self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result) def __dealloc__(self): diff --git a/src/sage/libs/linbox/conversion.pxd b/src/sage/libs/linbox/conversion.pxd index 1753277b1f1..f140a0fc321 100644 --- a/src/sage/libs/linbox/conversion.pxd +++ b/src/sage/libs/linbox/conversion.pxd @@ -77,7 +77,7 @@ cdef inline linbox_specifier get_method(str algo) except ERROR: # matrix_modn_sparse (sparse matrix over Z/nZ) # ################################################ -cdef inline void set_linbox_matrix_modn_sparse(SparseMatrix_Modular_uint64& A, Matrix_modn_sparse m): +cdef inline void set_linbox_matrix_modn_sparse(SparseMatrix_Modular_uint64& A, Matrix_modn_sparse m) noexcept: r""" Set the entries of a LinBox matrix from a Sage matrix. @@ -93,7 +93,7 @@ cdef inline void set_linbox_matrix_modn_sparse(SparseMatrix_Modular_uint64& A, M for j in range( row.num_nonzero): A.setEntry(i, row.positions[j], row.entries[j]) -cdef inline SparseMatrix_Modular_uint64 * new_linbox_matrix_modn_sparse(Modular_uint64 &F, Matrix_modn_sparse m): +cdef inline SparseMatrix_Modular_uint64 * new_linbox_matrix_modn_sparse(Modular_uint64 &F, Matrix_modn_sparse m) noexcept: r""" Return a new LinBox matrix from a Sage matrix. @@ -112,7 +112,7 @@ cdef inline SparseMatrix_Modular_uint64 * new_linbox_matrix_modn_sparse(Modular_ # matrix_integer_sparse # ######################### -cdef inline void set_linbox_matrix_integer_sparse(SparseMatrix_integer& A, Matrix_integer_sparse m): +cdef inline void set_linbox_matrix_integer_sparse(SparseMatrix_integer& A, Matrix_integer_sparse m) noexcept: r""" Set the entries of a LinBox matrix from a Sage matrix. @@ -131,7 +131,7 @@ cdef inline void set_linbox_matrix_integer_sparse(SparseMatrix_integer& A, Matri mpz_set(t.get_mpz(), v.entries[k]) A.setEntry(i, j, t) -cdef inline SparseMatrix_integer * new_linbox_matrix_integer_sparse(ZRing &ZZ, Matrix_integer_sparse m): +cdef inline SparseMatrix_integer * new_linbox_matrix_integer_sparse(ZRing &ZZ, Matrix_integer_sparse m) noexcept: r""" Return a new LinBox matrix from a Sage matrix. @@ -149,7 +149,7 @@ cdef inline SparseMatrix_integer * new_linbox_matrix_integer_sparse(ZRing &ZZ, M # vector integer dense # ######################## -cdef inline DenseVector_integer * new_linbox_vector_integer_dense(ZRing &ZZ, Vector_integer_dense v): +cdef inline DenseVector_integer * new_linbox_vector_integer_dense(ZRing &ZZ, Vector_integer_dense v) noexcept: r""" Return a new linbox vector from a sage one. @@ -167,7 +167,7 @@ cdef inline DenseVector_integer * new_linbox_vector_integer_dense(ZRing &ZZ, Vec return V -cdef inline Vector_integer_dense new_sage_vector_integer_dense(P, DenseVector_integer &v): +cdef inline Vector_integer_dense new_sage_vector_integer_dense(P, DenseVector_integer &v) noexcept: r""" Return a new Sage vector from a LinBox one. diff --git a/src/sage/libs/linbox/linbox_flint_interface.pxd b/src/sage/libs/linbox/linbox_flint_interface.pxd index 3cee66657f0..f47d5386a01 100644 --- a/src/sage/libs/linbox/linbox_flint_interface.pxd +++ b/src/sage/libs/linbox/linbox_flint_interface.pxd @@ -5,16 +5,16 @@ from sage.libs.flint.types cimport fmpz_t, fmpz_mat_t, fmpz_poly_t # set C <- A * B -cdef void linbox_fmpz_mat_mul(fmpz_mat_t C, fmpz_mat_t A, fmpz_mat_t B) +cdef void linbox_fmpz_mat_mul(fmpz_mat_t C, fmpz_mat_t A, fmpz_mat_t B) noexcept # set cp to the characteristic polynomial of A -cdef void linbox_fmpz_mat_charpoly(fmpz_poly_t cp, fmpz_mat_t A) +cdef void linbox_fmpz_mat_charpoly(fmpz_poly_t cp, fmpz_mat_t A) noexcept # set mp to the minimal polynomial of A -cdef void linbox_fmpz_mat_minpoly(fmpz_poly_t mp, fmpz_mat_t A) +cdef void linbox_fmpz_mat_minpoly(fmpz_poly_t mp, fmpz_mat_t A) noexcept # return the rank of A -cdef size_t linbox_fmpz_mat_rank(fmpz_mat_t A) +cdef size_t linbox_fmpz_mat_rank(fmpz_mat_t A) noexcept # set det to the determinant of A -cdef void linbox_fmpz_mat_det(fmpz_t det, fmpz_mat_t A) +cdef void linbox_fmpz_mat_det(fmpz_t det, fmpz_mat_t A) noexcept diff --git a/src/sage/libs/linbox/linbox_flint_interface.pyx b/src/sage/libs/linbox/linbox_flint_interface.pyx index 415cd473947..dabd375c2b8 100644 --- a/src/sage/libs/linbox/linbox_flint_interface.pyx +++ b/src/sage/libs/linbox/linbox_flint_interface.pyx @@ -43,7 +43,7 @@ cimport sage.libs.linbox.linbox as linbox from .linbox cimport PolynomialRing_integer -cdef void fmpz_mat_get_linbox(linbox.DenseMatrix_integer& A, fmpz_mat_t m): +cdef void fmpz_mat_get_linbox(linbox.DenseMatrix_integer& A, fmpz_mat_t m) noexcept: r""" Set the entries of A from m (no allocation performed). @@ -59,7 +59,7 @@ cdef void fmpz_mat_get_linbox(linbox.DenseMatrix_integer& A, fmpz_mat_t m): A.setEntry(i, j, t) -cdef void fmpz_mat_set_linbox(fmpz_mat_t m, linbox.DenseMatrix_integer& A): +cdef void fmpz_mat_set_linbox(fmpz_mat_t m, linbox.DenseMatrix_integer& A) noexcept: r""" Set the entries of m from A (no allocation performed). @@ -72,7 +72,7 @@ cdef void fmpz_mat_set_linbox(fmpz_mat_t m, linbox.DenseMatrix_integer& A): fmpz_set_mpz(fmpz_mat_entry(m, i, j), A.getEntry(i, j).get_mpz_const()) -cdef void fmpz_poly_set_linbox(fmpz_poly_t p, PolynomialRing_integer.Element& q): +cdef void fmpz_poly_set_linbox(fmpz_poly_t p, PolynomialRing_integer.Element& q) noexcept: r""" Set the entries of the polynomial p from q (no allocation performed). @@ -89,7 +89,7 @@ cdef void fmpz_poly_set_linbox(fmpz_poly_t p, PolynomialRing_integer.Element& q) _fmpz_poly_set_length(p, q.size()) -cdef void linbox_fmpz_mat_mul(fmpz_mat_t C, fmpz_mat_t A, fmpz_mat_t B): +cdef void linbox_fmpz_mat_mul(fmpz_mat_t C, fmpz_mat_t A, fmpz_mat_t B) noexcept: r""" Set C to be A * B. """ @@ -115,7 +115,7 @@ cdef void linbox_fmpz_mat_mul(fmpz_mat_t C, fmpz_mat_t A, fmpz_mat_t B): fmpz_mat_set_linbox(C, LBC[0]) -cdef void linbox_fmpz_mat_charpoly(fmpz_poly_t cp, fmpz_mat_t A): +cdef void linbox_fmpz_mat_charpoly(fmpz_poly_t cp, fmpz_mat_t A) noexcept: r""" Set cp to the characteristic polynomial of A. """ @@ -133,7 +133,7 @@ cdef void linbox_fmpz_mat_charpoly(fmpz_poly_t cp, fmpz_mat_t A): del m_A -cdef void linbox_fmpz_mat_minpoly(fmpz_poly_t mp, fmpz_mat_t A): +cdef void linbox_fmpz_mat_minpoly(fmpz_poly_t mp, fmpz_mat_t A) noexcept: r""" Set mp to the minimal polynomial of A. """ @@ -151,7 +151,7 @@ cdef void linbox_fmpz_mat_minpoly(fmpz_poly_t mp, fmpz_mat_t A): del m_A -cdef size_t linbox_fmpz_mat_rank(fmpz_mat_t A): +cdef size_t linbox_fmpz_mat_rank(fmpz_mat_t A) noexcept: r""" Return the rank of A """ @@ -168,7 +168,7 @@ cdef size_t linbox_fmpz_mat_rank(fmpz_mat_t A): return r -cdef void linbox_fmpz_mat_det(fmpz_t det, fmpz_mat_t A): +cdef void linbox_fmpz_mat_det(fmpz_t det, fmpz_mat_t A) noexcept: r""" Set det to the determinant of A. """ diff --git a/src/sage/libs/linkages/padics/Polynomial_ram.pxi b/src/sage/libs/linkages/padics/Polynomial_ram.pxi index e0584ecb8ad..2048bb0a3c2 100644 --- a/src/sage/libs/linkages/padics/Polynomial_ram.pxi +++ b/src/sage/libs/linkages/padics/Polynomial_ram.pxi @@ -318,7 +318,7 @@ cdef inline int cpow(celement out, celement a, mpz_t n, long prec, PowComputer_ _expansion_zero = [] # the expansion_mode enum is defined in padic_template_element_header.pxi -cdef inline cexpansion_next(celement value, expansion_mode mode, long curpower, PowComputer_ prime_pow): +cdef inline cexpansion_next(celement value, expansion_mode mode, long curpower, PowComputer_ prime_pow) noexcept: if mode == teichmuller_mode: raise NotImplementedError # This is not very efficient, but there's no clear better way. @@ -339,7 +339,7 @@ cdef inline cexpansion_next(celement value, expansion_mode mode, long curpower, cshift_notrunc(value, value, -1, curpower, prime_pow, False) return term -cdef inline cexpansion_getitem(celement value, long m, PowComputer_ prime_pow): +cdef inline cexpansion_getitem(celement value, long m, PowComputer_ prime_pow) noexcept: """ Return the `m`th `p`-adic digit in the ``simple_mode`` expansion. @@ -383,7 +383,7 @@ cdef int cteichmuller(celement out, celement value, long prec, PowComputer_ prim else: out._coeffs = [value[0].parent().teichmuller(value[0])] -cdef list ccoefficients(celement x, long valshift, long prec, PowComputer_ prime_pow): +cdef list ccoefficients(celement x, long valshift, long prec, PowComputer_ prime_pow) noexcept: """ Return a list of coefficients, as elements that can be converted into the base ring. diff --git a/src/sage/libs/linkages/padics/Polynomial_shared.pxi b/src/sage/libs/linkages/padics/Polynomial_shared.pxi index 367bbc2f33d..b210b53ce19 100644 --- a/src/sage/libs/linkages/padics/Polynomial_shared.pxi +++ b/src/sage/libs/linkages/padics/Polynomial_shared.pxi @@ -332,7 +332,7 @@ cdef inline int ccopy(celement out, celement a, PowComputer_ prime_pow) except - """ out._coeffs = a._coeffs[:] -cdef inline cpickle(celement a, PowComputer_ prime_pow): +cdef inline cpickle(celement a, PowComputer_ prime_pow) noexcept: r""" Return a representation of ``a`` for pickling. diff --git a/src/sage/libs/linkages/padics/fmpz_poly_unram.pxi b/src/sage/libs/linkages/padics/fmpz_poly_unram.pxi index 843070f4a42..afb9d191609 100644 --- a/src/sage/libs/linkages/padics/fmpz_poly_unram.pxi +++ b/src/sage/libs/linkages/padics/fmpz_poly_unram.pxi @@ -497,7 +497,7 @@ cdef inline int ccopy(celement out, celement a, PowComputer_ prime_pow) except - """ fmpz_poly_set(out, a) -cdef inline cpickle(celement a, PowComputer_ prime_pow): +cdef inline cpickle(celement a, PowComputer_ prime_pow) noexcept: """ Serialization into objects that Sage knows how to pickle. @@ -544,7 +544,7 @@ cdef inline long chash(celement a, long ordp, long prec, PowComputer_ prime_pow) fmpz_poly_get_coeff_mpz(h.value, a, 0) return hash(h) -cdef inline cmodp_rep(fmpz_poly_t rep, fmpz_poly_t value, expansion_mode mode, bint return_list, PowComputer_ prime_pow): +cdef inline cmodp_rep(fmpz_poly_t rep, fmpz_poly_t value, expansion_mode mode, bint return_list, PowComputer_ prime_pow) noexcept: """ Compute a polynomial that is reduced modulo p and equivalent to the given value. @@ -577,7 +577,7 @@ cdef inline cmodp_rep(fmpz_poly_t rep, fmpz_poly_t value, expansion_mode mode, b return L # the expansion_mode enum is defined in padic_template_element_header.pxi -cdef inline cexpansion_next(fmpz_poly_t value, expansion_mode mode, long curpower, PowComputer_ prime_pow): +cdef inline cexpansion_next(fmpz_poly_t value, expansion_mode mode, long curpower, PowComputer_ prime_pow) noexcept: """ Return the next digit in a `p`-adic expansion of ``value``. @@ -607,7 +607,7 @@ cdef inline cexpansion_next(fmpz_poly_t value, expansion_mode mode, long curpowe _fmpz_poly_normalise(value) return trim_zeros(ans) # defined in sage.rings.padics.misc and imported in padic_template_element -cdef inline cexpansion_getitem(fmpz_poly_t value, long m, PowComputer_ prime_pow): +cdef inline cexpansion_getitem(fmpz_poly_t value, long m, PowComputer_ prime_pow) noexcept: """ Return the `m`th `p`-adic digit in the ``simple_mode`` expansion. @@ -637,7 +637,7 @@ cdef inline cexpansion_getitem(fmpz_poly_t value, long m, PowComputer_ prime_pow # The element is filled in for zero in the p-adic expansion if necessary. _expansion_zero = [] -cdef list ccoefficients(celement x, long valshift, long prec, PowComputer_ prime_pow): +cdef list ccoefficients(celement x, long valshift, long prec, PowComputer_ prime_pow) noexcept: """ Return a list of coefficients, as elements that can be converted into the base ring. @@ -847,7 +847,7 @@ cdef inline int cconv_mpz_t_out(mpz_t out, celement x, long valshift, long prec, ## Extra functions ## -cdef cmatrix_mod_pn(celement a, long aprec, long valshift, PowComputer_ prime_pow): +cdef cmatrix_mod_pn(celement a, long aprec, long valshift, PowComputer_ prime_pow) noexcept: r""" Returns the matrix of right multiplication by the element on the power basis `1, x, x^2, \ldots, x^{d-1}` for this diff --git a/src/sage/libs/linkages/padics/mpz.pxi b/src/sage/libs/linkages/padics/mpz.pxi index 3a555e441dc..ba8c143f3b7 100644 --- a/src/sage/libs/linkages/padics/mpz.pxi +++ b/src/sage/libs/linkages/padics/mpz.pxi @@ -435,7 +435,7 @@ cdef inline int ccopy(mpz_t out, mpz_t a, PowComputer_ prime_pow) except -1: """ mpz_set(out, a) -cdef inline cpickle(mpz_t a, PowComputer_ prime_pow): +cdef inline cpickle(mpz_t a, PowComputer_ prime_pow) noexcept: """ Serialization into objects that Sage knows how to pickle. @@ -493,7 +493,7 @@ cdef inline long chash(mpz_t a, long ordp, long prec, PowComputer_ prime_pow) ex return n # the expansion_mode enum is defined in padic_template_element_header.pxi -cdef inline cexpansion_next(mpz_t value, expansion_mode mode, long curpower, PowComputer_ prime_pow): +cdef inline cexpansion_next(mpz_t value, expansion_mode mode, long curpower, PowComputer_ prime_pow) noexcept: """ Return the next digit in a `p`-adic expansion of ``value``. @@ -523,7 +523,7 @@ cdef inline cexpansion_next(mpz_t value, expansion_mode mode, long curpower, Pow mpz_sub(value, value, prime_pow.pow_mpz_t_tmp(curpower)) return ans -cdef inline cexpansion_getitem(mpz_t value, long m, PowComputer_ prime_pow): +cdef inline cexpansion_getitem(mpz_t value, long m, PowComputer_ prime_pow) noexcept: """ Return the `m`th `p`-adic digit in the ``simple_mode`` expansion. @@ -545,7 +545,7 @@ cdef inline cexpansion_getitem(mpz_t value, long m, PowComputer_ prime_pow): # It could be [] for some other linkages. _expansion_zero = Integer(0) -cdef list ccoefficients(mpz_t x, long valshift, long prec, PowComputer_ prime_pow): +cdef list ccoefficients(mpz_t x, long valshift, long prec, PowComputer_ prime_pow) noexcept: """ Return a list of coefficients, as elements that can be converted into the base ring. diff --git a/src/sage/libs/linkages/padics/relaxed/flint.pxi b/src/sage/libs/linkages/padics/relaxed/flint.pxi index 5955ea23e18..3dab6ecbc30 100644 --- a/src/sage/libs/linkages/padics/relaxed/flint.pxi +++ b/src/sage/libs/linkages/padics/relaxed/flint.pxi @@ -44,7 +44,7 @@ from sage.rings.finite_rings.finite_field_constructor import GF cdef fmpz_t digit_zero digit_init(digit_zero) -cdef inline void digit_init(fmpz_t a): +cdef inline void digit_init(fmpz_t a) noexcept: r""" Initialize a digit and set to it the value `0`. @@ -54,7 +54,7 @@ cdef inline void digit_init(fmpz_t a): """ fmpz_init(a) -cdef inline void digit_clear(fmpz_t a): +cdef inline void digit_clear(fmpz_t a) noexcept: r""" Deallocate memory assigned to a digit. @@ -66,7 +66,7 @@ cdef inline void digit_clear(fmpz_t a): # get and set -cdef inline Integer digit_get_sage(fmpz_t a): +cdef inline Integer digit_get_sage(fmpz_t a) noexcept: r""" Convert a digit to a Sage element. @@ -82,7 +82,7 @@ cdef inline Integer digit_get_sage(fmpz_t a): fmpz_get_mpz(elt.value, a) return elt -cdef inline void digit_set(fmpz_t a, fmpz_t b): +cdef inline void digit_set(fmpz_t a, fmpz_t b) noexcept: r""" Set up a digit. @@ -93,7 +93,7 @@ cdef inline void digit_set(fmpz_t a, fmpz_t b): """ fmpz_set(a, b) -cdef inline void digit_set_ui(fmpz_t a, slong b): +cdef inline void digit_set_ui(fmpz_t a, slong b) noexcept: r""" Set an integral value of a digit. @@ -104,7 +104,7 @@ cdef inline void digit_set_ui(fmpz_t a, slong b): """ fmpz_set_ui(a, b) -cdef inline void digit_set_sage(fmpz_t a, Integer elt): +cdef inline void digit_set_sage(fmpz_t a, Integer elt) noexcept: r""" Set the value of a digit. @@ -117,7 +117,7 @@ cdef inline void digit_set_sage(fmpz_t a, Integer elt): # comparisons -cdef inline bint digit_equal(fmpz_t a, fmpz_t b): +cdef inline bint digit_equal(fmpz_t a, fmpz_t b) noexcept: r""" Comparison of two digits. @@ -132,7 +132,7 @@ cdef inline bint digit_equal(fmpz_t a, fmpz_t b): """ return fmpz_equal(a, b) -cdef inline bint digit_equal_ui(fmpz_t a, slong b): +cdef inline bint digit_equal_ui(fmpz_t a, slong b) noexcept: r""" Comparison of a digit and an integer @@ -147,7 +147,7 @@ cdef inline bint digit_equal_ui(fmpz_t a, slong b): """ return fmpz_equal_ui(a, b) -cdef inline bint digit_is_zero(fmpz_t a): +cdef inline bint digit_is_zero(fmpz_t a) noexcept: r""" Comparison to zero @@ -163,7 +163,7 @@ cdef inline bint digit_is_zero(fmpz_t a): # random -cdef inline void digit_random_init(flint_rand_t generator, slong seed): +cdef inline void digit_random_init(flint_rand_t generator, slong seed) noexcept: r""" Initialize the random generator with a new seed @@ -174,7 +174,7 @@ cdef inline void digit_random_init(flint_rand_t generator, slong seed): """ flint_randseed(generator, seed, seed*seed + 1) -cdef inline void digit_random(fmpz_t res, PowComputer_flint prime_pow, flint_rand_t generator): +cdef inline void digit_random(fmpz_t res, PowComputer_flint prime_pow, flint_rand_t generator) noexcept: r""" Set a digit to a random value in the distinguished set of representatives. @@ -187,7 +187,7 @@ cdef inline void digit_random(fmpz_t res, PowComputer_flint prime_pow, flint_ran # operations -cdef inline void digit_add(fmpz_t res, fmpz_t a, fmpz_t b): +cdef inline void digit_add(fmpz_t res, fmpz_t a, fmpz_t b) noexcept: r""" Add two digits. @@ -199,7 +199,7 @@ cdef inline void digit_add(fmpz_t res, fmpz_t a, fmpz_t b): """ fmpz_add(res, a, b) -cdef inline void digit_sub(fmpz_t res, fmpz_t a, fmpz_t b): +cdef inline void digit_sub(fmpz_t res, fmpz_t a, fmpz_t b) noexcept: r""" Subtract two digits. @@ -211,7 +211,7 @@ cdef inline void digit_sub(fmpz_t res, fmpz_t a, fmpz_t b): """ fmpz_sub(res, a, b) -cdef inline void digit_mul(fmpz_t res, fmpz_t a, fmpz_t b): +cdef inline void digit_mul(fmpz_t res, fmpz_t a, fmpz_t b) noexcept: r""" Multiply two digits. @@ -223,7 +223,7 @@ cdef inline void digit_mul(fmpz_t res, fmpz_t a, fmpz_t b): """ fmpz_mul(res, a, b) -cdef inline void digit_mod(fmpz_t res, fmpz_t a, PowComputer_flint prime_pow): +cdef inline void digit_mod(fmpz_t res, fmpz_t a, PowComputer_flint prime_pow) noexcept: r""" Reduce a digit modulo the uniformizer. @@ -235,7 +235,7 @@ cdef inline void digit_mod(fmpz_t res, fmpz_t a, PowComputer_flint prime_pow): """ fmpz_mod(res, a, prime_pow.fprime) -cdef inline void digit_quorem(fmpz_t quo, fmpz_t rem, fmpz_t a, PowComputer_flint prime_pow): +cdef inline void digit_quorem(fmpz_t quo, fmpz_t rem, fmpz_t a, PowComputer_flint prime_pow) noexcept: r""" Reduce a digit modulo the uniformizer and keep the carry. @@ -248,7 +248,7 @@ cdef inline void digit_quorem(fmpz_t quo, fmpz_t rem, fmpz_t a, PowComputer_flin """ fmpz_tdiv_qr(quo, rem, a, prime_pow.fprime) -cdef inline void digit_smallest(cdigit res, cdigit carry, cdigit a, PowComputer_flint prime_pow): +cdef inline void digit_smallest(cdigit res, cdigit carry, cdigit a, PowComputer_flint prime_pow) noexcept: r""" Compute the smallest representative of a digit. @@ -275,7 +275,7 @@ cdef inline void digit_smallest(cdigit res, cdigit carry, cdigit a, PowComputer_ fmpz_set_ui(carry, 0) fmpz_clear(b) -cdef inline void digit_inv(fmpz_t res, fmpz_t a, PowComputer_flint prime_pow): +cdef inline void digit_inv(fmpz_t res, fmpz_t a, PowComputer_flint prime_pow) noexcept: r""" Compute the multiplicative inverse of a digit modulo the uniformizer. @@ -290,7 +290,7 @@ cdef inline void digit_inv(fmpz_t res, fmpz_t a, PowComputer_flint prime_pow): fmpz_gcdinv(gcd, res, a, prime_pow.fprime) fmpz_clear(gcd) -cdef bint digit_sqrt(fmpz_t ans, fmpz_t x, PowComputer_flint prime_pow): +cdef bint digit_sqrt(fmpz_t ans, fmpz_t x, PowComputer_flint prime_pow) noexcept: r""" Compute the square root of a digit modulo the uniformizer. @@ -306,7 +306,7 @@ cdef bint digit_sqrt(fmpz_t ans, fmpz_t x, PowComputer_flint prime_pow): # Operations on elements (represented as series of digits) ########################################################## -cdef inline void element_init(fmpz_poly_t x): +cdef inline void element_init(fmpz_poly_t x) noexcept: r""" Initialize an element. @@ -316,7 +316,7 @@ cdef inline void element_init(fmpz_poly_t x): """ fmpz_poly_init(x) -cdef inline void element_clear(fmpz_poly_t x): +cdef inline void element_clear(fmpz_poly_t x) noexcept: r""" Deallocate memory assigned to an element. @@ -328,7 +328,7 @@ cdef inline void element_clear(fmpz_poly_t x): # get and set -cdef inline Integer element_get_sage(fmpz_poly_t x, PowComputer_flint prime_pow): +cdef inline Integer element_get_sage(fmpz_poly_t x, PowComputer_flint prime_pow) noexcept: r""" Convert a digit to a Sage element. @@ -348,7 +348,7 @@ cdef inline Integer element_get_sage(fmpz_poly_t x, PowComputer_flint prime_pow) fmpz_clear(value) return ans -cdef inline void element_set(fmpz_poly_t x, fmpz_poly_t y): +cdef inline void element_set(fmpz_poly_t x, fmpz_poly_t y) noexcept: r""" Set an element @@ -361,7 +361,7 @@ cdef inline void element_set(fmpz_poly_t x, fmpz_poly_t y): # get and set digits -cdef inline fmpz* element_get_digit(fmpz_poly_t x, slong i): +cdef inline fmpz* element_get_digit(fmpz_poly_t x, slong i) noexcept: r""" Return the `i`-th coefficient of `x`. @@ -372,7 +372,7 @@ cdef inline fmpz* element_get_digit(fmpz_poly_t x, slong i): """ return get_coeff(x, i) -cdef inline void element_get_slice(fmpz_poly_t res, fmpz_poly_t x, slong start, slong length): +cdef inline void element_get_slice(fmpz_poly_t res, fmpz_poly_t x, slong start, slong length) noexcept: r""" Select a slice of an element. @@ -391,7 +391,7 @@ cdef inline void element_get_slice(fmpz_poly_t res, fmpz_poly_t x, slong start, """ get_slice(res, x, start, length) -cdef inline void element_set_digit(fmpz_poly_t x, fmpz_t a, slong i): +cdef inline void element_set_digit(fmpz_poly_t x, fmpz_t a, slong i) noexcept: r""" Set `i`-th coefficient of `x` to the value `a`. @@ -403,7 +403,7 @@ cdef inline void element_set_digit(fmpz_poly_t x, fmpz_t a, slong i): """ fmpz_poly_set_coeff_fmpz(x, i, a) -cdef inline void element_set_digit_ui(fmpz_poly_t x, slong a, slong i): +cdef inline void element_set_digit_ui(fmpz_poly_t x, slong a, slong i) noexcept: r""" Set `i`-th coefficient of `x` to the value `a`. @@ -415,7 +415,7 @@ cdef inline void element_set_digit_ui(fmpz_poly_t x, slong a, slong i): """ fmpz_poly_set_coeff_ui(x, i, a) -cdef inline void element_set_digit_sage(fmpz_poly_t x, Integer a, slong i): +cdef inline void element_set_digit_sage(fmpz_poly_t x, Integer a, slong i) noexcept: r""" Set `i`-th coefficient of `x` to the value `a`. @@ -429,7 +429,7 @@ cdef inline void element_set_digit_sage(fmpz_poly_t x, Integer a, slong i): # operations -cdef inline void element_iadd_digit(fmpz_poly_t x, fmpz_t a, slong i): +cdef inline void element_iadd_digit(fmpz_poly_t x, fmpz_t a, slong i) noexcept: r""" Inplace addition: add `a` to the `i`-th coefficient of `x`. @@ -442,7 +442,7 @@ cdef inline void element_iadd_digit(fmpz_poly_t x, fmpz_t a, slong i): """ iadd_coeff(x, a, i) -cdef inline void element_isub_digit(fmpz_poly_t x, fmpz_t a, slong i): +cdef inline void element_isub_digit(fmpz_poly_t x, fmpz_t a, slong i) noexcept: r""" Inplace subtraction: subtract `a` to the `i`-th coefficient of `x`. @@ -455,7 +455,7 @@ cdef inline void element_isub_digit(fmpz_poly_t x, fmpz_t a, slong i): """ isub_coeff(x, a, i) -cdef inline void element_iadd_slice(fmpz_poly_t x, fmpz_poly_t slice, slong start): +cdef inline void element_iadd_slice(fmpz_poly_t x, fmpz_poly_t slice, slong start) noexcept: r""" Inplace addition: add a slice to an element @@ -468,7 +468,7 @@ cdef inline void element_iadd_slice(fmpz_poly_t x, fmpz_poly_t slice, slong star """ iadd_shifted(x, slice, start) -cdef inline void element_scalarmul(fmpz_poly_t res, fmpz_poly_t x, fmpz_t a): +cdef inline void element_scalarmul(fmpz_poly_t res, fmpz_poly_t x, fmpz_t a) noexcept: r""" Scalar multiplication. @@ -480,7 +480,7 @@ cdef inline void element_scalarmul(fmpz_poly_t res, fmpz_poly_t x, fmpz_t a): """ fmpz_poly_scalar_mul_fmpz(res, x, a) -cdef inline void element_mul(fmpz_poly_t res, fmpz_poly_t x, fmpz_poly_t y): +cdef inline void element_mul(fmpz_poly_t res, fmpz_poly_t x, fmpz_poly_t y) noexcept: r""" Multiplication. @@ -492,7 +492,7 @@ cdef inline void element_mul(fmpz_poly_t res, fmpz_poly_t x, fmpz_poly_t y): """ fmpz_poly_mul(res, x, y) -cdef inline void element_reduce_digit(fmpz_poly_t x, slong i, PowComputer_flint prime_pow): +cdef inline void element_reduce_digit(fmpz_poly_t x, slong i, PowComputer_flint prime_pow) noexcept: r""" Reduce the `i`-th digit of `x` and propagate carry. @@ -504,7 +504,7 @@ cdef inline void element_reduce_digit(fmpz_poly_t x, slong i, PowComputer_flint """ reduce_coeff(x, i, prime_pow.fprime) -cdef inline void element_reducesmall_digit(fmpz_poly_t x, slong i, PowComputer_flint prime_pow): +cdef inline void element_reducesmall_digit(fmpz_poly_t x, slong i, PowComputer_flint prime_pow) noexcept: r""" Reduce the `i`-th digit of `x` and propagate carry, assuming that `x` is between `0` and `2*p - 1`. @@ -517,7 +517,7 @@ cdef inline void element_reducesmall_digit(fmpz_poly_t x, slong i, PowComputer_f """ reducesmall_coeff(x, i, prime_pow.fprime) -cdef inline void element_reduceneg_digit(fmpz_poly_t x, slong i, PowComputer_flint prime_pow): +cdef inline void element_reduceneg_digit(fmpz_poly_t x, slong i, PowComputer_flint prime_pow) noexcept: r""" Reduce the `i`-th digit of `x` and propagate carry, assuming that `x` is between `-p` and `p-1`. @@ -530,7 +530,7 @@ cdef inline void element_reduceneg_digit(fmpz_poly_t x, slong i, PowComputer_fli """ reduceneg_coeff(x, i, prime_pow.fprime) -cdef inline void element_shift_right(fmpz_poly_t x): +cdef inline void element_shift_right(fmpz_poly_t x) noexcept: r""" Remove the first digit of ``x``. diff --git a/src/sage/libs/meataxe.pyx b/src/sage/libs/meataxe.pyx index 40cb7c6a286..46559e9e99c 100644 --- a/src/sage/libs/meataxe.pyx +++ b/src/sage/libs/meataxe.pyx @@ -71,7 +71,7 @@ cdef Matrix_t *rawMatrix(int Field, list entries) except NULL: from sage.cpython.string cimport str_to_bytes, char_to_str -cdef void sage_meataxe_error_handler(const MtxErrorRecord_t *err): +cdef void sage_meataxe_error_handler(const MtxErrorRecord_t *err) noexcept: sig_block() ErrText = char_to_str(err.Text) BaseName = char_to_str(err.FileInfo.BaseName) @@ -79,7 +79,7 @@ cdef void sage_meataxe_error_handler(const MtxErrorRecord_t *err): PyErr_SetObject(ErrMsg.get(ErrText.split(': ')[-1], RuntimeError), f"{ErrText} in file {BaseName} (line {LineNo})") sig_unblock() -cdef inline meataxe_init(): +cdef inline meataxe_init() noexcept: ## Assign to a variable that enables MeatAxe to find ## its multiplication tables. global MtxLibDir diff --git a/src/sage/libs/mpmath/ext_impl.pxd b/src/sage/libs/mpmath/ext_impl.pxd index b934826ef56..f2540d326dd 100644 --- a/src/sage/libs/mpmath/ext_impl.pxd +++ b/src/sage/libs/mpmath/ext_impl.pxd @@ -4,63 +4,63 @@ ctypedef struct MPopts: long prec int rounding -cdef mpz_set_integer(mpz_t v, x) -cdef mpzi(mpz_t n) -cdef mpzl(mpz_t n) -cdef str rndmode_to_python(int rnd) -cdef rndmode_from_python(str rnd) +cdef mpz_set_integer(mpz_t v, x) noexcept +cdef mpzi(mpz_t n) noexcept +cdef mpzl(mpz_t n) noexcept +cdef str rndmode_to_python(int rnd) noexcept +cdef rndmode_from_python(str rnd) noexcept ctypedef struct MPF: mpz_t man mpz_t exp int special -cdef void MPF_init(MPF *x) -cdef void MPF_clear(MPF *x) -cdef void MPF_set(MPF *dest, MPF *src) -cdef void MPF_set_zero(MPF *x) -cdef void MPF_set_one(MPF *x) -cdef void MPF_set_nan(MPF *x) -cdef void MPF_set_inf(MPF *x) -cdef void MPF_set_ninf(MPF *x) -cdef MPF_set_si(MPF *x, long n) -cdef MPF_set_int(MPF *x, n) -cdef MPF_set_man_exp(MPF *x, man, exp) -cdef MPF_set_tuple(MPF *x, tuple value) -cdef MPF_to_tuple(MPF *x) -cdef MPF_set_double(MPF *r, double x) -cdef double MPF_to_double(MPF *x, bint strict) -cdef MPF_to_fixed(mpz_t r, MPF *x, long prec, bint truncate) -cdef int MPF_sgn(MPF *x) -cdef void MPF_neg(MPF *r, MPF *s) -cdef void MPF_abs(MPF *r, MPF *s) -cdef MPF_normalize(MPF *x, MPopts opts) -cdef void MPF_pos(MPF *x, MPF *y, MPopts opts) -cdef MPF_add(MPF *r, MPF *s, MPF *t, MPopts opts) -cdef MPF_sub(MPF *r, MPF *s, MPF *t, MPopts opts) -cdef bint MPF_eq(MPF *s, MPF *t) -cdef bint MPF_ne(MPF *s, MPF *t) -cdef int MPF_cmp(MPF *s, MPF *t) -cdef bint MPF_lt(MPF *s, MPF *t) -cdef bint MPF_le(MPF *s, MPF *t) -cdef bint MPF_gt(MPF *s, MPF *t) -cdef bint MPF_ge(MPF *s, MPF *t) -cdef MPF_mul(MPF *r, MPF *s, MPF *t, MPopts opts) -cdef MPF_div(MPF *r, MPF *s, MPF *t, MPopts opts) -cdef int MPF_sqrt(MPF *r, MPF *s, MPopts opts) -cdef MPF_hypot(MPF *r, MPF *a, MPF *b, MPopts opts) -cdef MPF_pow_int(MPF *r, MPF *x, mpz_t n, MPopts opts) -cdef MPF_set_double(MPF *r, double x) -cdef MPF_exp(MPF *y, MPF *x, MPopts opts) -cdef MPF_complex_sqrt(MPF *c, MPF *d, MPF *a, MPF *b, MPopts opts) -cdef MPF_complex_exp(MPF *re, MPF *im, MPF *a, MPF *b, MPopts opts) -cdef int MPF_log(MPF *y, MPF *x, MPopts opts) -cdef MPF_set_pi(MPF *x, MPopts opts) -cdef MPF_set_ln2(MPF *x, MPopts opts) -cdef MPF_cos(MPF *c, MPF *x, MPopts opts) -cdef MPF_sin(MPF *c, MPF *x, MPopts opts) -cdef MPF_cos_sin(MPF *c, MPF *s, MPF *x, MPopts opts) +cdef void MPF_init(MPF *x) noexcept +cdef void MPF_clear(MPF *x) noexcept +cdef void MPF_set(MPF *dest, MPF *src) noexcept +cdef void MPF_set_zero(MPF *x) noexcept +cdef void MPF_set_one(MPF *x) noexcept +cdef void MPF_set_nan(MPF *x) noexcept +cdef void MPF_set_inf(MPF *x) noexcept +cdef void MPF_set_ninf(MPF *x) noexcept +cdef MPF_set_si(MPF *x, long n) noexcept +cdef MPF_set_int(MPF *x, n) noexcept +cdef MPF_set_man_exp(MPF *x, man, exp) noexcept +cdef MPF_set_tuple(MPF *x, tuple value) noexcept +cdef MPF_to_tuple(MPF *x) noexcept +cdef MPF_set_double(MPF *r, double x) noexcept +cdef double MPF_to_double(MPF *x, bint strict) noexcept +cdef MPF_to_fixed(mpz_t r, MPF *x, long prec, bint truncate) noexcept +cdef int MPF_sgn(MPF *x) noexcept +cdef void MPF_neg(MPF *r, MPF *s) noexcept +cdef void MPF_abs(MPF *r, MPF *s) noexcept +cdef MPF_normalize(MPF *x, MPopts opts) noexcept +cdef void MPF_pos(MPF *x, MPF *y, MPopts opts) noexcept +cdef MPF_add(MPF *r, MPF *s, MPF *t, MPopts opts) noexcept +cdef MPF_sub(MPF *r, MPF *s, MPF *t, MPopts opts) noexcept +cdef bint MPF_eq(MPF *s, MPF *t) noexcept +cdef bint MPF_ne(MPF *s, MPF *t) noexcept +cdef int MPF_cmp(MPF *s, MPF *t) noexcept +cdef bint MPF_lt(MPF *s, MPF *t) noexcept +cdef bint MPF_le(MPF *s, MPF *t) noexcept +cdef bint MPF_gt(MPF *s, MPF *t) noexcept +cdef bint MPF_ge(MPF *s, MPF *t) noexcept +cdef MPF_mul(MPF *r, MPF *s, MPF *t, MPopts opts) noexcept +cdef MPF_div(MPF *r, MPF *s, MPF *t, MPopts opts) noexcept +cdef int MPF_sqrt(MPF *r, MPF *s, MPopts opts) noexcept +cdef MPF_hypot(MPF *r, MPF *a, MPF *b, MPopts opts) noexcept +cdef MPF_pow_int(MPF *r, MPF *x, mpz_t n, MPopts opts) noexcept +cdef MPF_set_double(MPF *r, double x) noexcept +cdef MPF_exp(MPF *y, MPF *x, MPopts opts) noexcept +cdef MPF_complex_sqrt(MPF *c, MPF *d, MPF *a, MPF *b, MPopts opts) noexcept +cdef MPF_complex_exp(MPF *re, MPF *im, MPF *a, MPF *b, MPopts opts) noexcept +cdef int MPF_log(MPF *y, MPF *x, MPopts opts) noexcept +cdef MPF_set_pi(MPF *x, MPopts opts) noexcept +cdef MPF_set_ln2(MPF *x, MPopts opts) noexcept +cdef MPF_cos(MPF *c, MPF *x, MPopts opts) noexcept +cdef MPF_sin(MPF *c, MPF *x, MPopts opts) noexcept +cdef MPF_cos_sin(MPF *c, MPF *s, MPF *x, MPopts opts) noexcept cdef int MPF_pow(MPF *z, MPF *x, MPF *y, MPopts opts) except -1 -cdef MPF_complex_pow(MPF *zre, MPF *zim, MPF *xre, MPF *xim, MPF *yre, MPF *yim, MPopts opts) +cdef MPF_complex_pow(MPF *zre, MPF *zim, MPF *xre, MPF *xim, MPF *yre, MPF *yim, MPopts opts) noexcept cdef MPF_hypsum(MPF *a, MPF *b, int p, int q, param_types, str ztype, coeffs, \ - z, long prec, long wp, long epsshift, dict magnitude_check, kwargs) + z, long prec, long wp, long epsshift, dict magnitude_check, kwargs) noexcept diff --git a/src/sage/libs/mpmath/ext_impl.pyx b/src/sage/libs/mpmath/ext_impl.pyx index 2d8d2470273..aa69f6e0409 100644 --- a/src/sage/libs/mpmath/ext_impl.pyx +++ b/src/sage/libs/mpmath/ext_impl.pyx @@ -42,7 +42,7 @@ from sage.rings.integer cimport Integer from sage.libs.gmp.pylong cimport * -cdef mpz_set_integer(mpz_t v, x): +cdef mpz_set_integer(mpz_t v, x) noexcept: if isinstance(x, int): mpz_set_pylong(v, x) elif isinstance(x, Integer): @@ -50,21 +50,21 @@ cdef mpz_set_integer(mpz_t v, x): else: raise TypeError("cannot convert %s to an integer" % x) -cdef inline void mpz_add_si(mpz_t a, mpz_t b, long x): +cdef inline void mpz_add_si(mpz_t a, mpz_t b, long x) noexcept: if x >= 0: mpz_add_ui(a, b, x) else: # careful: overflow when negating INT_MIN mpz_sub_ui(a, b, (-x)) -cdef inline mpzi(mpz_t n): +cdef inline mpzi(mpz_t n) noexcept: return mpz_get_pyintlong(n) -cdef inline mpzl(mpz_t n): +cdef inline mpzl(mpz_t n) noexcept: return mpz_get_pylong(n) # This should be done better -cdef int mpz_tstbit_abs(mpz_t z, unsigned long bit_index): +cdef int mpz_tstbit_abs(mpz_t z, unsigned long bit_index) noexcept: cdef int res if mpz_sgn(z) < 0: mpz_neg(z, z) @@ -74,7 +74,7 @@ cdef int mpz_tstbit_abs(mpz_t z, unsigned long bit_index): res = mpz_tstbit(z, bit_index) return res -cdef void mpz_set_fixed(mpz_t t, MPF *x, int prec, bint abs=False): +cdef void mpz_set_fixed(mpz_t t, MPF *x, int prec, bint abs=False) noexcept: """ Set t = x, or t = |x|, as a fixed-point number with prec bits. """ @@ -87,7 +87,7 @@ cdef void mpz_set_fixed(mpz_t t, MPF *x, int prec, bint abs=False): if abs: mpz_abs(t, t) -cdef unsigned long mpz_bitcount(mpz_t z): +cdef unsigned long mpz_bitcount(mpz_t z) noexcept: if mpz_sgn(z) == 0: return 0 return mpz_sizeinbase(z, 2) @@ -101,7 +101,7 @@ cdef unsigned long mpz_bitcount(mpz_t z): # Note: MPFR's emax is 1073741823 DEF MAX_SHIFT = 536870912 # 2^29 -cdef int mpz_reasonable_shift(mpz_t z): +cdef int mpz_reasonable_shift(mpz_t z) noexcept: if mpz_sgn(z) > 0: return mpz_cmp_ui(z, MAX_SHIFT) < 0 else: @@ -120,28 +120,28 @@ DEF S_INF = 3 DEF S_NINF = 4 DEF S_NAN = 5 -cdef inline str rndmode_to_python(int rnd): +cdef inline str rndmode_to_python(int rnd) noexcept: if rnd == ROUND_N: return 'n' if rnd == ROUND_F: return 'f' if rnd == ROUND_C: return 'c' if rnd == ROUND_D: return 'd' if rnd == ROUND_U: return 'u' -cdef inline rndmode_from_python(str rnd): +cdef inline rndmode_from_python(str rnd) noexcept: if rnd == 'n': return ROUND_N if rnd == 'f': return ROUND_F if rnd == 'c': return ROUND_C if rnd == 'd': return ROUND_D if rnd == 'u': return ROUND_U -cdef inline mpfr_rnd_t rndmode_to_mpfr(int rnd): +cdef inline mpfr_rnd_t rndmode_to_mpfr(int rnd) noexcept: if rnd == ROUND_N: return MPFR_RNDN if rnd == ROUND_F: return MPFR_RNDD if rnd == ROUND_C: return MPFR_RNDU if rnd == ROUND_D: return MPFR_RNDZ if rnd == ROUND_U: return MPFR_RNDA -cdef inline int reciprocal_rnd(int rnd): +cdef inline int reciprocal_rnd(int rnd) noexcept: if rnd == ROUND_N: return ROUND_N if rnd == ROUND_D: return ROUND_U if rnd == ROUND_U: return ROUND_D @@ -163,19 +163,19 @@ cdef double _double_inf = float("1e300") * float("1e300") cdef double _double_ninf = -_double_inf cdef double _double_nan = _double_inf - _double_inf -cdef inline void MPF_init(MPF *x): +cdef inline void MPF_init(MPF *x) noexcept: """Allocate space and set value to zero. Must be called exactly once when creating a new MPF.""" x.special = S_ZERO mpz_init(x.man) mpz_init(x.exp) -cdef inline void MPF_clear(MPF *x): +cdef inline void MPF_clear(MPF *x) noexcept: """Deallocate space. Must be called exactly once when finished with an MPF.""" mpz_clear(x.man) mpz_clear(x.exp) -cdef inline void MPF_set(MPF *dest, MPF *src): +cdef inline void MPF_set(MPF *dest, MPF *src) noexcept: """Clone MPF value. Assumes source value is already normalized.""" if src is dest: return @@ -183,29 +183,29 @@ cdef inline void MPF_set(MPF *dest, MPF *src): mpz_set(dest.man, src.man) mpz_set(dest.exp, src.exp) -cdef inline void MPF_set_zero(MPF *x): +cdef inline void MPF_set_zero(MPF *x) noexcept: """Set value to 0.""" x.special = S_ZERO -cdef inline void MPF_set_one(MPF *x): +cdef inline void MPF_set_one(MPF *x) noexcept: """Set value to 1.""" x.special = S_NORMAL mpz_set_ui(x.man, 1) mpz_set_ui(x.exp, 0) -cdef inline void MPF_set_nan(MPF *x): +cdef inline void MPF_set_nan(MPF *x) noexcept: """Set value to NaN (not a number).""" x.special = S_NAN -cdef inline void MPF_set_inf(MPF *x): +cdef inline void MPF_set_inf(MPF *x) noexcept: """Set value to +infinity.""" x.special = S_INF -cdef inline void MPF_set_ninf(MPF *x): +cdef inline void MPF_set_ninf(MPF *x) noexcept: """Set value to -infinity.""" x.special = S_NINF -cdef MPF_set_si(MPF *x, long n): +cdef MPF_set_si(MPF *x, long n) noexcept: """Set value to that of a given C (long) integer.""" if n: x.special = S_NORMAL @@ -215,7 +215,7 @@ cdef MPF_set_si(MPF *x, long n): else: MPF_set_zero(x) -cdef MPF_set_int(MPF *x, n): +cdef MPF_set_int(MPF *x, n) noexcept: """Set value to that of a given Python integer.""" x.special = S_NORMAL mpz_set_integer(x.man, n) @@ -225,7 +225,7 @@ cdef MPF_set_int(MPF *x, n): else: MPF_set_zero(x) -cdef MPF_set_man_exp(MPF *x, man, exp): +cdef MPF_set_man_exp(MPF *x, man, exp) noexcept: """ Set value to man*2^exp where man, exp may be of any appropriate Python integer types. @@ -260,7 +260,7 @@ cdef tuple _mpf_fnan = (0, MPZ_ZERO, -123, -1) cdef tuple _mpf_finf = (0, MPZ_ZERO, -456, -2) cdef tuple _mpf_fninf = (1, MPZ_ZERO, -789, -3) -cdef MPF_set_tuple(MPF *x, tuple value): +cdef MPF_set_tuple(MPF *x, tuple value) noexcept: """ Set value of an MPF to that of a normalized (sign, man, exp, bc) tuple in the format used by mpmath.libmp. @@ -289,7 +289,7 @@ cdef MPF_set_tuple(MPF *x, tuple value): else: MPF_set_nan(x) -cdef MPF_to_tuple(MPF *x): +cdef MPF_to_tuple(MPF *x) noexcept: """Convert MPF value to (sign, man, exp, bc) tuple.""" cdef Integer man if x.special: @@ -309,7 +309,7 @@ cdef MPF_to_tuple(MPF *x): bc = mpz_sizeinbase(x.man, 2) return (sign, man, exp, bc) -cdef MPF_set_double(MPF *r, double x): +cdef MPF_set_double(MPF *r, double x) noexcept: """ Set r to the value of a C double x. """ @@ -334,7 +334,7 @@ cdef MPF_set_double(MPF *r, double x): import math as pymath # TODO: implement this function safely without using the Python math module -cdef double MPF_to_double(MPF *x, bint strict): +cdef double MPF_to_double(MPF *x, bint strict) noexcept: """Convert MPF value to a Python float.""" if x.special == S_NORMAL: man = mpzi(x.man) @@ -366,7 +366,7 @@ cdef double MPF_to_double(MPF *x, bint strict): return _double_ninf return _double_nan -cdef MPF_to_fixed(mpz_t r, MPF *x, long prec, bint truncate): +cdef MPF_to_fixed(mpz_t r, MPF *x, long prec, bint truncate) noexcept: """ Set r = x, r being in the format of a fixed-point number with prec bits. Floor division is used unless truncate=True in which case @@ -395,7 +395,7 @@ cdef MPF_to_fixed(mpz_t r, MPF *x, long prec, bint truncate): return raise OverflowError("cannot convert huge number to fixed-point format") -cdef int MPF_sgn(MPF *x): +cdef int MPF_sgn(MPF *x) noexcept: """ Gives the sign of an MPF (-1, 0, or 1). """ @@ -407,7 +407,7 @@ cdef int MPF_sgn(MPF *x): return 0 return mpz_sgn(x.man) -cdef void MPF_neg(MPF *r, MPF *s): +cdef void MPF_neg(MPF *r, MPF *s) noexcept: """ Sets r = -s. MPF_neg(x, x) negates in place. """ @@ -428,7 +428,7 @@ cdef void MPF_neg(MPF *r, MPF *s): if r is not s: mpz_set(r.exp, s.exp) -cdef void MPF_abs(MPF *r, MPF *s): +cdef void MPF_abs(MPF *r, MPF *s) noexcept: """ Sets r = abs(s). MPF_abs(r, r) sets the absolute value in place. """ @@ -443,7 +443,7 @@ cdef void MPF_abs(MPF *r, MPF *s): if r is not s: mpz_set(r.exp, s.exp) -cdef MPF_normalize(MPF *x, MPopts opts): +cdef MPF_normalize(MPF *x, MPopts opts) noexcept: """ Normalize. @@ -500,7 +500,7 @@ cdef MPF_normalize(MPF *x, MPopts opts): shift += trail mpz_add_si(x.exp, x.exp, shift) -cdef void MPF_pos(MPF *x, MPF *y, MPopts opts): +cdef void MPF_pos(MPF *x, MPF *y, MPopts opts) noexcept: """ Set x = +y (i.e. copy the value, and round if the working precision is smaller than the width @@ -509,7 +509,7 @@ cdef void MPF_pos(MPF *x, MPF *y, MPopts opts): MPF_set(x, y) MPF_normalize(x, opts) -cdef void _add_special(MPF *r, MPF *s, MPF *t): +cdef void _add_special(MPF *r, MPF *s, MPF *t) noexcept: if s.special == S_ZERO: # (+0) + (-0) = +0 if t.special == S_NZERO: @@ -542,7 +542,7 @@ cdef void _add_special(MPF *r, MPF *s, MPF *t): MPF_set(r, t) return -cdef void _sub_special(MPF *r, MPF *s, MPF *t): +cdef void _sub_special(MPF *r, MPF *s, MPF *t) noexcept: if s.special == S_ZERO: # (+0) - (+/-0) = (+0) if t.special == S_NZERO: @@ -577,7 +577,7 @@ cdef void _sub_special(MPF *r, MPF *s, MPF *t): else: MPF_neg(r, t) -cdef void _mul_special(MPF *r, MPF *s, MPF *t): +cdef void _mul_special(MPF *r, MPF *s, MPF *t) noexcept: if s.special == S_ZERO: if t.special == S_NORMAL or t.special == S_ZERO: MPF_set(r, s) @@ -616,7 +616,7 @@ cdef void _mul_special(MPF *r, MPF *s, MPF *t): else: MPF_set_ninf(r) -cdef _div_special(MPF *r, MPF *s, MPF *t): +cdef _div_special(MPF *r, MPF *s, MPF *t) noexcept: # TODO: handle signed zeros correctly if s.special == S_NAN or t.special == S_NAN: MPF_set_nan(r) @@ -637,7 +637,7 @@ cdef _div_special(MPF *r, MPF *s, MPF *t): elif t.special == S_INF or t.special == S_NINF: MPF_set_zero(r) -cdef _add_perturbation(MPF *r, MPF *s, int sign, MPopts opts): +cdef _add_perturbation(MPF *r, MPF *s, int sign, MPopts opts) noexcept: cdef long shift if opts.rounding == ROUND_N: MPF_set(r, s) @@ -650,7 +650,7 @@ cdef _add_perturbation(MPF *r, MPF *s, int sign, MPopts opts): mpz_sub_ui(r.exp, s.exp, shift) MPF_normalize(r, opts) -cdef MPF_add(MPF *r, MPF *s, MPF *t, MPopts opts): +cdef MPF_add(MPF *r, MPF *s, MPF *t, MPopts opts) noexcept: """ Set r = s + t, with exact rounding. @@ -704,7 +704,7 @@ cdef MPF_add(MPF *r, MPF *s, MPF *t, MPopts opts): else: _add_perturbation(r, t, mpz_sgn(s.man), opts) -cdef MPF_sub(MPF *r, MPF *s, MPF *t, MPopts opts): +cdef MPF_sub(MPF *r, MPF *s, MPF *t, MPopts opts) noexcept: """ Set r = s - t, with exact rounding. @@ -760,7 +760,7 @@ cdef MPF_sub(MPF *r, MPF *s, MPF *t, MPopts opts): _add_perturbation(r, t, -mpz_sgn(s.man), opts) MPF_neg(r, r) -cdef bint MPF_eq(MPF *s, MPF *t): +cdef bint MPF_eq(MPF *s, MPF *t) noexcept: """ Evaluates s == t. """ @@ -773,7 +773,7 @@ cdef bint MPF_eq(MPF *s, MPF *t): return True return False -cdef bint MPF_ne(MPF *s, MPF *t): +cdef bint MPF_ne(MPF *s, MPF *t) noexcept: """ Evaluates s != t. """ @@ -783,7 +783,7 @@ cdef bint MPF_ne(MPF *s, MPF *t): return (mpz_cmp(s.man, t.man) != 0) or (mpz_cmp(s.exp, t.exp) != 0) return s.special != t.special -cdef int MPF_cmp(MPF *s, MPF *t): +cdef int MPF_cmp(MPF *s, MPF *t) noexcept: """ Evaluates cmp(s,t). Conventions for nan follow those of the mpmath.libmp function. @@ -818,7 +818,7 @@ cdef int MPF_cmp(MPF *s, MPF *t): MPF_sub(&tmp1, s, t, opts_mini_prec) return MPF_sgn(&tmp1) -cdef bint MPF_lt(MPF *s, MPF *t): +cdef bint MPF_lt(MPF *s, MPF *t) noexcept: """ Evaluates s < t. """ @@ -826,7 +826,7 @@ cdef bint MPF_lt(MPF *s, MPF *t): return False return MPF_cmp(s, t) < 0 -cdef bint MPF_le(MPF *s, MPF *t): +cdef bint MPF_le(MPF *s, MPF *t) noexcept: """ Evaluates s <= t. """ @@ -834,7 +834,7 @@ cdef bint MPF_le(MPF *s, MPF *t): return False return MPF_cmp(s, t) <= 0 -cdef bint MPF_gt(MPF *s, MPF *t): +cdef bint MPF_gt(MPF *s, MPF *t) noexcept: """ Evaluates s > t. """ @@ -842,7 +842,7 @@ cdef bint MPF_gt(MPF *s, MPF *t): return False return MPF_cmp(s, t) > 0 -cdef bint MPF_ge(MPF *s, MPF *t): +cdef bint MPF_ge(MPF *s, MPF *t) noexcept: """ Evaluates s >= t. """ @@ -850,7 +850,7 @@ cdef bint MPF_ge(MPF *s, MPF *t): return False return MPF_cmp(s, t) >= 0 -cdef MPF_mul(MPF *r, MPF *s, MPF *t, MPopts opts): +cdef MPF_mul(MPF *r, MPF *s, MPF *t, MPopts opts) noexcept: """ Set r = s * t, with correct rounding. @@ -866,7 +866,7 @@ cdef MPF_mul(MPF *r, MPF *s, MPF *t, MPopts opts): if opts.prec: MPF_normalize(r, opts) -cdef MPF_div(MPF *r, MPF *s, MPF *t, MPopts opts): +cdef MPF_div(MPF *r, MPF *s, MPF *t, MPopts opts) noexcept: """ Set r = s / t, with correct rounding. """ @@ -912,7 +912,7 @@ cdef MPF_div(MPF *r, MPF *s, MPF *t, MPopts opts): mpz_sub_ui(r.exp, r.exp, extra) MPF_normalize(r, opts) -cdef int MPF_sqrt(MPF *r, MPF *s, MPopts opts): +cdef int MPF_sqrt(MPF *r, MPF *s, MPopts opts) noexcept: """ Set r = sqrt(s), with correct rounding. """ @@ -961,7 +961,7 @@ cdef int MPF_sqrt(MPF *r, MPF *s, MPopts opts): MPF_normalize(r, opts) return 0 -cdef MPF_hypot(MPF *r, MPF *a, MPF *b, MPopts opts): +cdef MPF_hypot(MPF *r, MPF *a, MPF *b, MPopts opts) noexcept: """ Set r = sqrt(a^2 + b^2) """ @@ -981,7 +981,7 @@ cdef MPF_hypot(MPF *r, MPF *a, MPF *b, MPopts opts): MPF_add(r, &tmp1, &tmp2, tmp_opts) MPF_sqrt(r, r, opts) -cdef MPF_pow_int(MPF *r, MPF *x, mpz_t n, MPopts opts): +cdef MPF_pow_int(MPF *r, MPF *x, mpz_t n, MPopts opts) noexcept: """ Set r = x ** n. Currently falls back to mpmath.libmp unless n is tiny. @@ -1074,7 +1074,7 @@ cdef int _pi_prec = -1 cdef mpz_t _ln2_value cdef int _ln2_prec = -1 -cdef mpz_set_pi(mpz_t x, int prec): +cdef mpz_set_pi(mpz_t x, int prec) noexcept: """ Set x = pi as a fixed-point number. """ @@ -1090,7 +1090,7 @@ cdef mpz_set_pi(mpz_t x, int prec): mpz_set(x, _pi_value) _pi_prec = prec -cdef mpz_set_ln2(mpz_t x, int prec): +cdef mpz_set_ln2(mpz_t x, int prec) noexcept: """ Set x = ln(2) as a fixed-point number. """ @@ -1106,7 +1106,7 @@ cdef mpz_set_ln2(mpz_t x, int prec): mpz_set(x, _ln2_value) _ln2_prec = prec -cdef void _cy_exp_mpfr(mpz_t y, mpz_t x, int prec): +cdef void _cy_exp_mpfr(mpz_t y, mpz_t x, int prec) noexcept: """ Computes y = exp(x) for fixed-point numbers y and x using MPFR, assuming that no overflow will occur. @@ -1122,7 +1122,7 @@ cdef void _cy_exp_mpfr(mpz_t y, mpz_t x, int prec): mpfr_clear(yf) mpfr_clear(xf) -cdef cy_exp_basecase(mpz_t y, mpz_t x, int prec): +cdef cy_exp_basecase(mpz_t y, mpz_t x, int prec) noexcept: """ Computes y = exp(x) for fixed-point numbers y and x, assuming that x is small (|x| ~< 1). At small precisions, this function @@ -1174,7 +1174,7 @@ cdef cy_exp_basecase(mpz_t y, mpz_t x, int prec): mpz_clear(a) -cdef MPF_exp(MPF *y, MPF *x, MPopts opts): +cdef MPF_exp(MPF *y, MPF *x, MPopts opts) noexcept: """ Set y = exp(x). """ @@ -1229,7 +1229,7 @@ cdef MPF_exp(MPF *y, MPF *x, MPopts opts): MPF_normalize(y, opts) -cdef MPF_complex_sqrt(MPF *c, MPF *d, MPF *a, MPF *b, MPopts opts): +cdef MPF_complex_sqrt(MPF *c, MPF *d, MPF *a, MPF *b, MPopts opts) noexcept: """ Set c+di = sqrt(a+bi). @@ -1287,7 +1287,7 @@ cdef MPF_complex_sqrt(MPF *c, MPF *d, MPF *a, MPF *b, MPopts opts): MPF_clear(&u) MPF_clear(&v) -cdef int MPF_get_mpfr_overflow(mpfr_t y, MPF *x): +cdef int MPF_get_mpfr_overflow(mpfr_t y, MPF *x) noexcept: """ Store the mpmath number x exactly in the MPFR variable y. The precision of y will be adjusted if necessary. If the exponent overflows, only @@ -1321,7 +1321,7 @@ cdef int MPF_get_mpfr_overflow(mpfr_t y, MPF *x): else: return 1 -cdef MPF_set_mpfr(MPF *y, mpfr_t x, MPopts opts): +cdef MPF_set_mpfr(MPF *y, mpfr_t x, MPopts opts) noexcept: """ Convert the MPFR number x to a normalized MPF y. inf/nan and zero are handled. @@ -1345,7 +1345,7 @@ cdef MPF_set_mpfr(MPF *y, mpfr_t x, MPopts opts): y.special = S_NORMAL MPF_normalize(y, opts) -cdef int MPF_log(MPF *y, MPF *x, MPopts opts): +cdef int MPF_log(MPF *y, MPF *x, MPopts opts) noexcept: """ Set y = log(|x|). Returns 1 if x is negative. """ @@ -1400,7 +1400,7 @@ cdef int MPF_log(MPF *y, MPF *x, MPopts opts): mpfr_clear(yy) return negative -cdef MPF_set_pi(MPF *x, MPopts opts): +cdef MPF_set_pi(MPF *x, MPopts opts) noexcept: """ Set x = pi. """ @@ -1409,7 +1409,7 @@ cdef MPF_set_pi(MPF *x, MPopts opts): mpz_set_si(x.exp, -(opts.prec+20)) MPF_normalize(x, opts) -cdef MPF_set_ln2(MPF *x, MPopts opts): +cdef MPF_set_ln2(MPF *x, MPopts opts) noexcept: """ Set x = ln(2). """ @@ -1493,7 +1493,7 @@ cdef mpz_t log_int_cache[MAX_LOG_INT_CACHE+1] cdef long log_int_cache_prec[MAX_LOG_INT_CACHE+1] cdef bint log_int_cache_initialized = 0 -cdef mpz_log_int(mpz_t v, mpz_t n, int prec): +cdef mpz_log_int(mpz_t v, mpz_t n, int prec) noexcept: """ Set v = log(n) where n is an integer and v is a fixed-point number with the specified precision. @@ -1543,7 +1543,7 @@ def log_int_fixed(n, long prec, ln2=None): return t -cdef _MPF_cos_python(MPF *c, MPF *x, MPopts opts): +cdef _MPF_cos_python(MPF *c, MPF *x, MPopts opts) noexcept: """ Computes c = cos(x) by calling the mpmath.libmp Python implementation. """ @@ -1552,7 +1552,7 @@ cdef _MPF_cos_python(MPF *c, MPF *x, MPopts opts): rndmode_to_python(opts.rounding), 1, False) MPF_set_tuple(c, ct) -cdef _MPF_sin_python(MPF *s, MPF *x, MPopts opts): +cdef _MPF_sin_python(MPF *s, MPF *x, MPopts opts) noexcept: """ Computes s = sin(x) by calling the mpmath.libmp Python implementation. """ @@ -1562,7 +1562,7 @@ cdef _MPF_sin_python(MPF *s, MPF *x, MPopts opts): MPF_set_tuple(s, st) -cdef MPF_cos(MPF *c, MPF *x, MPopts opts): +cdef MPF_cos(MPF *c, MPF *x, MPopts opts) noexcept: """ Set c = cos(x) """ @@ -1585,7 +1585,7 @@ cdef MPF_cos(MPF *c, MPF *x, MPopts opts): mpfr_clear(xf) mpfr_clear(cf) -cdef MPF_sin(MPF *s, MPF *x, MPopts opts): +cdef MPF_sin(MPF *s, MPF *x, MPopts opts) noexcept: """ Set s = sin(x) """ @@ -1608,7 +1608,7 @@ cdef MPF_sin(MPF *s, MPF *x, MPopts opts): mpfr_clear(xf) mpfr_clear(sf) -cdef MPF_cos_sin(MPF *c, MPF *s, MPF *x, MPopts opts): +cdef MPF_cos_sin(MPF *c, MPF *s, MPF *x, MPopts opts) noexcept: """ Set c = cos(x), s = sin(x) """ @@ -1638,7 +1638,7 @@ cdef MPF_cos_sin(MPF *c, MPF *s, MPF *x, MPopts opts): mpfr_clear(sf) -cdef MPF_complex_exp(MPF *re, MPF *im, MPF *a, MPF *b, MPopts opts): +cdef MPF_complex_exp(MPF *re, MPF *im, MPF *a, MPF *b, MPopts opts) noexcept: """ Set re+im*i = exp(a+bi) """ @@ -1752,7 +1752,7 @@ cdef int MPF_pow(MPF *z, MPF *x, MPF *y, MPopts opts) except -1: MPF_clear(&w) return 0 -cdef MPF_complex_square(MPF *re, MPF *im, MPF *a, MPF *b, MPopts opts): +cdef MPF_complex_square(MPF *re, MPF *im, MPF *a, MPF *b, MPopts opts) noexcept: """ Set re+im*i = (a+bi)^2 = a^2-b^2, 2ab*i. """ @@ -1769,7 +1769,7 @@ cdef MPF_complex_square(MPF *re, MPF *im, MPF *a, MPF *b, MPopts opts): MPF_clear(&u) -cdef MPF_complex_reciprocal(MPF *re, MPF *im, MPF *a, MPF *b, MPopts opts): +cdef MPF_complex_reciprocal(MPF *re, MPF *im, MPF *a, MPF *b, MPopts opts) noexcept: """ Set re+im*i = 1/(a+bi), i.e. compute the reciprocal of a complex number. @@ -1793,7 +1793,7 @@ cdef MPF_complex_reciprocal(MPF *re, MPF *im, MPF *a, MPF *b, MPopts opts): MPF_clear(&m) -cdef MPF_complex_pow_int(MPF *zre, MPF *zim, MPF *xre, MPF *xim, mpz_t n, MPopts opts): +cdef MPF_complex_pow_int(MPF *zre, MPF *zim, MPF *xre, MPF *xim, mpz_t n, MPopts opts) noexcept: """ Set zre+zim*i = (xre+xim) ^ n, i.e. raise a complex number to an integer power. """ @@ -1859,7 +1859,7 @@ cdef MPF_complex_pow_int(MPF *zre, MPF *zim, MPF *xre, MPF *xim, mpz_t n, MPopts MPF_set_tuple(zim, vi) -cdef MPF_complex_pow_re(MPF *zre, MPF *zim, MPF *xre, MPF *xim, MPF *y, MPopts opts): +cdef MPF_complex_pow_re(MPF *zre, MPF *zim, MPF *xre, MPF *xim, MPF *y, MPopts opts) noexcept: """ Set (zre+zim*i) = (xre+xim*i) ^ y, i.e. raise a complex number to a real power. @@ -1904,7 +1904,7 @@ cdef MPF_complex_pow_re(MPF *zre, MPF *zim, MPF *xre, MPF *xim, MPF *y, MPopts o MPF_set_tuple(zim, vi) -cdef MPF_complex_pow(MPF *zre, MPF *zim, MPF *xre, MPF *xim, MPF *yre, MPF *yim, MPopts opts): +cdef MPF_complex_pow(MPF *zre, MPF *zim, MPF *xre, MPF *xim, MPF *yre, MPF *yim, MPopts opts) noexcept: """ Set (zre + zim*i) = (xre+xim*i) ^ (yre+yim*i). """ @@ -1922,7 +1922,7 @@ cdef MPF_complex_pow(MPF *zre, MPF *zim, MPF *xre, MPF *xim, MPF *yre, MPF *yim, MPF_set_tuple(zim, vi) -cdef mpz_set_tuple_fixed(mpz_t x, tuple t, long prec): +cdef mpz_set_tuple_fixed(mpz_t x, tuple t, long prec) noexcept: """ Set the integer x to a fixed-point number with specified precision and the value of t = (sign,man,exp,bc). Truncating division is used @@ -1939,7 +1939,7 @@ cdef mpz_set_tuple_fixed(mpz_t x, tuple t, long prec): else: mpz_tdiv_q_2exp(x, x, -offset) -cdef mpz_set_complex_tuple_fixed(mpz_t x, mpz_t y, tuple t, long prec): +cdef mpz_set_complex_tuple_fixed(mpz_t x, mpz_t y, tuple t, long prec) noexcept: """ Set the integers (x,y) to fixed-point numbers with the values of the mpf pair t = ((xsign,xman,xexp,xbc), (ysign,yman,yexp,ybc)). @@ -1947,7 +1947,7 @@ cdef mpz_set_complex_tuple_fixed(mpz_t x, mpz_t y, tuple t, long prec): mpz_set_tuple_fixed(x, t[0], prec) mpz_set_tuple_fixed(y, t[1], prec) -cdef MPF_set_fixed(MPF *x, mpz_t man, long wp, long prec, int rnd): +cdef MPF_set_fixed(MPF *x, mpz_t man, long wp, long prec, int rnd) noexcept: """ Set value of an MPF given a fixed-point mantissa of precision wp, rounding to the given precision and rounding mode. @@ -1978,7 +1978,7 @@ cdef mpz_t BCIM[MAX_PARAMS] cdef MPF_hypsum(MPF *a, MPF *b, int p, int q, param_types, str ztype, coeffs, z, - long prec, long wp, long epsshift, dict magnitude_check, kwargs): + long prec, long wp, long epsshift, dict magnitude_check, kwargs) noexcept: """ Evaluates a+bi = pFq(..., z) by summing the hypergeometric series in fixed-point arithmetic. diff --git a/src/sage/libs/mpmath/ext_main.pyx b/src/sage/libs/mpmath/ext_main.pyx index a46c85ba52f..a00c5ee4831 100644 --- a/src/sage/libs/mpmath/ext_main.pyx +++ b/src/sage/libs/mpmath/ext_main.pyx @@ -109,7 +109,7 @@ cdef class constant cdef class wrapped_libmp_function cdef class wrapped_specfun -cdef __isint(MPF *v): +cdef __isint(MPF *v) noexcept: return v.special == S_ZERO or (v.special == S_NORMAL and mpz_sgn(v.exp) >= 0) cdef int MPF_set_any(MPF *re, MPF *im, x, MPopts opts, bint str_tuple_ok) except -1: @@ -185,7 +185,7 @@ cdef int MPF_set_any(MPF *re, MPF *im, x, MPopts opts, bint str_tuple_ok) except return 1 return 0 -cdef binop(int op, x, y, MPopts opts): +cdef binop(int op, x, y, MPopts opts) noexcept: cdef int typx cdef int typy cdef MPF xre, xim, yre, yim @@ -498,7 +498,7 @@ cdef class Context: _prec_rounding = property(_get_prec_rounding) - cpdef mpf make_mpf(ctx, tuple v): + cpdef mpf make_mpf(ctx, tuple v) noexcept: """ Creates an mpf from tuple data :: @@ -511,7 +511,7 @@ cdef class Context: MPF_set_tuple(&x.value, v) return x - cpdef mpc make_mpc(ctx, tuple v): + cpdef mpc make_mpc(ctx, tuple v) noexcept: """ Creates an mpc from tuple data :: @@ -973,7 +973,7 @@ cdef class Context: # Doing a+b directly doesn't work with mpi, presumably due to # Cython trying to be clever with the operation resolution - cdef _stupid_add(ctx, a, b): + cdef _stupid_add(ctx, a, b) noexcept: return a + b def _convert_param(ctx, x): @@ -1178,7 +1178,7 @@ cdef class Context: f_wrapped.__doc__ = doc setattr(cls, name, f_wrapped) - cdef MPopts _fun_get_opts(ctx, kwargs): + cdef MPopts _fun_get_opts(ctx, kwargs) noexcept: """ Helper function that extracts precision and rounding information from kwargs, or returns the global working precision and rounding diff --git a/src/sage/libs/mpmath/utils.pxd b/src/sage/libs/mpmath/utils.pxd index 686b108da9a..646afa61899 100644 --- a/src/sage/libs/mpmath/utils.pxd +++ b/src/sage/libs/mpmath/utils.pxd @@ -1,3 +1,3 @@ from sage.libs.mpfr.types cimport mpfr_t -cdef mpfr_to_mpfval(mpfr_t) +cdef mpfr_to_mpfval(mpfr_t) noexcept diff --git a/src/sage/libs/mpmath/utils.pyx b/src/sage/libs/mpmath/utils.pyx index 83f8108be08..7265c0bf7a7 100644 --- a/src/sage/libs/mpmath/utils.pyx +++ b/src/sage/libs/mpmath/utils.pyx @@ -16,7 +16,7 @@ from sage.libs.gmp.all cimport * from sage.rings.real_mpfr cimport RealField -cpdef int bitcount(n): +cpdef int bitcount(n) noexcept: """ Bitcount of a Sage Integer or Python int/long. @@ -46,7 +46,7 @@ cpdef int bitcount(n): return 0 return mpz_sizeinbase(m.value, 2) -cpdef isqrt(n): +cpdef isqrt(n) noexcept: """ Square root (rounded to floor) of a Sage Integer or Python int/long. The result is a Sage Integer. @@ -77,7 +77,7 @@ cpdef isqrt(n): mpz_sqrt(y.value, m.value) return y -cpdef from_man_exp(man, exp, long prec = 0, str rnd = 'd'): +cpdef from_man_exp(man, exp, long prec = 0, str rnd = 'd') noexcept: """ Create normalized mpf value tuple from mantissa and exponent. @@ -106,7 +106,7 @@ cpdef from_man_exp(man, exp, long prec = 0, str rnd = 'd'): else: return normalize(0, res, exp, bc, prec, rnd) -cpdef normalize(long sign, Integer man, exp, long bc, long prec, str rnd): +cpdef normalize(long sign, Integer man, exp, long bc, long prec, str rnd) noexcept: """ Create normalized mpf value tuple from full list of components. @@ -154,7 +154,7 @@ cpdef normalize(long sign, Integer man, exp, long bc, long prec, str rnd): bc = mpz_sizeinbase(res.value, 2) return (sign, res, int(exp), bc) -cdef mpfr_from_mpfval(mpfr_t res, tuple x): +cdef mpfr_from_mpfval(mpfr_t res, tuple x) noexcept: """ Set value of an MPFR number (in place) to that of a given mpmath mpf data tuple. @@ -180,7 +180,7 @@ cdef mpfr_from_mpfval(mpfr_t res, tuple x): else: mpfr_set_nan(res) -cdef mpfr_to_mpfval(mpfr_t value): +cdef mpfr_to_mpfval(mpfr_t value) noexcept: """ Given an MPFR value, return an mpmath mpf data tuple representing the same number. diff --git a/src/sage/libs/ntl/conversion.pxd b/src/sage/libs/ntl/conversion.pxd index dfd7647a6c4..840e3947ea3 100644 --- a/src/sage/libs/ntl/conversion.pxd +++ b/src/sage/libs/ntl/conversion.pxd @@ -36,7 +36,7 @@ from sage.matrix.matrix_generic_dense cimport Matrix_generic_dense # matrix_modn_dense_float (dense matrix over Z/nZ) # ################################################ -cdef inline void set_ntl_matrix_modn_dense_float(mat_ZZ_p_c& A, ntl_ZZ_pContext_class c, Matrix_modn_dense_float m): +cdef inline void set_ntl_matrix_modn_dense_float(mat_ZZ_p_c& A, ntl_ZZ_pContext_class c, Matrix_modn_dense_float m) noexcept: r""" set the entries of a NTL matrix from a Sage matrix. @@ -53,7 +53,7 @@ cdef inline void set_ntl_matrix_modn_dense_float(mat_ZZ_p_c& A, ntl_ZZ_pContext_ tmp = ntl_ZZ_p(m[i,j], c) A.put(i, j, tmp.x) -cdef inline void set_ntl_matrix_modn_dense_double(mat_ZZ_p_c& A, ntl_ZZ_pContext_class c, Matrix_modn_dense_double m): +cdef inline void set_ntl_matrix_modn_dense_double(mat_ZZ_p_c& A, ntl_ZZ_pContext_class c, Matrix_modn_dense_double m) noexcept: r""" set the entries of a NTL matrix from a Sage matrix. @@ -70,7 +70,7 @@ cdef inline void set_ntl_matrix_modn_dense_double(mat_ZZ_p_c& A, ntl_ZZ_pContext tmp = ntl_ZZ_p(m[i,j], c) A.put(i, j, tmp.x) -cdef inline void set_ntl_matrix_modn_generic_dense(mat_ZZ_p_c& A, ntl_ZZ_pContext_class c, Matrix_generic_dense m): +cdef inline void set_ntl_matrix_modn_generic_dense(mat_ZZ_p_c& A, ntl_ZZ_pContext_class c, Matrix_generic_dense m) noexcept: r""" set the entries of a NTL matrix from a Sage matrix. @@ -87,7 +87,7 @@ cdef inline void set_ntl_matrix_modn_generic_dense(mat_ZZ_p_c& A, ntl_ZZ_pContex tmp = ntl_ZZ_p(m[i,j], c) A.put(i, j, tmp.x) -cdef inline void set_ntl_matrix_modn_dense(mat_ZZ_p_c& A, ntl_ZZ_pContext_class c, m): +cdef inline void set_ntl_matrix_modn_dense(mat_ZZ_p_c& A, ntl_ZZ_pContext_class c, m) noexcept: r""" set the entries of a NTL matrix from a Sage matrix. diff --git a/src/sage/libs/ntl/convert.pxd b/src/sage/libs/ntl/convert.pxd index aa733329dce..1a9532f0aba 100644 --- a/src/sage/libs/ntl/convert.pxd +++ b/src/sage/libs/ntl/convert.pxd @@ -1,6 +1,6 @@ from .types cimport ZZ_c from sage.libs.gmp.types cimport mpz_t, mpz_srcptr -cdef void ZZ_to_mpz(mpz_t output, ZZ_c* x) -cdef void mpz_to_ZZ(ZZ_c *output, mpz_srcptr x) -cdef void PyLong_to_ZZ(ZZ_c* z, value) +cdef void ZZ_to_mpz(mpz_t output, ZZ_c* x) noexcept +cdef void mpz_to_ZZ(ZZ_c *output, mpz_srcptr x) noexcept +cdef void PyLong_to_ZZ(ZZ_c* z, value) noexcept diff --git a/src/sage/libs/ntl/convert.pyx b/src/sage/libs/ntl/convert.pyx index d06270d5077..975a3f3fced 100644 --- a/src/sage/libs/ntl/convert.pyx +++ b/src/sage/libs/ntl/convert.pyx @@ -27,7 +27,7 @@ cdef extern from "sage/libs/ntl/ntlwrap_impl.h": void ZZ_to_mpz(mpz_t output, ZZ_c* x) void mpz_to_ZZ(ZZ_c *output, mpz_srcptr x) -cdef void PyLong_to_ZZ(ZZ_c* z, value): +cdef void PyLong_to_ZZ(ZZ_c* z, value) noexcept: """ Convert ``value`` (which must be a Python ``long``) to NTL. """ diff --git a/src/sage/libs/ntl/misc.pxi b/src/sage/libs/ntl/misc.pxi index e9dcd9807b0..e0d24b01a60 100644 --- a/src/sage/libs/ntl/misc.pxi +++ b/src/sage/libs/ntl/misc.pxi @@ -8,7 +8,7 @@ from cysignals.signals cimport sig_off cdef extern from *: void del_charstar "delete[]"(char*) -cdef object string(char* s): +cdef object string(char* s) noexcept: """ Takes a char* allocated using malloc, and converts it to a Python string, then deletes the allocated memory. Also unsets the signal @@ -20,7 +20,7 @@ cdef object string(char* s): sig_free(s) return t -cdef object string_delete(char* s): +cdef object string_delete(char* s) noexcept: """ Takes a char* allocated using C++ new, and converts it to a Python string, then deletes the allocated memory. Also unsets the signal diff --git a/src/sage/libs/ntl/ntl_GF2E.pxd b/src/sage/libs/ntl/ntl_GF2E.pxd index 8977f711078..f634042e7cb 100644 --- a/src/sage/libs/ntl/ntl_GF2E.pxd +++ b/src/sage/libs/ntl/ntl_GF2E.pxd @@ -4,5 +4,5 @@ from .ntl_GF2EContext cimport ntl_GF2EContext_class cdef class ntl_GF2E(): cdef GF2E_c x cdef ntl_GF2EContext_class c - cdef ntl_GF2E _new(self) + cdef ntl_GF2E _new(self) noexcept diff --git a/src/sage/libs/ntl/ntl_GF2E.pyx b/src/sage/libs/ntl/ntl_GF2E.pyx index c78fd6704db..078a3e2e6f7 100644 --- a/src/sage/libs/ntl/ntl_GF2E.pyx +++ b/src/sage/libs/ntl/ntl_GF2E.pyx @@ -155,7 +155,7 @@ cdef class ntl_GF2E(): self.c = ntl_GF2EContext(modulus) self.c.restore_c() - cdef ntl_GF2E _new(self): + cdef ntl_GF2E _new(self) noexcept: cdef ntl_GF2E r self.c.restore_c() r = ntl_GF2E.__new__(ntl_GF2E) diff --git a/src/sage/libs/ntl/ntl_GF2EContext.pxd b/src/sage/libs/ntl/ntl_GF2EContext.pxd index 44ab9891713..df1f44f87aa 100644 --- a/src/sage/libs/ntl/ntl_GF2EContext.pxd +++ b/src/sage/libs/ntl/ntl_GF2EContext.pxd @@ -4,5 +4,5 @@ from .ntl_GF2X cimport ntl_GF2X cdef class ntl_GF2EContext_class(): cdef GF2EContext_c x cdef ntl_GF2X m - cdef void restore_c(self) + cdef void restore_c(self) noexcept cdef object __weakref__ diff --git a/src/sage/libs/ntl/ntl_GF2EContext.pyx b/src/sage/libs/ntl/ntl_GF2EContext.pyx index 11d06893505..f00bda404df 100644 --- a/src/sage/libs/ntl/ntl_GF2EContext.pyx +++ b/src/sage/libs/ntl/ntl_GF2EContext.pyx @@ -105,7 +105,7 @@ cdef class ntl_GF2EContext_class(): """ self.restore_c() - cdef void restore_c(self): + cdef void restore_c(self) noexcept: self.x.restore() def ntl_GF2EContext( v ): diff --git a/src/sage/libs/ntl/ntl_GF2EX.pxd b/src/sage/libs/ntl/ntl_GF2EX.pxd index 70e06122753..e9a98a3afd6 100644 --- a/src/sage/libs/ntl/ntl_GF2EX.pxd +++ b/src/sage/libs/ntl/ntl_GF2EX.pxd @@ -5,5 +5,5 @@ from .ntl_GF2E cimport ntl_GF2E cdef class ntl_GF2EX(): cdef GF2EX_c x cdef ntl_GF2EContext_class c - cdef ntl_GF2E _new_element(self) - cdef ntl_GF2EX _new(self) + cdef ntl_GF2E _new_element(self) noexcept + cdef ntl_GF2EX _new(self) noexcept diff --git a/src/sage/libs/ntl/ntl_GF2EX.pyx b/src/sage/libs/ntl/ntl_GF2EX.pyx index e9dfbab4668..72d18cedd4a 100644 --- a/src/sage/libs/ntl/ntl_GF2EX.pyx +++ b/src/sage/libs/ntl/ntl_GF2EX.pyx @@ -85,14 +85,14 @@ cdef class ntl_GF2EX(): self.c = ntl_GF2EContext(modulus) self.c.restore_c() - cdef ntl_GF2E _new_element(self): + cdef ntl_GF2E _new_element(self) noexcept: cdef ntl_GF2E r self.c.restore_c() r = ntl_GF2E.__new__(ntl_GF2E) r.c = self.c return r - cdef ntl_GF2EX _new(self): + cdef ntl_GF2EX _new(self) noexcept: cdef ntl_GF2EX r self.c.restore_c() r = ntl_GF2EX.__new__(ntl_GF2EX) diff --git a/src/sage/libs/ntl/ntl_GF2X_linkage.pxi b/src/sage/libs/ntl/ntl_GF2X_linkage.pxi index 3f01c91ab00..cf480a34653 100644 --- a/src/sage/libs/ntl/ntl_GF2X_linkage.pxi +++ b/src/sage/libs/ntl/ntl_GF2X_linkage.pxi @@ -24,7 +24,7 @@ from sage.libs.ntl.GF2 cimport * from sage.libs.ntl.GF2X cimport * -cdef GF2X_c *celement_new(long parent): +cdef GF2X_c *celement_new(long parent) noexcept: """ EXAMPLES:: @@ -32,7 +32,7 @@ cdef GF2X_c *celement_new(long parent): """ return new GF2X_c() -cdef int celement_delete(GF2X_c *e, long parent): +cdef int celement_delete(GF2X_c *e, long parent) noexcept: """ EXAMPLES:: @@ -41,7 +41,7 @@ cdef int celement_delete(GF2X_c *e, long parent): """ del e -cdef int celement_construct(GF2X_c *e, long parent): +cdef int celement_construct(GF2X_c *e, long parent) noexcept: """ EXAMPLES:: @@ -49,7 +49,7 @@ cdef int celement_construct(GF2X_c *e, long parent): """ pass -cdef int celement_destruct(GF2X_c *e, long parent): +cdef int celement_destruct(GF2X_c *e, long parent) noexcept: """ EXAMPLES:: @@ -67,7 +67,7 @@ cdef int celement_gen(GF2X_c *e, long i, long parent) except -2: cdef unsigned char g = 2 GF2XFromBytes(e[0], (&g), 1) -cdef object celement_repr(GF2X_c *e, long parent): +cdef object celement_repr(GF2X_c *e, long parent) noexcept: """ We ignore NTL's printing. diff --git a/src/sage/libs/ntl/ntl_ZZ.pxd b/src/sage/libs/ntl/ntl_ZZ.pxd index 31a23b29d46..2ada3d8398c 100644 --- a/src/sage/libs/ntl/ntl_ZZ.pxd +++ b/src/sage/libs/ntl/ntl_ZZ.pxd @@ -2,5 +2,5 @@ from sage.libs.ntl.types cimport ZZ_c cdef class ntl_ZZ(): cdef ZZ_c x - cdef int get_as_int(ntl_ZZ self) - cdef void set_from_int(ntl_ZZ self, int value) + cdef int get_as_int(ntl_ZZ self) noexcept + cdef void set_from_int(ntl_ZZ self, int value) noexcept diff --git a/src/sage/libs/ntl/ntl_ZZ.pyx b/src/sage/libs/ntl/ntl_ZZ.pyx index 41e14fdcf09..37acfef79a8 100644 --- a/src/sage/libs/ntl/ntl_ZZ.pyx +++ b/src/sage/libs/ntl/ntl_ZZ.pyx @@ -32,7 +32,7 @@ from sage.misc.randstate cimport current_randstate from cpython.object cimport Py_LT, Py_LE, Py_EQ, Py_NE, Py_GT, Py_GE -cdef make_ZZ(ZZ_c* x): +cdef make_ZZ(ZZ_c* x) noexcept: cdef ntl_ZZ y y = ntl_ZZ() y.x = x[0] @@ -269,7 +269,7 @@ cdef class ntl_ZZ(): """ return int(self._integer_()) - cdef int get_as_int(ntl_ZZ self): + cdef int get_as_int(ntl_ZZ self) noexcept: r""" Returns value as C int. @@ -312,7 +312,7 @@ cdef class ntl_ZZ(): ZZ_to_mpz(ans.value, &self.x) return ans - cdef void set_from_int(ntl_ZZ self, int value): + cdef void set_from_int(ntl_ZZ self, int value) noexcept: r""" Sets the value from a C int. diff --git a/src/sage/libs/ntl/ntl_ZZX.pxd b/src/sage/libs/ntl/ntl_ZZX.pxd index c15a3f2d1e4..5f6238f73f1 100644 --- a/src/sage/libs/ntl/ntl_ZZX.pxd +++ b/src/sage/libs/ntl/ntl_ZZX.pxd @@ -2,5 +2,5 @@ from .types cimport ZZX_c cdef class ntl_ZZX(): cdef ZZX_c x - cdef void setitem_from_int(ntl_ZZX self, long i, int value) - cdef int getitem_as_int(ntl_ZZX self, long i) + cdef void setitem_from_int(ntl_ZZX self, long i, int value) noexcept + cdef int getitem_as_int(ntl_ZZX self, long i) noexcept diff --git a/src/sage/libs/ntl/ntl_ZZX.pyx b/src/sage/libs/ntl/ntl_ZZX.pyx index 34fd47a8527..343e5883191 100644 --- a/src/sage/libs/ntl/ntl_ZZX.pyx +++ b/src/sage/libs/ntl/ntl_ZZX.pyx @@ -37,7 +37,7 @@ from sage.arith.power cimport generic_power_pos ZZ = IntegerRing() -cdef inline ntl_ZZ make_ZZ(ZZ_c* x): +cdef inline ntl_ZZ make_ZZ(ZZ_c* x) noexcept: """ These make_XXXX functions are deprecated and should be phased out.""" cdef ntl_ZZ y y = ntl_ZZ() @@ -46,12 +46,12 @@ cdef inline ntl_ZZ make_ZZ(ZZ_c* x): return y # You must do sig_on() before calling this function -cdef inline ntl_ZZ make_ZZ_sig_off(ZZ_c* x): +cdef inline ntl_ZZ make_ZZ_sig_off(ZZ_c* x) noexcept: cdef ntl_ZZ y = make_ZZ(x) sig_off() return y -cdef inline ntl_ZZX make_ZZX(ZZX_c* x): +cdef inline ntl_ZZX make_ZZX(ZZX_c* x) noexcept: """ These make_XXXX functions are deprecated and should be phased out.""" cdef ntl_ZZX y y = ntl_ZZX() @@ -60,13 +60,13 @@ cdef inline ntl_ZZX make_ZZX(ZZX_c* x): return y # You must do sig_on() before calling this function -cdef inline ntl_ZZX make_ZZX_sig_off(ZZX_c* x): +cdef inline ntl_ZZX make_ZZX_sig_off(ZZX_c* x) noexcept: cdef ntl_ZZX y = make_ZZX(x) sig_off() return y from sage.structure.proof.proof import get_flag -cdef proof_flag(t): +cdef proof_flag(t) noexcept: return get_flag(t, "polynomial") ############################################################################## @@ -200,7 +200,7 @@ cdef class ntl_ZZX(): cc = ntl_ZZ(a) ZZX_SetCoeff(self.x, i, cc.x) - cdef void setitem_from_int(ntl_ZZX self, long i, int value): + cdef void setitem_from_int(ntl_ZZX self, long i, int value) noexcept: r""" Sets ith coefficient to value. @@ -245,7 +245,7 @@ cdef class ntl_ZZX(): sig_off() return r - cdef int getitem_as_int(ntl_ZZX self, long i): + cdef int getitem_as_int(ntl_ZZX self, long i) noexcept: r""" Returns ith coefficient as C int. Return value is only valid if the result fits into an int. diff --git a/src/sage/libs/ntl/ntl_ZZ_p.pxd b/src/sage/libs/ntl/ntl_ZZ_p.pxd index 4863afeb2c2..08a0a3beb84 100644 --- a/src/sage/libs/ntl/ntl_ZZ_p.pxd +++ b/src/sage/libs/ntl/ntl_ZZ_p.pxd @@ -4,6 +4,6 @@ from .ntl_ZZ_pContext cimport ntl_ZZ_pContext_class cdef class ntl_ZZ_p(): cdef ZZ_p_c x cdef ntl_ZZ_pContext_class c - cdef int get_as_int(ntl_ZZ_p self) - cdef void set_from_int(ntl_ZZ_p self, int value) - cdef ntl_ZZ_p _new(self) + cdef int get_as_int(ntl_ZZ_p self) noexcept + cdef void set_from_int(ntl_ZZ_p self, int value) noexcept + cdef ntl_ZZ_p _new(self) noexcept diff --git a/src/sage/libs/ntl/ntl_ZZ_p.pyx b/src/sage/libs/ntl/ntl_ZZ_p.pyx index d032d9b81b9..cca767303f7 100644 --- a/src/sage/libs/ntl/ntl_ZZ_p.pyx +++ b/src/sage/libs/ntl/ntl_ZZ_p.pyx @@ -154,7 +154,7 @@ cdef class ntl_ZZ_p(): self.c = ntl_ZZ_pContext(modulus) self.c.restore_c() - cdef ntl_ZZ_p _new(self): + cdef ntl_ZZ_p _new(self) noexcept: cdef ntl_ZZ_p r self.c.restore_c() r = ntl_ZZ_p.__new__(ntl_ZZ_p) @@ -348,7 +348,7 @@ cdef class ntl_ZZ_p(): """ return self.get_as_int() - cdef int get_as_int(ntl_ZZ_p self): + cdef int get_as_int(ntl_ZZ_p self) noexcept: r""" Returns value as C int. Return value is only valid if the result fits into an int. @@ -375,7 +375,7 @@ cdef class ntl_ZZ_p(): self.c.restore_c() return self.get_as_int() - cdef void set_from_int(ntl_ZZ_p self, int value): + cdef void set_from_int(ntl_ZZ_p self, int value) noexcept: r""" Sets the value from a C int. diff --git a/src/sage/libs/ntl/ntl_ZZ_pContext.pxd b/src/sage/libs/ntl/ntl_ZZ_pContext.pxd index 171776d85d7..61269d95584 100644 --- a/src/sage/libs/ntl/ntl_ZZ_pContext.pxd +++ b/src/sage/libs/ntl/ntl_ZZ_pContext.pxd @@ -5,7 +5,7 @@ from .types cimport ZZ_c cdef class ntl_ZZ_pContext_class(): cdef ZZ_pContext_c x - cdef void restore_c(self) + cdef void restore_c(self) noexcept cdef ntl_ZZ p cdef double p_bits cdef object __weakref__ @@ -14,7 +14,7 @@ cdef class ntl_ZZ_pContext_class(): cdef class ntl_ZZ_pContext_factory(): cdef object context_dict - cdef ntl_ZZ_pContext_class make_c(self, ntl_ZZ v) + cdef ntl_ZZ_pContext_class make_c(self, ntl_ZZ v) noexcept cdef extern from "ntlwrap.h": diff --git a/src/sage/libs/ntl/ntl_ZZ_pContext.pyx b/src/sage/libs/ntl/ntl_ZZ_pContext.pyx index dbcc8af1441..52c04e277cd 100644 --- a/src/sage/libs/ntl/ntl_ZZ_pContext.pyx +++ b/src/sage/libs/ntl/ntl_ZZ_pContext.pyx @@ -114,7 +114,7 @@ cdef class ntl_ZZ_pContext_class(): """ self.restore_c() - cdef void restore_c(self): + cdef void restore_c(self) noexcept: self.x.restore() cpdef void _assert_is_current_modulus(self) except *: @@ -162,7 +162,7 @@ cdef class ntl_ZZ_pContext_factory(): def __init__(self): self.context_dict = {} - cdef ntl_ZZ_pContext_class make_c(self, ntl_ZZ v): + cdef ntl_ZZ_pContext_class make_c(self, ntl_ZZ v) noexcept: """ Creates a new ZZ_pContext. diff --git a/src/sage/libs/ntl/ntl_ZZ_pE.pxd b/src/sage/libs/ntl/ntl_ZZ_pE.pxd index 267608a016d..cb9efd2279f 100644 --- a/src/sage/libs/ntl/ntl_ZZ_pE.pxd +++ b/src/sage/libs/ntl/ntl_ZZ_pE.pxd @@ -5,6 +5,6 @@ from .ntl_ZZ_pX cimport ntl_ZZ_pX cdef class ntl_ZZ_pE(): cdef ZZ_pE_c x cdef ntl_ZZ_pEContext_class c - cdef ntl_ZZ_pX get_as_ZZ_pX(ntl_ZZ_pE self) - cdef void set_from_ZZ_pX(ntl_ZZ_pE self, ntl_ZZ_pX value) - cdef ntl_ZZ_pE _new(self) + cdef ntl_ZZ_pX get_as_ZZ_pX(ntl_ZZ_pE self) noexcept + cdef void set_from_ZZ_pX(ntl_ZZ_pE self, ntl_ZZ_pX value) noexcept + cdef ntl_ZZ_pE _new(self) noexcept diff --git a/src/sage/libs/ntl/ntl_ZZ_pE.pyx b/src/sage/libs/ntl/ntl_ZZ_pE.pyx index 790d5c59648..b0882217e86 100644 --- a/src/sage/libs/ntl/ntl_ZZ_pE.pyx +++ b/src/sage/libs/ntl/ntl_ZZ_pE.pyx @@ -149,7 +149,7 @@ cdef class ntl_ZZ_pE(): self.c = ntl_ZZ_pEContext(modulus) self.c.restore_c() - cdef ntl_ZZ_pE _new(self): + cdef ntl_ZZ_pE _new(self) noexcept: cdef ntl_ZZ_pE r self.c.restore_c() r = ntl_ZZ_pE.__new__(ntl_ZZ_pE) @@ -268,7 +268,7 @@ cdef class ntl_ZZ_pE(): return r - cdef ntl_ZZ_pX get_as_ZZ_pX(ntl_ZZ_pE self): + cdef ntl_ZZ_pX get_as_ZZ_pX(ntl_ZZ_pE self) noexcept: r""" Returns value as ntl_ZZ_pX. """ @@ -294,7 +294,7 @@ cdef class ntl_ZZ_pE(): """ return self.get_as_ZZ_pX() - cdef void set_from_ZZ_pX(ntl_ZZ_pE self, ntl_ZZ_pX value): + cdef void set_from_ZZ_pX(ntl_ZZ_pE self, ntl_ZZ_pX value) noexcept: r""" Sets the value from a ZZ_pX. """ diff --git a/src/sage/libs/ntl/ntl_ZZ_pEContext.pxd b/src/sage/libs/ntl/ntl_ZZ_pEContext.pxd index 72c9ec42eab..027c59465a9 100644 --- a/src/sage/libs/ntl/ntl_ZZ_pEContext.pxd +++ b/src/sage/libs/ntl/ntl_ZZ_pEContext.pxd @@ -13,7 +13,7 @@ cdef class ntl_ZZ_pEContext_class(): cdef ZZ_pEContext_ptrs ptrs cdef ZZ_pEContext_c x cdef ntl_ZZ_pContext_class pc - cdef void restore_c(self) + cdef void restore_c(self) noexcept cdef ntl_ZZ_pX f cpdef void _assert_is_current_modulus(self) except * diff --git a/src/sage/libs/ntl/ntl_ZZ_pEContext.pyx b/src/sage/libs/ntl/ntl_ZZ_pEContext.pyx index fca10d5667f..affd31d299d 100644 --- a/src/sage/libs/ntl/ntl_ZZ_pEContext.pyx +++ b/src/sage/libs/ntl/ntl_ZZ_pEContext.pyx @@ -122,7 +122,7 @@ cdef class ntl_ZZ_pEContext_class(): """ self.restore_c() - cdef void restore_c(self): + cdef void restore_c(self) noexcept: """ Sets the global NTL modulus to be self. diff --git a/src/sage/libs/ntl/ntl_ZZ_pEX.pxd b/src/sage/libs/ntl/ntl_ZZ_pEX.pxd index b00e87bbcec..de3e1e54fff 100644 --- a/src/sage/libs/ntl/ntl_ZZ_pEX.pxd +++ b/src/sage/libs/ntl/ntl_ZZ_pEX.pxd @@ -6,4 +6,4 @@ cdef class ntl_ZZ_pEX(): cdef ntl_ZZ_pEContext_class c #cdef void setitem_from_int(ntl_ZZ_pX self, long i, int value) #cdef int getitem_as_int(ntl_ZZ_pX self, long i) - cdef ntl_ZZ_pEX _new(self) + cdef ntl_ZZ_pEX _new(self) noexcept diff --git a/src/sage/libs/ntl/ntl_ZZ_pEX.pyx b/src/sage/libs/ntl/ntl_ZZ_pEX.pyx index c12df77c2f0..6ebde955aa3 100644 --- a/src/sage/libs/ntl/ntl_ZZ_pEX.pyx +++ b/src/sage/libs/ntl/ntl_ZZ_pEX.pyx @@ -133,7 +133,7 @@ cdef class ntl_ZZ_pEX(): raise ValueError("modulus must not be None") self.c.restore_c() - cdef ntl_ZZ_pEX _new(self): + cdef ntl_ZZ_pEX _new(self) noexcept: cdef ntl_ZZ_pEX r self.c.restore_c() r = ntl_ZZ_pEX.__new__(ntl_ZZ_pEX) diff --git a/src/sage/libs/ntl/ntl_ZZ_pEX_linkage.pxi b/src/sage/libs/ntl/ntl_ZZ_pEX_linkage.pxi index caf74e6c64f..22d15b71b45 100644 --- a/src/sage/libs/ntl/ntl_ZZ_pEX_linkage.pxi +++ b/src/sage/libs/ntl/ntl_ZZ_pEX_linkage.pxi @@ -25,7 +25,7 @@ from sage.libs.ntl.ZZ_pEX cimport * from sage.libs.ntl.ntl_ZZ_pE cimport ntl_ZZ_pE from sage.libs.ntl.types cimport ZZ_pX_c, ZZ_pEX_c -cdef ZZ_pEX_c *celement_new(cparent parent): +cdef ZZ_pEX_c *celement_new(cparent parent) noexcept: """ EXAMPLES:: @@ -36,7 +36,7 @@ cdef ZZ_pEX_c *celement_new(cparent parent): parent[0].zzpec[0].restore() return new ZZ_pEX_c() -cdef int celement_delete(ZZ_pEX_c *e, cparent parent): +cdef int celement_delete(ZZ_pEX_c *e, cparent parent) noexcept: """ EXAMPLES:: @@ -48,7 +48,7 @@ cdef int celement_delete(ZZ_pEX_c *e, cparent parent): parent[0].zzpec[0].restore() del e -cdef int celement_construct(ZZ_pEX_c *e, cparent parent): +cdef int celement_construct(ZZ_pEX_c *e, cparent parent) noexcept: """ EXAMPLES:: @@ -58,7 +58,7 @@ cdef int celement_construct(ZZ_pEX_c *e, cparent parent): parent[0].zzpc[0].restore() parent[0].zzpec[0].restore() -cdef int celement_destruct(ZZ_pEX_c *e, cparent parent): +cdef int celement_destruct(ZZ_pEX_c *e, cparent parent) noexcept: """ EXAMPLES:: @@ -80,7 +80,7 @@ cdef int celement_gen(ZZ_pEX_c *e, long i, cparent parent) except -2: parent[0].zzpec[0].restore() ZZ_pEX_SetX(e[0]) -cdef object celement_repr(ZZ_pEX_c *e, cparent parent): +cdef object celement_repr(ZZ_pEX_c *e, cparent parent) noexcept: """ We ignore NTL's printing. diff --git a/src/sage/libs/ntl/ntl_ZZ_pX.pxd b/src/sage/libs/ntl/ntl_ZZ_pX.pxd index 6dfed011120..e414fc5c272 100644 --- a/src/sage/libs/ntl/ntl_ZZ_pX.pxd +++ b/src/sage/libs/ntl/ntl_ZZ_pX.pxd @@ -4,9 +4,9 @@ from sage.libs.ntl.ntl_ZZ_pContext cimport ntl_ZZ_pContext_class cdef class ntl_ZZ_pX(): cdef ZZ_pX_c x cdef ntl_ZZ_pContext_class c - cdef void setitem_from_int(ntl_ZZ_pX self, long i, int value) - cdef int getitem_as_int(ntl_ZZ_pX self, long i) - cdef ntl_ZZ_pX _new(self) + cdef void setitem_from_int(ntl_ZZ_pX self, long i, int value) noexcept + cdef int getitem_as_int(ntl_ZZ_pX self, long i) noexcept + cdef ntl_ZZ_pX _new(self) noexcept cdef class ntl_ZZ_pX_Modulus(): cdef ZZ_pX_Modulus_c x diff --git a/src/sage/libs/ntl/ntl_ZZ_pX.pyx b/src/sage/libs/ntl/ntl_ZZ_pX.pyx index 4ad48fb3496..3422239aaac 100644 --- a/src/sage/libs/ntl/ntl_ZZ_pX.pyx +++ b/src/sage/libs/ntl/ntl_ZZ_pX.pyx @@ -38,7 +38,7 @@ from sage.misc.randstate cimport current_randstate from sage.libs.gmp.mpz cimport * -cdef inline make_ZZ_p(ZZ_p_c* x, ntl_ZZ_pContext_class ctx): +cdef inline make_ZZ_p(ZZ_p_c* x, ntl_ZZ_pContext_class ctx) noexcept: cdef ntl_ZZ_p y sig_off() y = ntl_ZZ_p(modulus = ctx) @@ -47,7 +47,7 @@ cdef inline make_ZZ_p(ZZ_p_c* x, ntl_ZZ_pContext_class ctx): return y -cdef make_ZZ_pX(ZZ_pX_c* x, ntl_ZZ_pContext_class ctx): +cdef make_ZZ_pX(ZZ_pX_c* x, ntl_ZZ_pContext_class ctx) noexcept: cdef ntl_ZZ_pX y y = ntl_ZZ_pX.__new__(ntl_ZZ_pX) y.c = ctx @@ -138,7 +138,7 @@ cdef class ntl_ZZ_pX(): self.c = ntl_ZZ_pContext(ntl_ZZ(modulus)) self.c.restore_c() - cdef ntl_ZZ_pX _new(self): + cdef ntl_ZZ_pX _new(self) noexcept: cdef ntl_ZZ_pX r self.c.restore_c() r = ntl_ZZ_pX.__new__(ntl_ZZ_pX) @@ -222,7 +222,7 @@ cdef class ntl_ZZ_pX(): self.c.restore_c() ZZ_pX_SetCoeff(self.x, i, _a.x) - cdef void setitem_from_int(ntl_ZZ_pX self, long i, int value): + cdef void setitem_from_int(ntl_ZZ_pX self, long i, int value) noexcept: r""" Sets ith coefficient to value. @@ -267,7 +267,7 @@ cdef class ntl_ZZ_pX(): r.x = ZZ_pX_coeff( self.x, i) return r - cdef int getitem_as_int(ntl_ZZ_pX self, long i): + cdef int getitem_as_int(ntl_ZZ_pX self, long i) noexcept: r""" Returns ith coefficient as C int. Return value is only valid if the result fits into an int. diff --git a/src/sage/libs/ntl/ntl_lzz_p.pxd b/src/sage/libs/ntl/ntl_lzz_p.pxd index ec74b46d447..6a1466b62d3 100644 --- a/src/sage/libs/ntl/ntl_lzz_p.pxd +++ b/src/sage/libs/ntl/ntl_lzz_p.pxd @@ -4,4 +4,4 @@ from .ntl_lzz_pContext cimport ntl_zz_pContext_class cdef class ntl_zz_p(): cdef zz_p_c x cdef ntl_zz_pContext_class c - cdef ntl_zz_p _new(ntl_zz_p self) + cdef ntl_zz_p _new(ntl_zz_p self) noexcept diff --git a/src/sage/libs/ntl/ntl_lzz_p.pyx b/src/sage/libs/ntl/ntl_lzz_p.pyx index af86b9bcf69..0f7fd8fd5e3 100644 --- a/src/sage/libs/ntl/ntl_lzz_p.pyx +++ b/src/sage/libs/ntl/ntl_lzz_p.pyx @@ -150,7 +150,7 @@ cdef class ntl_zz_p(): ## now that we've determined the modulus, set that modulus. self.c.restore_c() - cdef ntl_zz_p _new(self): + cdef ntl_zz_p _new(self) noexcept: """ Quick and dirty zz_p object creation. diff --git a/src/sage/libs/ntl/ntl_lzz_pContext.pxd b/src/sage/libs/ntl/ntl_lzz_pContext.pxd index 058d2842ecc..cffc49f6b4c 100644 --- a/src/sage/libs/ntl/ntl_lzz_pContext.pxd +++ b/src/sage/libs/ntl/ntl_lzz_pContext.pxd @@ -2,5 +2,5 @@ from .types cimport zz_pContext_c cdef class ntl_zz_pContext_class(): cdef zz_pContext_c x - cdef void restore_c(self) + cdef void restore_c(self) noexcept cdef long p diff --git a/src/sage/libs/ntl/ntl_lzz_pContext.pyx b/src/sage/libs/ntl/ntl_lzz_pContext.pyx index 0cb0a69642a..2c1c941b9e8 100644 --- a/src/sage/libs/ntl/ntl_lzz_pContext.pyx +++ b/src/sage/libs/ntl/ntl_lzz_pContext.pyx @@ -92,7 +92,7 @@ cdef class ntl_zz_pContext_class(): """ self.restore_c() - cdef void restore_c(self): + cdef void restore_c(self) noexcept: """ Actual code for the above. diff --git a/src/sage/libs/ntl/ntl_lzz_pX.pxd b/src/sage/libs/ntl/ntl_lzz_pX.pxd index 3ab79084299..2cc09419fe5 100644 --- a/src/sage/libs/ntl/ntl_lzz_pX.pxd +++ b/src/sage/libs/ntl/ntl_lzz_pX.pxd @@ -6,4 +6,4 @@ from sage.libs.ntl.ntl_lzz_pContext cimport ntl_zz_pContext_class cdef class ntl_zz_pX(): cdef zz_pX_c x cdef ntl_zz_pContext_class c - cdef ntl_zz_pX _new(self) + cdef ntl_zz_pX _new(self) noexcept diff --git a/src/sage/libs/ntl/ntl_lzz_pX.pyx b/src/sage/libs/ntl/ntl_lzz_pX.pyx index 7d19cc55e37..bbcd9f14dec 100644 --- a/src/sage/libs/ntl/ntl_lzz_pX.pyx +++ b/src/sage/libs/ntl/ntl_lzz_pX.pyx @@ -232,7 +232,7 @@ cdef class ntl_zz_pX(): zz_pX_SetCoeff_long(self.x, i, val) return - cdef ntl_zz_pX _new(self): + cdef ntl_zz_pX _new(self) noexcept: """ Quick and dirty method for creating a new object with the same zz_pContext as self. diff --git a/src/sage/libs/ntl/ntl_mat_GF2.pxd b/src/sage/libs/ntl/ntl_mat_GF2.pxd index b900d2f9e3f..34176ca530e 100644 --- a/src/sage/libs/ntl/ntl_mat_GF2.pxd +++ b/src/sage/libs/ntl/ntl_mat_GF2.pxd @@ -3,5 +3,5 @@ from .ntl_GF2 cimport ntl_GF2 cdef class ntl_mat_GF2(): cdef mat_GF2_c x - cdef ntl_GF2 _new_element(self) - cdef ntl_mat_GF2 _new(self) + cdef ntl_GF2 _new_element(self) noexcept + cdef ntl_mat_GF2 _new(self) noexcept diff --git a/src/sage/libs/ntl/ntl_mat_GF2.pyx b/src/sage/libs/ntl/ntl_mat_GF2.pyx index ee90bf17fce..4c7b19a066b 100644 --- a/src/sage/libs/ntl/ntl_mat_GF2.pyx +++ b/src/sage/libs/ntl/ntl_mat_GF2.pyx @@ -118,12 +118,12 @@ cdef class ntl_mat_GF2(): mat_GF2_setitem(&self.x, i, j, &(elem).x) sig_off() - cdef ntl_GF2 _new_element(self): + cdef ntl_GF2 _new_element(self) noexcept: cdef ntl_GF2 r r = ntl_GF2.__new__(ntl_GF2) return r - cdef ntl_mat_GF2 _new(self): + cdef ntl_mat_GF2 _new(self) noexcept: cdef ntl_mat_GF2 r r = ntl_mat_GF2.__new__(ntl_mat_GF2) r.x.SetDims(self.x.NumRows(),self.x.NumCols()) diff --git a/src/sage/libs/ntl/ntl_mat_GF2E.pxd b/src/sage/libs/ntl/ntl_mat_GF2E.pxd index 5c8aacd5cef..c01392b81db 100644 --- a/src/sage/libs/ntl/ntl_mat_GF2E.pxd +++ b/src/sage/libs/ntl/ntl_mat_GF2E.pxd @@ -5,5 +5,5 @@ from .ntl_GF2E cimport ntl_GF2E cdef class ntl_mat_GF2E(): cdef mat_GF2E_c x cdef ntl_GF2EContext_class c - cdef ntl_GF2E _new_element(self) - cdef ntl_mat_GF2E _new(self) + cdef ntl_GF2E _new_element(self) noexcept + cdef ntl_mat_GF2E _new(self) noexcept diff --git a/src/sage/libs/ntl/ntl_mat_GF2E.pyx b/src/sage/libs/ntl/ntl_mat_GF2E.pyx index 46a5c9bc59e..24f75c6c026 100644 --- a/src/sage/libs/ntl/ntl_mat_GF2E.pyx +++ b/src/sage/libs/ntl/ntl_mat_GF2E.pyx @@ -136,14 +136,14 @@ cdef class ntl_mat_GF2E(): self.c = ntl_GF2EContext(modulus) self.c.restore_c() - cdef ntl_GF2E _new_element(self): + cdef ntl_GF2E _new_element(self) noexcept: cdef ntl_GF2E r self.c.restore_c() r = ntl_GF2E.__new__(ntl_GF2E) r.c = self.c return r - cdef ntl_mat_GF2E _new(self): + cdef ntl_mat_GF2E _new(self) noexcept: cdef ntl_mat_GF2E r self.c.restore_c() r = ntl_mat_GF2E.__new__(ntl_mat_GF2E) diff --git a/src/sage/libs/ntl/ntl_mat_ZZ.pyx b/src/sage/libs/ntl/ntl_mat_ZZ.pyx index fb1769db352..8df56b2632e 100644 --- a/src/sage/libs/ntl/ntl_mat_ZZ.pyx +++ b/src/sage/libs/ntl/ntl_mat_ZZ.pyx @@ -32,7 +32,7 @@ from cpython.object cimport PyObject_RichCompare from .ntl_ZZ import unpickle_class_args -cdef inline ntl_ZZ make_ZZ(ZZ_c* x): +cdef inline ntl_ZZ make_ZZ(ZZ_c* x) noexcept: cdef ntl_ZZ y y = ntl_ZZ() y.x = x[0] @@ -40,12 +40,12 @@ cdef inline ntl_ZZ make_ZZ(ZZ_c* x): return y # You must do sig_on() before calling this function -cdef inline ntl_ZZ make_ZZ_sig_off(ZZ_c* x): +cdef inline ntl_ZZ make_ZZ_sig_off(ZZ_c* x) noexcept: cdef ntl_ZZ y = make_ZZ(x) sig_off() return y -cdef inline ntl_mat_ZZ make_mat_ZZ(mat_ZZ_c* x): +cdef inline ntl_mat_ZZ make_mat_ZZ(mat_ZZ_c* x) noexcept: cdef ntl_mat_ZZ y y = ntl_mat_ZZ.__new__(ntl_mat_ZZ) y.x = x[0] @@ -55,7 +55,7 @@ cdef inline ntl_mat_ZZ make_mat_ZZ(mat_ZZ_c* x): return y # You must do sig_on() before calling this function -cdef inline ntl_mat_ZZ make_mat_ZZ_sig_off(mat_ZZ_c* x): +cdef inline ntl_mat_ZZ make_mat_ZZ_sig_off(mat_ZZ_c* x) noexcept: cdef ntl_mat_ZZ y = make_mat_ZZ(x) sig_off() return y diff --git a/src/sage/libs/pari/convert_flint.pxd b/src/sage/libs/pari/convert_flint.pxd index 774b3c48bd8..3d6003f56bd 100644 --- a/src/sage/libs/pari/convert_flint.pxd +++ b/src/sage/libs/pari/convert_flint.pxd @@ -2,12 +2,12 @@ from cypari2.types cimport GEN from cypari2.gen cimport Gen from sage.libs.flint.types cimport fmpz_t, fmpz_mat_t, fmpq_t, fmpq_mat_t -cdef GEN _new_GEN_from_fmpz_t(fmpz_t value) -cdef GEN _new_GEN_from_fmpz_mat_t(fmpz_mat_t B) -cdef GEN _new_GEN_from_fmpz_mat_t_rotate90(fmpz_mat_t B) -cdef Gen integer_matrix(fmpz_mat_t B, bint rotate) +cdef GEN _new_GEN_from_fmpz_t(fmpz_t value) noexcept +cdef GEN _new_GEN_from_fmpz_mat_t(fmpz_mat_t B) noexcept +cdef GEN _new_GEN_from_fmpz_mat_t_rotate90(fmpz_mat_t B) noexcept +cdef Gen integer_matrix(fmpz_mat_t B, bint rotate) noexcept -cdef GEN _new_GEN_from_fmpq_t(fmpq_t value) -cdef GEN _new_GEN_from_fmpq_mat_t(fmpq_mat_t B) -cdef GEN _new_GEN_from_fmpq_mat_t_rotate90(fmpq_mat_t B) -cdef Gen rational_matrix(fmpq_mat_t B, bint rotate) +cdef GEN _new_GEN_from_fmpq_t(fmpq_t value) noexcept +cdef GEN _new_GEN_from_fmpq_mat_t(fmpq_mat_t B) noexcept +cdef GEN _new_GEN_from_fmpq_mat_t_rotate90(fmpq_mat_t B) noexcept +cdef Gen rational_matrix(fmpq_mat_t B, bint rotate) noexcept diff --git a/src/sage/libs/pari/convert_flint.pyx b/src/sage/libs/pari/convert_flint.pyx index 07dd6cfc3dd..340e72c13bb 100644 --- a/src/sage/libs/pari/convert_flint.pyx +++ b/src/sage/libs/pari/convert_flint.pyx @@ -31,7 +31,7 @@ from cypari2.stack cimport new_gen from .convert_gmp cimport _new_GEN_from_mpz_t -cdef inline GEN _new_GEN_from_fmpz_t(fmpz_t value): +cdef inline GEN _new_GEN_from_fmpz_t(fmpz_t value) noexcept: r""" Create a new PARI ``t_INT`` from a ``fmpz_t``. @@ -44,7 +44,7 @@ cdef inline GEN _new_GEN_from_fmpz_t(fmpz_t value): return stoi(value[0]) -cdef inline GEN _new_GEN_from_fmpq_t(fmpq_t value): +cdef inline GEN _new_GEN_from_fmpq_t(fmpq_t value) noexcept: r""" Create a new PARI ``t_RAT`` from a ``fmpq_t``. @@ -58,7 +58,7 @@ cdef inline GEN _new_GEN_from_fmpq_t(fmpq_t value): return mkfrac(num, denom) -cdef GEN _new_GEN_from_fmpz_mat_t(fmpz_mat_t B): +cdef GEN _new_GEN_from_fmpz_mat_t(fmpz_mat_t B) noexcept: r""" Create a new PARI ``t_MAT`` with ``nr`` rows and ``nc`` columns from a ``fmpz_mat_t``. @@ -76,7 +76,7 @@ cdef GEN _new_GEN_from_fmpz_mat_t(fmpz_mat_t B): return A -cdef GEN _new_GEN_from_fmpq_mat_t(fmpq_mat_t B): +cdef GEN _new_GEN_from_fmpq_mat_t(fmpq_mat_t B) noexcept: cdef GEN x cdef GEN A = zeromatcopy(fmpq_mat_nrows(B), fmpq_mat_ncols(B)) cdef Py_ssize_t i, j @@ -86,7 +86,7 @@ cdef GEN _new_GEN_from_fmpq_mat_t(fmpq_mat_t B): set_gcoeff(A, i+1, j+1, x) # A[i+1, j+1] = x (using 1-based indexing) return A -cdef GEN _new_GEN_from_fmpz_mat_t_rotate90(fmpz_mat_t B): +cdef GEN _new_GEN_from_fmpz_mat_t_rotate90(fmpz_mat_t B) noexcept: r""" Create a new PARI ``t_MAT`` with ``nr`` rows and ``nc`` columns from a ``fmpz_mat_t`` and rotate the matrix 90 degrees @@ -106,7 +106,7 @@ cdef GEN _new_GEN_from_fmpz_mat_t_rotate90(fmpz_mat_t B): return A -cdef GEN _new_GEN_from_fmpq_mat_t_rotate90(fmpq_mat_t B): +cdef GEN _new_GEN_from_fmpq_mat_t_rotate90(fmpq_mat_t B) noexcept: r""" Create a new PARI ``t_MAT`` with ``nr`` rows and ``nc`` columns from a ``fmpq_mat_t`` and rotate the matrix 90 degrees @@ -126,7 +126,7 @@ cdef GEN _new_GEN_from_fmpq_mat_t_rotate90(fmpq_mat_t B): return A -cdef Gen integer_matrix(fmpz_mat_t B, bint rotate): +cdef Gen integer_matrix(fmpz_mat_t B, bint rotate) noexcept: """ EXAMPLES:: @@ -142,7 +142,7 @@ cdef Gen integer_matrix(fmpz_mat_t B, bint rotate): return new_gen(g) -cdef Gen rational_matrix(fmpq_mat_t B, bint rotate): +cdef Gen rational_matrix(fmpq_mat_t B, bint rotate) noexcept: """ EXAMPLES:: diff --git a/src/sage/libs/pari/convert_gmp.pxd b/src/sage/libs/pari/convert_gmp.pxd index e08380f571d..b745a823ab5 100644 --- a/src/sage/libs/pari/convert_gmp.pxd +++ b/src/sage/libs/pari/convert_gmp.pxd @@ -2,12 +2,12 @@ from cypari2.types cimport GEN from cypari2.gen cimport Gen from sage.libs.gmp.types cimport mpz_t, mpq_t, mpz_ptr, mpq_ptr -cdef Gen new_gen_from_mpz_t(mpz_t value) -cdef GEN _new_GEN_from_mpz_t(mpz_t value) -cdef Gen new_gen_from_mpq_t(mpq_t value) -cdef GEN _new_GEN_from_mpq_t(mpq_t value) -cdef Gen new_gen_from_padic(long ordp, long relprec, mpz_t prime, mpz_t p_pow, mpz_t unit) -cdef GEN _new_GEN_from_mpq_t_matrix(mpq_t** B, long nr, long nc) -cdef Gen rational_matrix(mpq_t** B, long nr, long nc) -cdef void INT_to_mpz(mpz_ptr value, GEN g) -cdef void INTFRAC_to_mpq(mpq_ptr value, GEN g) +cdef Gen new_gen_from_mpz_t(mpz_t value) noexcept +cdef GEN _new_GEN_from_mpz_t(mpz_t value) noexcept +cdef Gen new_gen_from_mpq_t(mpq_t value) noexcept +cdef GEN _new_GEN_from_mpq_t(mpq_t value) noexcept +cdef Gen new_gen_from_padic(long ordp, long relprec, mpz_t prime, mpz_t p_pow, mpz_t unit) noexcept +cdef GEN _new_GEN_from_mpq_t_matrix(mpq_t** B, long nr, long nc) noexcept +cdef Gen rational_matrix(mpq_t** B, long nr, long nc) noexcept +cdef void INT_to_mpz(mpz_ptr value, GEN g) noexcept +cdef void INTFRAC_to_mpq(mpq_ptr value, GEN g) noexcept diff --git a/src/sage/libs/pari/convert_gmp.pyx b/src/sage/libs/pari/convert_gmp.pyx index fcd212a8703..4a38bd5f527 100644 --- a/src/sage/libs/pari/convert_gmp.pyx +++ b/src/sage/libs/pari/convert_gmp.pyx @@ -27,7 +27,7 @@ from sage.libs.gmp.all cimport * from cypari2.paridecl cimport * from cypari2.stack cimport new_gen -cdef Gen new_gen_from_mpz_t(mpz_t value): +cdef Gen new_gen_from_mpz_t(mpz_t value) noexcept: """ Create a new PARI Gen of type ``t_INT`` from a given GMP integer ``value``. @@ -53,7 +53,7 @@ cdef Gen new_gen_from_mpz_t(mpz_t value): return new_gen(_new_GEN_from_mpz_t(value)) -cdef inline GEN _new_GEN_from_mpz_t(mpz_t value): +cdef inline GEN _new_GEN_from_mpz_t(mpz_t value) noexcept: r""" Create a new PARI ``t_INT`` from a ``mpz_t``. @@ -73,7 +73,7 @@ cdef inline GEN _new_GEN_from_mpz_t(mpz_t value): return z -cdef Gen new_gen_from_mpq_t(mpq_t value): +cdef Gen new_gen_from_mpq_t(mpq_t value) noexcept: """ Create a new PARI Gen of type ``t_INT`` or ``t_FRAC`` from a given GMP rational ``value``. @@ -105,7 +105,7 @@ cdef Gen new_gen_from_mpq_t(mpq_t value): return new_gen(_new_GEN_from_mpq_t(value)) -cdef inline GEN _new_GEN_from_mpq_t(mpq_t value): +cdef inline GEN _new_GEN_from_mpq_t(mpq_t value) noexcept: r""" Create a new PARI ``t_INT`` or ``t_FRAC`` from a ``mpq_t``. @@ -121,7 +121,7 @@ cdef inline GEN _new_GEN_from_mpq_t(mpq_t value): cdef Gen new_gen_from_padic(long ordp, long relprec, - mpz_t prime, mpz_t p_pow, mpz_t unit): + mpz_t prime, mpz_t p_pow, mpz_t unit) noexcept: """ Create a new PARI Gen of type ``t_PADIC`` from the given input data as GMP integers. @@ -136,7 +136,7 @@ cdef Gen new_gen_from_padic(long ordp, long relprec, return new_gen(z) -cdef GEN _new_GEN_from_mpq_t_matrix(mpq_t** B, long nr, long nc): +cdef GEN _new_GEN_from_mpq_t_matrix(mpq_t** B, long nr, long nc) noexcept: """ Create a new PARI ``t_MAT`` from a given 2-dimensional array of GMP rationals ``mpq_t``. @@ -155,7 +155,7 @@ cdef GEN _new_GEN_from_mpq_t_matrix(mpq_t** B, long nr, long nc): return A -cdef Gen rational_matrix(mpq_t** B, long nr, long nc): +cdef Gen rational_matrix(mpq_t** B, long nr, long nc) noexcept: """ Create a new PARI matrix of type ``t_MAT`` from a given array of GMP rationals ``mpq_t``. @@ -180,7 +180,7 @@ cdef Gen rational_matrix(mpq_t** B, long nr, long nc): return new_gen(g) -cdef inline void INT_to_mpz(mpz_ptr value, GEN g): +cdef inline void INT_to_mpz(mpz_ptr value, GEN g) noexcept: """ Convert a PARI ``t_INT`` to a GMP integer, stored in ``value``. """ @@ -194,7 +194,7 @@ cdef inline void INT_to_mpz(mpz_ptr value, GEN g): mpz_neg(value, value) -cdef void INTFRAC_to_mpq(mpq_ptr value, GEN g): +cdef void INTFRAC_to_mpq(mpq_ptr value, GEN g) noexcept: """ Convert a PARI ``t_INT`` or ``t_FRAC`` to a GMP rational, stored in ``value``. diff --git a/src/sage/libs/pari/convert_sage.pxd b/src/sage/libs/pari/convert_sage.pxd index 266a8204a39..ffa9c0ef6c0 100644 --- a/src/sage/libs/pari/convert_sage.pxd +++ b/src/sage/libs/pari/convert_sage.pxd @@ -2,14 +2,14 @@ from cypari2.gen cimport Gen from sage.rings.integer cimport Integer from sage.rings.rational cimport Rational -cpdef gen_to_sage(Gen z, locals=*) +cpdef gen_to_sage(Gen z, locals=*) noexcept -cpdef set_integer_from_gen(Integer self, Gen x) -cpdef Gen new_gen_from_integer(Integer self) -cpdef set_rational_from_gen(Rational self, Gen x) -cpdef Gen new_gen_from_rational(Rational self) +cpdef set_integer_from_gen(Integer self, Gen x) noexcept +cpdef Gen new_gen_from_integer(Integer self) noexcept +cpdef set_rational_from_gen(Rational self, Gen x) noexcept +cpdef Gen new_gen_from_rational(Rational self) noexcept -cpdef pari_is_prime(Integer p) -cpdef pari_is_prime_power(Integer q, bint get_data) -cpdef unsigned long pari_maxprime() -cpdef list pari_prime_range(long c_start, long c_stop, bint py_ints=*) +cpdef pari_is_prime(Integer p) noexcept +cpdef pari_is_prime_power(Integer q, bint get_data) noexcept +cpdef unsigned long pari_maxprime() noexcept +cpdef list pari_prime_range(long c_start, long c_stop, bint py_ints=*) noexcept diff --git a/src/sage/libs/pari/convert_sage.pyx b/src/sage/libs/pari/convert_sage.pyx index 71a1744698e..500ed520312 100644 --- a/src/sage/libs/pari/convert_sage.pyx +++ b/src/sage/libs/pari/convert_sage.pyx @@ -38,7 +38,7 @@ from sage.rings.padics.factory import Qp from sage.rings.infinity import Infinity -cpdef gen_to_sage(Gen z, locals=None): +cpdef gen_to_sage(Gen z, locals=None) noexcept: """ Convert a PARI gen to a Sage/Python object. @@ -326,7 +326,7 @@ cpdef gen_to_sage(Gen z, locals=None): return sage_eval(str(z), locals=locals) -cpdef set_integer_from_gen(Integer self, Gen x): +cpdef set_integer_from_gen(Integer self, Gen x) noexcept: r""" EXAMPLES:: @@ -374,7 +374,7 @@ cpdef set_integer_from_gen(Integer self, Gen x): INT_to_mpz(self.value, (x).g) -cpdef Gen new_gen_from_integer(Integer self): +cpdef Gen new_gen_from_integer(Integer self) noexcept: """ TESTS:: @@ -386,7 +386,7 @@ cpdef Gen new_gen_from_integer(Integer self): return new_gen_from_mpz_t(self.value) -cpdef set_rational_from_gen(Rational self, Gen x): +cpdef set_rational_from_gen(Rational self, Gen x) noexcept: r""" EXAMPLES:: @@ -406,7 +406,7 @@ cpdef set_rational_from_gen(Rational self, Gen x): mpz_set_si(mpq_denref(self.value), 1) -cpdef Gen new_gen_from_rational(Rational self): +cpdef Gen new_gen_from_rational(Rational self) noexcept: """ TESTS:: @@ -418,7 +418,7 @@ cpdef Gen new_gen_from_rational(Rational self): return new_gen_from_mpq_t(self.value) -cpdef list pari_divisors_small(Integer self): +cpdef list pari_divisors_small(Integer self) noexcept: r""" Return the list of divisors of this number using PARI ``divisorsu``. @@ -464,7 +464,7 @@ cpdef list pari_divisors_small(Integer self): avma = ltop -cpdef pari_is_prime(Integer p): +cpdef pari_is_prime(Integer p) noexcept: r""" Return whether ``p`` is a prime. @@ -491,7 +491,7 @@ cpdef pari_is_prime(Integer p): return bool(uisprime(mpz_get_ui(p.value))) -cpdef pari_is_prime_power(Integer q, bint get_data): +cpdef pari_is_prime_power(Integer q, bint get_data) noexcept: r""" Return whether ``q`` is a prime power. @@ -532,7 +532,7 @@ cpdef pari_is_prime_power(Integer q, bint get_data): return (q, smallInteger(0)) if get_data else False -cpdef unsigned long pari_maxprime(): +cpdef unsigned long pari_maxprime() noexcept: """ Return to which limit PARI has computed the primes. @@ -548,7 +548,7 @@ cpdef unsigned long pari_maxprime(): return maxprime() -cpdef list pari_prime_range(long c_start, long c_stop, bint py_ints=False): +cpdef list pari_prime_range(long c_start, long c_stop, bint py_ints=False) noexcept: """ Return a list of all primes between ``start`` and ``stop - 1``, inclusive. diff --git a/src/sage/libs/pari/convert_sage_complex_double.pxd b/src/sage/libs/pari/convert_sage_complex_double.pxd index 51299d77759..803892b274a 100644 --- a/src/sage/libs/pari/convert_sage_complex_double.pxd +++ b/src/sage/libs/pari/convert_sage_complex_double.pxd @@ -1,13 +1,13 @@ from cypari2.gen cimport Gen from sage.rings.complex_double cimport ComplexDoubleElement -cpdef ComplexDoubleElement pari_to_cdf(Gen g) +cpdef ComplexDoubleElement pari_to_cdf(Gen g) noexcept -cpdef Gen new_gen_from_complex_double_element(ComplexDoubleElement self) +cpdef Gen new_gen_from_complex_double_element(ComplexDoubleElement self) noexcept -cpdef ComplexDoubleElement complex_double_element_eta(ComplexDoubleElement self, int flag) -cpdef ComplexDoubleElement complex_double_element_agm(ComplexDoubleElement self, right) -cpdef ComplexDoubleElement complex_double_element_dilog(ComplexDoubleElement self) -cpdef ComplexDoubleElement complex_double_element_gamma(ComplexDoubleElement self) -cpdef ComplexDoubleElement complex_double_element_gamma_inc(ComplexDoubleElement self, t) -cpdef ComplexDoubleElement complex_double_element_zeta(ComplexDoubleElement self) +cpdef ComplexDoubleElement complex_double_element_eta(ComplexDoubleElement self, int flag) noexcept +cpdef ComplexDoubleElement complex_double_element_agm(ComplexDoubleElement self, right) noexcept +cpdef ComplexDoubleElement complex_double_element_dilog(ComplexDoubleElement self) noexcept +cpdef ComplexDoubleElement complex_double_element_gamma(ComplexDoubleElement self) noexcept +cpdef ComplexDoubleElement complex_double_element_gamma_inc(ComplexDoubleElement self, t) noexcept +cpdef ComplexDoubleElement complex_double_element_zeta(ComplexDoubleElement self) noexcept diff --git a/src/sage/libs/pari/convert_sage_complex_double.pyx b/src/sage/libs/pari/convert_sage_complex_double.pyx index ef12c81f5e2..d4022c62a0f 100644 --- a/src/sage/libs/pari/convert_sage_complex_double.pyx +++ b/src/sage/libs/pari/convert_sage_complex_double.pyx @@ -6,7 +6,7 @@ from cypari2.paridecl cimport * from cypari2.convert cimport new_gen_from_double, new_t_COMPLEX_from_double -cpdef ComplexDoubleElement pari_to_cdf(Gen g): +cpdef ComplexDoubleElement pari_to_cdf(Gen g) noexcept: """ Create a CDF element from a PARI ``gen``. @@ -40,7 +40,7 @@ cpdef ComplexDoubleElement pari_to_cdf(Gen g): return z -cpdef Gen new_gen_from_complex_double_element(ComplexDoubleElement self): +cpdef Gen new_gen_from_complex_double_element(ComplexDoubleElement self) noexcept: """ Return PARI version of ``self``, as ``t_COMPLEX`` or ``t_REAL``. @@ -60,7 +60,7 @@ cpdef Gen new_gen_from_complex_double_element(ComplexDoubleElement self): return new_t_COMPLEX_from_double(GSL_REAL(self._complex), GSL_IMAG(self._complex)) -cpdef ComplexDoubleElement complex_double_element_eta(ComplexDoubleElement self, int flag): +cpdef ComplexDoubleElement complex_double_element_eta(ComplexDoubleElement self, int flag) noexcept: """ TESTS:: @@ -74,7 +74,7 @@ cpdef ComplexDoubleElement complex_double_element_eta(ComplexDoubleElement self, return pari_to_cdf(new_gen_from_complex_double_element(self).eta(flag)) -cpdef ComplexDoubleElement complex_double_element_agm(ComplexDoubleElement self, right): +cpdef ComplexDoubleElement complex_double_element_agm(ComplexDoubleElement self, right) noexcept: """ TESTS:: @@ -85,7 +85,7 @@ cpdef ComplexDoubleElement complex_double_element_agm(ComplexDoubleElement self, return pari_to_cdf(new_gen_from_complex_double_element(self).agm(right)) -cpdef ComplexDoubleElement complex_double_element_dilog(ComplexDoubleElement self): +cpdef ComplexDoubleElement complex_double_element_dilog(ComplexDoubleElement self) noexcept: """ TESTS:: @@ -96,7 +96,7 @@ cpdef ComplexDoubleElement complex_double_element_dilog(ComplexDoubleElement sel return pari_to_cdf(new_gen_from_complex_double_element(self).dilog()) -cpdef ComplexDoubleElement complex_double_element_gamma(ComplexDoubleElement self): +cpdef ComplexDoubleElement complex_double_element_gamma(ComplexDoubleElement self) noexcept: """ TESTS:: @@ -107,7 +107,7 @@ cpdef ComplexDoubleElement complex_double_element_gamma(ComplexDoubleElement sel return pari_to_cdf(new_gen_from_complex_double_element(self).gamma()) -cpdef ComplexDoubleElement complex_double_element_gamma_inc(ComplexDoubleElement self, t): +cpdef ComplexDoubleElement complex_double_element_gamma_inc(ComplexDoubleElement self, t) noexcept: """ TESTS:: @@ -118,7 +118,7 @@ cpdef ComplexDoubleElement complex_double_element_gamma_inc(ComplexDoubleElement return pari_to_cdf(new_gen_from_complex_double_element(self).incgam(t)) -cpdef ComplexDoubleElement complex_double_element_zeta(ComplexDoubleElement self): +cpdef ComplexDoubleElement complex_double_element_zeta(ComplexDoubleElement self) noexcept: """ TESTS:: diff --git a/src/sage/libs/pari/convert_sage_real_double.pxd b/src/sage/libs/pari/convert_sage_real_double.pxd index 12fa7418e69..df2119d0370 100644 --- a/src/sage/libs/pari/convert_sage_real_double.pxd +++ b/src/sage/libs/pari/convert_sage_real_double.pxd @@ -1,4 +1,4 @@ from cypari2.gen cimport Gen from sage.rings.real_double cimport RealDoubleElement -cpdef Gen new_gen_from_real_double_element(RealDoubleElement self) +cpdef Gen new_gen_from_real_double_element(RealDoubleElement self) noexcept diff --git a/src/sage/libs/pari/convert_sage_real_double.pyx b/src/sage/libs/pari/convert_sage_real_double.pyx index 6d7ffe7038e..ee7eba3f4a8 100644 --- a/src/sage/libs/pari/convert_sage_real_double.pyx +++ b/src/sage/libs/pari/convert_sage_real_double.pyx @@ -1,6 +1,6 @@ from cypari2.convert cimport new_gen_from_double -cpdef Gen new_gen_from_real_double_element(RealDoubleElement self): +cpdef Gen new_gen_from_real_double_element(RealDoubleElement self) noexcept: """ Return a PARI representation of ``self``. diff --git a/src/sage/libs/pari/misc.pxd b/src/sage/libs/pari/misc.pxd index ae89aff0b84..da162742f1d 100644 --- a/src/sage/libs/pari/misc.pxd +++ b/src/sage/libs/pari/misc.pxd @@ -1,3 +1,3 @@ from cypari2.gen cimport Gen -cdef Gen new_t_POL_from_int_star(int* vals, unsigned long length, long varnum) +cdef Gen new_t_POL_from_int_star(int* vals, unsigned long length, long varnum) noexcept diff --git a/src/sage/libs/pari/misc.pyx b/src/sage/libs/pari/misc.pyx index 1ed774d417c..02fd8403b8e 100644 --- a/src/sage/libs/pari/misc.pyx +++ b/src/sage/libs/pari/misc.pyx @@ -3,7 +3,7 @@ from cypari2.paridecl cimport * from cypari2.stack cimport new_gen -cdef Gen new_t_POL_from_int_star(int* vals, unsigned long length, long varnum): +cdef Gen new_t_POL_from_int_star(int* vals, unsigned long length, long varnum) noexcept: """ Convert an array of ints to a PARI polynomial. diff --git a/src/sage/libs/singular/function.pxd b/src/sage/libs/singular/function.pxd index 503384004d5..29748c039c6 100644 --- a/src/sage/libs/singular/function.pxd +++ b/src/sage/libs/singular/function.pxd @@ -19,7 +19,7 @@ from sage.libs.singular.decl cimport leftv, idhdl, syStrategy, matrix, poly, ide from sage.libs.singular.decl cimport ring as singular_ring from sage.rings.polynomial.multi_polynomial_libsingular cimport MPolynomialRing_libsingular, MPolynomial_libsingular -cdef new_sage_polynomial(ring, poly *p) +cdef new_sage_polynomial(ring, poly *p) noexcept cdef poly* access_singular_poly(p) except -1 cdef singular_ring* access_singular_ring(r) except -1 @@ -35,8 +35,8 @@ cdef class Converter(SageObject): cdef object _sage_ring cdef singular_ring* _singular_ring cdef leftv* pop_front(self) except NULL - cdef leftv * _append_leftv(self, leftv *v) - cdef leftv * _append(self, void* data, int res_type) + cdef leftv * _append_leftv(self, leftv *v) noexcept + cdef leftv * _append(self, void* data, int res_type) noexcept cdef leftv * append_polynomial(self, p) except NULL cdef leftv * append_ideal(self, i) except NULL cdef leftv * append_number(self, n) except NULL @@ -50,15 +50,15 @@ cdef class Converter(SageObject): cdef leftv * append_matrix(self, a) except NULL cdef leftv * append_ring(self, r) except NULL cdef leftv * append_module(self, m) except NULL - cdef to_sage_integer_matrix(self, intvec *mat) - cdef object to_sage_module_element_sequence_destructive(self, ideal *i) - cdef to_sage_vector_destructive(self, poly *p, free_module = ?) - cdef to_sage_matrix(self, matrix* mat) - cdef to_python(self, leftv* to_convert) + cdef to_sage_integer_matrix(self, intvec *mat) noexcept + cdef object to_sage_module_element_sequence_destructive(self, ideal *i) noexcept + cdef to_sage_vector_destructive(self, poly *p, free_module = ?) noexcept + cdef to_sage_matrix(self, matrix* mat) noexcept + cdef to_python(self, leftv* to_convert) noexcept cdef class BaseCallHandler: - cdef leftv* handle_call(self, Converter argument_list, singular_ring *_ring=?) - cdef bint free_res(self) + cdef leftv* handle_call(self, Converter argument_list, singular_ring *_ring=?) noexcept + cdef bint free_res(self) noexcept cdef class LibraryCallHandler(BaseCallHandler): cdef idhdl * proc_idhdl @@ -72,9 +72,9 @@ cdef class SingularFunction(SageObject): cdef MPolynomialRing_libsingular _ring cdef BaseCallHandler call_handler - cdef BaseCallHandler get_call_handler(self) - cdef bint function_exists(self) - cdef common_ring(self, tuple args, ring=?) + cdef BaseCallHandler get_call_handler(self) noexcept + cdef bint function_exists(self) noexcept + cdef common_ring(self, tuple args, ring=?) noexcept cdef class SingularLibraryFunction(SingularFunction): pass @@ -83,4 +83,4 @@ cdef class SingularKernelFunction(SingularFunction): pass # the most direct function call interface -cdef call_function(SingularFunction self, tuple args, object R, bint signal_handler=?, object attributes=?) +cdef call_function(SingularFunction self, tuple args, object R, bint signal_handler=?, object attributes=?) noexcept diff --git a/src/sage/libs/singular/function.pyx b/src/sage/libs/singular/function.pyx index c597c63aafe..ac4bde0c20b 100644 --- a/src/sage/libs/singular/function.pyx +++ b/src/sage/libs/singular/function.pyx @@ -339,7 +339,7 @@ cdef class Resolution: self._resolution.references -= 1 -cdef leftv* new_leftv(void *data, res_type): +cdef leftv* new_leftv(void *data, res_type) noexcept: """ INPUT: @@ -353,7 +353,7 @@ cdef leftv* new_leftv(void *data, res_type): res.rtyp = res_type return res -cdef free_leftv(leftv *args, ring *r = NULL): +cdef free_leftv(leftv *args, ring *r = NULL) noexcept: """ Kills this ``leftv`` and all ``leftv``s in the tail. @@ -393,7 +393,7 @@ def is_sage_wrapper_for_singular_ring(ring): return True return False -cdef new_sage_polynomial(ring, poly *p): +cdef new_sage_polynomial(ring, poly *p) noexcept: if isinstance(ring, MPolynomialRing_libsingular): return new_MP(ring, p) else: @@ -456,7 +456,7 @@ cdef ring* access_singular_ring(r) except -1: return ( r )._ring raise ValueError("not a singular polynomial ring wrapper") -cdef poly* copy_sage_polynomial_into_singular_poly(p): +cdef poly* copy_sage_polynomial_into_singular_poly(p) noexcept: return p_Copy(access_singular_poly(p), access_singular_ring(p.parent())) @@ -653,7 +653,7 @@ cdef class Converter(SageObject): res.next = NULL return res - cdef leftv *_append_leftv(self, leftv *v): + cdef leftv *_append_leftv(self, leftv *v) noexcept: """ Append a new Singular element to the list. """ @@ -667,7 +667,7 @@ cdef class Converter(SageObject): self.args = v return v - cdef leftv *_append(self, void* data, int res_type): + cdef leftv *_append(self, void* data, int res_type) noexcept: """ Create a new ``leftv`` and append it to the list. @@ -678,7 +678,7 @@ cdef class Converter(SageObject): """ return self._append_leftv( new_leftv(data, res_type) ) - cdef to_sage_matrix(self, matrix* mat): + cdef to_sage_matrix(self, matrix* mat) noexcept: """ Convert singular matrix to matrix over the polynomial ring. """ @@ -693,7 +693,7 @@ cdef class Converter(SageObject): result[i,j] = p return result - cdef to_sage_vector_destructive(self, poly *p, free_module = None): + cdef to_sage_vector_destructive(self, poly *p, free_module = None) noexcept: cdef int rank if free_module: rank = free_module.rank() @@ -733,7 +733,7 @@ cdef class Converter(SageObject): result.append(new_sage_polynomial(self._sage_ring, first)) return free_module(result) - cdef object to_sage_module_element_sequence_destructive( self, ideal *i): + cdef object to_sage_module_element_sequence_destructive( self, ideal *i) noexcept: """ Convert a SINGULAR module to a Sage Sequence (the format Sage stores a Groebner basis in). @@ -756,7 +756,7 @@ cdef class Converter(SageObject): return Sequence(l, check=False, immutable=True) - cdef to_sage_integer_matrix(self, intvec* mat): + cdef to_sage_integer_matrix(self, intvec* mat) noexcept: """ Convert Singular matrix to matrix over the polynomial ring. """ @@ -908,7 +908,7 @@ cdef class Converter(SageObject): b = str_to_bytes(n) return self._append(omStrDup(b), STRING_CMD) - cdef to_python(self, leftv* to_convert): + cdef to_python(self, leftv* to_convert) noexcept: """ Convert the ``leftv`` to a Python object. @@ -994,13 +994,13 @@ cdef class BaseCallHandler: A call handler is an abstraction which hides the details of the implementation differences between kernel and library functions. """ - cdef leftv* handle_call(self, Converter argument_list, ring *_ring=NULL): + cdef leftv* handle_call(self, Converter argument_list, ring *_ring=NULL) noexcept: """ Actual function call. """ return NULL - cdef bint free_res(self): + cdef bint free_res(self) noexcept: """ Do we need to free the result object. """ @@ -1029,7 +1029,7 @@ cdef class LibraryCallHandler(BaseCallHandler): """ super().__init__() - cdef leftv* handle_call(self, Converter argument_list, ring *_ring=NULL): + cdef leftv* handle_call(self, Converter argument_list, ring *_ring=NULL) noexcept: if _ring != currRing: rChangeCurrRing(_ring) cdef bint error = iiMake_proc(self.proc_idhdl, NULL, argument_list.args) cdef leftv * res @@ -1041,7 +1041,7 @@ cdef class LibraryCallHandler(BaseCallHandler): return res raise RuntimeError("Error raised calling singular function") - cdef bint free_res(self): + cdef bint free_res(self) noexcept: """ We do not need to free the result object for library functions. @@ -1073,7 +1073,7 @@ cdef class KernelCallHandler(BaseCallHandler): self.cmd_n = cmd_n self.arity = arity - cdef leftv* handle_call(self, Converter argument_list, ring *_ring=NULL): + cdef leftv* handle_call(self, Converter argument_list, ring *_ring=NULL) noexcept: cdef leftv * res res = omAllocBin(sleftv_bin) res.Init() @@ -1129,7 +1129,7 @@ cdef class KernelCallHandler(BaseCallHandler): .format(number_of_arguments, self.arity)) return NULL - cdef bint free_res(self): + cdef bint free_res(self) noexcept: """ We need to free the result object for kernel functions. """ @@ -1168,13 +1168,13 @@ cdef class SingularFunction(SageObject): currRingHdl.data.uring = omAlloc0Bin(sip_sring_bin) currRingHdl.data.uring.ref += 1 - cdef BaseCallHandler get_call_handler(self): + cdef BaseCallHandler get_call_handler(self) noexcept: """ Return a call handler which does the actual work. """ raise NotImplementedError - cdef bint function_exists(self): + cdef bint function_exists(self) noexcept: """ Return ``True`` if the function exists in this interface. """ @@ -1358,7 +1358,7 @@ The Singular documentation for '%s' is given below. else: return prefix + "\n::\n\n"+" Singular documentation not found" - cdef common_ring(self, tuple args, ring=None): + cdef common_ring(self, tuple args, ring=None) noexcept: """ Return the common ring for the argument list ``args``. @@ -1442,7 +1442,7 @@ The Singular documentation for '%s' is given below. return richcmp(lx._name, rx._name, op) -cdef inline call_function(SingularFunction self, tuple args, object R, bint signal_handler=True, attributes=None): +cdef inline call_function(SingularFunction self, tuple args, object R, bint signal_handler=True, attributes=None) noexcept: global currRingHdl global errorreported global currentVoice @@ -1530,7 +1530,7 @@ cdef class SingularLibraryFunction(SingularFunction): super().__init__(name) self.call_handler = self.get_call_handler() - cdef BaseCallHandler get_call_handler(self): + cdef BaseCallHandler get_call_handler(self) noexcept: cdef idhdl* singular_idhdl = ggetid(str_to_bytes(self._name)) if singular_idhdl==NULL: raise NameError("Singular library function {!r} is not defined".format(self._name)) @@ -1541,7 +1541,7 @@ cdef class SingularLibraryFunction(SingularFunction): res.proc_idhdl = singular_idhdl return res - cdef bint function_exists(self): + cdef bint function_exists(self) noexcept: cdef idhdl* singular_idhdl = ggetid(str_to_bytes(self._name)) return singular_idhdl!=NULL @@ -1577,7 +1577,7 @@ cdef class SingularKernelFunction(SingularFunction): super().__init__(name) self.call_handler = self.get_call_handler() - cdef BaseCallHandler get_call_handler(self): + cdef BaseCallHandler get_call_handler(self) noexcept: cdef int cmd_n = 0 arity = IsCmd(str_to_bytes(self._name), cmd_n) # call by reverence for CMD_n if not cmd_n: @@ -1585,7 +1585,7 @@ cdef class SingularKernelFunction(SingularFunction): return KernelCallHandler(cmd_n, arity) - cdef bint function_exists(self): + cdef bint function_exists(self) noexcept: cdef int cmd_n = -1 arity = IsCmd(str_to_bytes(self._name), cmd_n) # call by reverence for CMD_n return cmd_n != -1 @@ -1842,7 +1842,7 @@ def list_of_functions(packages=False): h = IDNEXT(h) return l -cdef inline RingWrap new_RingWrap(ring* r): +cdef inline RingWrap new_RingWrap(ring* r) noexcept: cdef RingWrap ring_wrap_result = RingWrap.__new__(RingWrap) ring_wrap_result._ring = r ring_wrap_result._ring.ref += 1 diff --git a/src/sage/libs/singular/groebner_strategy.pxd b/src/sage/libs/singular/groebner_strategy.pxd index 605e2679228..391f11aee97 100644 --- a/src/sage/libs/singular/groebner_strategy.pxd +++ b/src/sage/libs/singular/groebner_strategy.pxd @@ -11,11 +11,11 @@ cdef class GroebnerStrategy(SageObject): cdef MPolynomialRing_libsingular _parent cdef object _ideal - cpdef MPolynomial_libsingular normal_form(self, MPolynomial_libsingular p) + cpdef MPolynomial_libsingular normal_form(self, MPolynomial_libsingular p) noexcept cdef class NCGroebnerStrategy(SageObject): cdef skStrategy *_strat cdef NCPolynomialRing_plural _parent cdef object _ideal - cpdef NCPolynomial_plural normal_form(self, NCPolynomial_plural p) + cpdef NCPolynomial_plural normal_form(self, NCPolynomial_plural p) noexcept diff --git a/src/sage/libs/singular/groebner_strategy.pyx b/src/sage/libs/singular/groebner_strategy.pyx index c2417fb927d..40a0a0f939d 100644 --- a/src/sage/libs/singular/groebner_strategy.pyx +++ b/src/sage/libs/singular/groebner_strategy.pyx @@ -260,7 +260,7 @@ cdef class GroebnerStrategy(SageObject): """ return unpickle_GroebnerStrategy0, (self._ideal,) - cpdef MPolynomial_libsingular normal_form(self, MPolynomial_libsingular p): + cpdef MPolynomial_libsingular normal_form(self, MPolynomial_libsingular p) noexcept: """ Compute the normal form of ``p`` with respect to the generators of this object. @@ -511,7 +511,7 @@ cdef class NCGroebnerStrategy(SageObject): """ return unpickle_NCGroebnerStrategy0, (self._ideal,) - cpdef NCPolynomial_plural normal_form(self, NCPolynomial_plural p): + cpdef NCPolynomial_plural normal_form(self, NCPolynomial_plural p) noexcept: """ Compute the normal form of ``p`` with respect to the generators of this object. diff --git a/src/sage/libs/singular/polynomial.pxd b/src/sage/libs/singular/polynomial.pxd index c5cbd292cca..df27179da54 100644 --- a/src/sage/libs/singular/polynomial.pxd +++ b/src/sage/libs/singular/polynomial.pxd @@ -17,21 +17,21 @@ from sage.structure.element cimport RingElement from sage.libs.singular.decl cimport poly, ring cdef int singular_polynomial_check(poly *p, ring *r) except -1 -cdef int singular_polynomial_add (poly **ret, poly *p, poly *q, ring *r) -cdef int singular_polynomial_call (poly **ret, poly *p, ring *r, list args, poly *(*get_element)(object)) -cdef int singular_polynomial_cmp (poly *p, poly *q, ring *r) -cdef int singular_polynomial_rmul (poly **ret, poly *p, RingElement q, ring *r) +cdef int singular_polynomial_add (poly **ret, poly *p, poly *q, ring *r) noexcept +cdef int singular_polynomial_call (poly **ret, poly *p, ring *r, list args, poly *(*get_element)(object)) noexcept +cdef int singular_polynomial_cmp (poly *p, poly *q, ring *r) noexcept +cdef int singular_polynomial_rmul (poly **ret, poly *p, RingElement q, ring *r) noexcept cdef int singular_polynomial_mul (poly **ret, poly *p, poly *q, ring *r) except -1 -cdef int singular_polynomial_sub (poly **ret, poly *p, poly *q, ring *r) +cdef int singular_polynomial_sub (poly **ret, poly *p, poly *q, ring *r) noexcept cdef int singular_polynomial_div_coeff (poly **ret, poly *p, poly *q, ring *r) except -1 cdef int singular_polynomial_pow (poly **ret, poly *p, unsigned long exp, ring *r) except -1 -cdef int singular_polynomial_neg(poly **ret, poly *p, ring *r) +cdef int singular_polynomial_neg(poly **ret, poly *p, ring *r) noexcept -cdef object singular_polynomial_latex(poly *p, ring *r, object base, object latex_gens) -cdef object singular_polynomial_str(poly *p, ring *r) -cdef object singular_polynomial_str_with_changed_varnames(poly *p, ring *r, object varnames) -cdef long singular_polynomial_deg(poly *p, poly *x, ring *r) +cdef object singular_polynomial_latex(poly *p, ring *r, object base, object latex_gens) noexcept +cdef object singular_polynomial_str(poly *p, ring *r) noexcept +cdef object singular_polynomial_str_with_changed_varnames(poly *p, ring *r, object varnames) noexcept +cdef long singular_polynomial_deg(poly *p, poly *x, ring *r) noexcept -cdef int singular_polynomial_length_bounded(poly *p, int bound) +cdef int singular_polynomial_length_bounded(poly *p, int bound) noexcept cdef int singular_vector_maximal_component(poly *v, ring *r) except -1 cdef int singular_polynomial_subst(poly **p, int var_index, poly *value, ring *r) except -1 diff --git a/src/sage/libs/singular/polynomial.pyx b/src/sage/libs/singular/polynomial.pyx index 9f81a20b0a7..d208aa9a37c 100644 --- a/src/sage/libs/singular/polynomial.pyx +++ b/src/sage/libs/singular/polynomial.pyx @@ -51,7 +51,7 @@ cdef int singular_polynomial_check(poly *p, ring *r) except -1: p = p.next return 0 -cdef int singular_polynomial_add(poly **ret, poly *p, poly *q, ring *r): +cdef int singular_polynomial_add(poly **ret, poly *p, poly *q, ring *r) noexcept: """ ``ret[0] = p+q`` where ``p`` and ``p`` in ``r``. @@ -78,7 +78,7 @@ cdef int singular_polynomial_add(poly **ret, poly *p, poly *q, ring *r): ret[0] = p_Add_q(p, q, r) return 0 -cdef int singular_polynomial_sub(poly **ret, poly *p, poly *q, ring *r): +cdef int singular_polynomial_sub(poly **ret, poly *p, poly *q, ring *r) noexcept: """ ``ret[0] = p-q`` where ``p`` and ``p`` in ``r``. @@ -105,7 +105,7 @@ cdef int singular_polynomial_sub(poly **ret, poly *p, poly *q, ring *r): ret[0] = p_Add_q(p, p_Neg(q, r), r) return 0 -cdef int singular_polynomial_rmul(poly **ret, poly *p, RingElement n, ring *r): +cdef int singular_polynomial_rmul(poly **ret, poly *p, RingElement n, ring *r) noexcept: """ ``ret[0] = n*p`` where ``n`` is a coefficient and ``p`` in ``r``. @@ -132,7 +132,7 @@ cdef int singular_polynomial_rmul(poly **ret, poly *p, RingElement n, ring *r): n_Delete(&_n, r.cf) return 0 -cdef int singular_polynomial_call(poly **ret, poly *p, ring *r, list args, poly *(*get_element)(object)): +cdef int singular_polynomial_call(poly **ret, poly *p, ring *r, list args, poly *(*get_element)(object)) noexcept: """ ``ret[0] = p(*args)`` where each entry in arg is a polynomial and ``p`` in ``r``. @@ -231,7 +231,7 @@ cdef int singular_polynomial_call(poly **ret, poly *p, ring *r, list args, poly return 0 -cdef int singular_polynomial_cmp(poly *p, poly *q, ring *r): +cdef int singular_polynomial_cmp(poly *p, poly *q, ring *r) noexcept: """ Compare two Singular elements ``p`` and ``q`` in ``r``. @@ -399,7 +399,7 @@ cdef int singular_polynomial_pow(poly **ret, poly *p, unsigned long exp, ring *r sig_off() return 0 -cdef int singular_polynomial_neg(poly **ret, poly *p, ring *r): +cdef int singular_polynomial_neg(poly **ret, poly *p, ring *r) noexcept: """ ``ret[0] = -p where ``p`` in ``r``. @@ -425,7 +425,7 @@ cdef int singular_polynomial_neg(poly **ret, poly *p, ring *r): ret[0] = p_Neg(p_Copy(p,r),r) return 0 -cdef object singular_polynomial_str(poly *p, ring *r): +cdef object singular_polynomial_str(poly *p, ring *r) noexcept: """ Return the string representation of ``p``. @@ -450,7 +450,7 @@ cdef object singular_polynomial_str(poly *p, ring *r): s = parenthvar_pattern.sub("\\1", s) return s -cdef object singular_polynomial_latex(poly *p, ring *r, object base, object latex_gens): +cdef object singular_polynomial_latex(poly *p, ring *r, object base, object latex_gens) noexcept: r""" Return the LaTeX string representation of ``p``. @@ -532,7 +532,7 @@ cdef object singular_polynomial_latex(poly *p, ring *r, object base, object late return "0" return poly -cdef object singular_polynomial_str_with_changed_varnames(poly *p, ring *r, object varnames): +cdef object singular_polynomial_str_with_changed_varnames(poly *p, ring *r, object varnames) noexcept: cdef char **_names cdef char **_orig_names cdef int i @@ -555,7 +555,7 @@ cdef object singular_polynomial_str_with_changed_varnames(poly *p, ring *r, obje omFree(_names) return s -cdef long singular_polynomial_deg(poly *p, poly *x, ring *r): +cdef long singular_polynomial_deg(poly *p, poly *x, ring *r) noexcept: cdef long _deg, deg cdef int dummy @@ -579,7 +579,7 @@ cdef long singular_polynomial_deg(poly *p, poly *x, ring *r): p = pNext(p) return deg -cdef int singular_polynomial_length_bounded(poly *p, int bound): +cdef int singular_polynomial_length_bounded(poly *p, int bound) noexcept: """ Return the number of monomials in ``p`` but stop counting at ``bound``. diff --git a/src/sage/libs/singular/ring.pxd b/src/sage/libs/singular/ring.pxd index b6cc791355b..70ff788f21c 100644 --- a/src/sage/libs/singular/ring.pxd +++ b/src/sage/libs/singular/ring.pxd @@ -52,7 +52,7 @@ cdef ring *singular_ring_new(base_ring, n, names, term_order) except NULL cdef ring *singular_ring_reference(ring *existing_ring) except NULL # carefully delete a ring once its refcount is zero -cdef void singular_ring_delete(ring *doomed) +cdef void singular_ring_delete(ring *doomed) noexcept # Used internally for reference counting -cdef wrap_ring(ring* R) +cdef wrap_ring(ring* R) noexcept diff --git a/src/sage/libs/singular/ring.pyx b/src/sage/libs/singular/ring.pyx index 56dc364219c..494fd2c0caf 100644 --- a/src/sage/libs/singular/ring.pyx +++ b/src/sage/libs/singular/ring.pyx @@ -618,7 +618,7 @@ cdef class ring_wrapper_Py(): return (self._ring == r._ring) == (op == Py_EQ) -cdef wrap_ring(ring* R): +cdef wrap_ring(ring* R) noexcept: """ Wrap a C ring pointer into a Python object. @@ -690,7 +690,7 @@ cdef ring *singular_ring_reference(ring *existing_ring) except NULL: ############################################################################# -cdef void singular_ring_delete(ring *doomed): +cdef void singular_ring_delete(ring *doomed) noexcept: """ Carefully deallocate the ring, without changing "currRing" (since this method can be called at unpredictable times due to garbage @@ -745,7 +745,7 @@ cdef void singular_ring_delete(ring *doomed): ############################################################################# # helpers for debugging -cpdef poison_currRing(frame, event, arg): +cpdef poison_currRing(frame, event, arg) noexcept: """ Poison the ``currRing`` pointer. @@ -778,7 +778,7 @@ cpdef poison_currRing(frame, event, arg): return poison_currRing -cpdef print_currRing(): +cpdef print_currRing() noexcept: """ Print the ``currRing`` pointer. diff --git a/src/sage/libs/singular/singular.pxd b/src/sage/libs/singular/singular.pxd index e1a55fbcd84..d943a1018a2 100644 --- a/src/sage/libs/singular/singular.pxd +++ b/src/sage/libs/singular/singular.pxd @@ -18,41 +18,41 @@ from sage.rings.number_field.number_field_base cimport NumberField # Conversion from Singular to Sage types # ====================================== -cdef Rational si2sa_QQ(number (*), number **, ring (*)) -cdef Integer si2sa_ZZ(number (*),ring (*)) +cdef Rational si2sa_QQ(number (*), number **, ring (*)) noexcept +cdef Integer si2sa_ZZ(number (*),ring (*)) noexcept -cdef FFgivE si2sa_GFqGivaro(number *n, ring *_ring, Cache_givaro cache) -cdef FFgf2eE si2sa_GFqNTLGF2E(number *n, ring *_ring, Cache_ntl_gf2e cache) -cdef object si2sa_GFq_generic(number *n, ring *_ring, object base) -cdef object si2sa_ZZmod(number *n, ring *_ring, object base) +cdef FFgivE si2sa_GFqGivaro(number *n, ring *_ring, Cache_givaro cache) noexcept +cdef FFgf2eE si2sa_GFqNTLGF2E(number *n, ring *_ring, Cache_ntl_gf2e cache) noexcept +cdef object si2sa_GFq_generic(number *n, ring *_ring, object base) noexcept +cdef object si2sa_ZZmod(number *n, ring *_ring, object base) noexcept -cdef object si2sa_NF(number *n, ring *_ring, object base) +cdef object si2sa_NF(number *n, ring *_ring, object base) noexcept -cdef object si2sa_intvec(intvec *v) +cdef object si2sa_intvec(intvec *v) noexcept # dispatches to all the above. -cdef object si2sa(number *n, ring *_ring, object base) +cdef object si2sa(number *n, ring *_ring, object base) noexcept -cdef list singular_monomial_exponents(poly *p, ring *r) -cpdef list si2sa_resolution(Resolution res) -cpdef tuple si2sa_resolution_graded(Resolution res, tuple degrees) +cdef list singular_monomial_exponents(poly *p, ring *r) noexcept +cpdef list si2sa_resolution(Resolution res) noexcept +cpdef tuple si2sa_resolution_graded(Resolution res, tuple degrees) noexcept # ====================================== # Conversion from Sage to Singular types # ====================================== -cdef number *sa2si_QQ(Rational ,ring (*)) -cdef number *sa2si_ZZ(Integer d, ring *_ring) +cdef number *sa2si_QQ(Rational ,ring (*)) noexcept +cdef number *sa2si_ZZ(Integer d, ring *_ring) noexcept -cdef number *sa2si_GFqGivaro(int exp ,ring (*)) -cdef number *sa2si_GFqNTLGF2E(FFgf2eE elem, ring *_ring) -cdef number *sa2si_GFq_generic(object vector, ring *_ring) -cdef number *sa2si_ZZmod(IntegerMod_abstract d, ring *_ring) +cdef number *sa2si_GFqGivaro(int exp ,ring (*)) noexcept +cdef number *sa2si_GFqNTLGF2E(FFgf2eE elem, ring *_ring) noexcept +cdef number *sa2si_GFq_generic(object vector, ring *_ring) noexcept +cdef number *sa2si_ZZmod(IntegerMod_abstract d, ring *_ring) noexcept -cdef number *sa2si_NF(object element, ring *_ring) +cdef number *sa2si_NF(object element, ring *_ring) noexcept # dispatches to all the above. -cdef number *sa2si(Element elem, ring * _ring) +cdef number *sa2si(Element elem, ring * _ring) noexcept # ============== # Initialisation @@ -60,4 +60,4 @@ cdef number *sa2si(Element elem, ring * _ring) cdef int overflow_check(unsigned long e, ring *_ring) except -1 -cdef init_libsingular() +cdef init_libsingular() noexcept diff --git a/src/sage/libs/singular/singular.pyx b/src/sage/libs/singular/singular.pyx index f357ce611c9..63a6e9b332f 100644 --- a/src/sage/libs/singular/singular.pyx +++ b/src/sage/libs/singular/singular.pyx @@ -56,7 +56,7 @@ ctypedef struct fraction "fractionObject": _saved_options = (int(0),0,0) -cdef Rational si2sa_QQ(number *n, number **nn, ring *_ring): +cdef Rational si2sa_QQ(number *n, number **nn, ring *_ring) noexcept: """ Create a sage rational number from a singular one. @@ -128,7 +128,7 @@ cdef Rational si2sa_QQ(number *n, number **nn, ring *_ring): mpq_clear(_z) return z -cdef Integer si2sa_ZZ(number *n, ring *_ring): +cdef Integer si2sa_ZZ(number *n, ring *_ring) noexcept: """ Create a sage integer number from a singular one. @@ -163,7 +163,7 @@ cdef Integer si2sa_ZZ(number *n, ring *_ring): z.set_from_mpz(n) return z -cdef FFgivE si2sa_GFqGivaro(number *n, ring *_ring, Cache_givaro cache): +cdef FFgivE si2sa_GFqGivaro(number *n, ring *_ring, Cache_givaro cache) noexcept: """ Create a sage element of a small finite field from a singular one. @@ -218,7 +218,7 @@ cdef FFgivE si2sa_GFqGivaro(number *n, ring *_ring, Cache_givaro cache): z = pNext(z) return (cache._zero_element)._new_c(ret) -cdef FFgf2eE si2sa_GFqNTLGF2E(number *n, ring *_ring, Cache_ntl_gf2e cache): +cdef FFgf2eE si2sa_GFqNTLGF2E(number *n, ring *_ring, Cache_ntl_gf2e cache) noexcept: """ Create a sage element of a finite field of characteristic 2 from a singular one. @@ -270,7 +270,7 @@ cdef FFgf2eE si2sa_GFqNTLGF2E(number *n, ring *_ring, Cache_ntl_gf2e cache): z = pNext(z) return ret -cdef object si2sa_GFq_generic(number *n, ring *_ring, object base): +cdef object si2sa_GFq_generic(number *n, ring *_ring, object base) noexcept: """ Create a sage element of a generic finite field from a singular one. @@ -332,7 +332,7 @@ cdef object si2sa_GFq_generic(number *n, ring *_ring, object base): z = pNext(z) return ret -cdef object si2sa_transext_QQ(number *n, ring *_ring, object base): +cdef object si2sa_transext_QQ(number *n, ring *_ring, object base) noexcept: """ Create a sage element of a transcendental extension of ``QQ`` from a singular one. @@ -421,7 +421,7 @@ cdef object si2sa_transext_QQ(number *n, ring *_ring, object base): return snumer/sdenom -cdef object si2sa_transext_FF(number *n, ring *_ring, object base): +cdef object si2sa_transext_FF(number *n, ring *_ring, object base) noexcept: """ Create a sage element of a transcendental extension of a prime field from a singular one. @@ -504,7 +504,7 @@ cdef object si2sa_transext_FF(number *n, ring *_ring, object base): return snumer/sdenom -cdef object si2sa_NF(number *n, ring *_ring, object base): +cdef object si2sa_NF(number *n, ring *_ring, object base) noexcept: """ Create a sage element of a number field from a singular one. @@ -570,7 +570,7 @@ cdef object si2sa_NF(number *n, ring *_ring, object base): z = pNext(z) return base(ret) -cdef inline object si2sa_ZZmod(number *n, ring *_ring, object base): +cdef inline object si2sa_ZZmod(number *n, ring *_ring, object base) noexcept: """ Create a sage element of a ring of integers modulo n from a singular one. @@ -632,7 +632,7 @@ cdef inline object si2sa_ZZmod(number *n, ring *_ring, object base): return base(_ring.cf.cfInt(n,_ring.cf)) -cdef list singular_monomial_exponents(poly *p, ring *r): +cdef list singular_monomial_exponents(poly *p, ring *r) noexcept: r""" Return the list of exponents of monomial ``p``. """ @@ -643,7 +643,7 @@ cdef list singular_monomial_exponents(poly *p, ring *r): ml[v-1] = p_GetExp(p, v, r) return ml -cpdef list si2sa_resolution(Resolution res): +cpdef list si2sa_resolution(Resolution res) noexcept: r""" Pull the data from Singular resolution ``res`` to construct a Sage resolution. @@ -760,7 +760,7 @@ cpdef list si2sa_resolution(Resolution res): return res_mats -cpdef tuple si2sa_resolution_graded(Resolution res, tuple degrees): +cpdef tuple si2sa_resolution_graded(Resolution res, tuple degrees) noexcept: """ Pull the data from Singular resolution ``res`` to construct a Sage resolution. @@ -898,7 +898,7 @@ cpdef tuple si2sa_resolution_graded(Resolution res, tuple degrees): return (res_mats, res_degs) -cdef number *sa2si_QQ(Rational r, ring *_ring): +cdef number *sa2si_QQ(Rational r, ring *_ring) noexcept: """ Create a singular number from a sage rational. @@ -928,7 +928,7 @@ cdef number *sa2si_QQ(Rational r, ring *_ring): if _ring != currRing: rChangeCurrRing(_ring) return nlInit2gmp( mpq_numref(r.value), mpq_denref(r.value),_ring.cf ) -cdef number *sa2si_GFqGivaro(int quo, ring *_ring): +cdef number *sa2si_GFqGivaro(int quo, ring *_ring) noexcept: """ Create a singular number in a small finite field. @@ -995,7 +995,7 @@ cdef number *sa2si_GFqGivaro(int quo, ring *_ring): _ring.cf.cfDelete(&a, _ring.cf) return n1 -cdef number *sa2si_GFqNTLGF2E(FFgf2eE elem, ring *_ring): +cdef number *sa2si_GFqNTLGF2E(FFgf2eE elem, ring *_ring) noexcept: """ Create a singular number from a sage element of a finite field of characteristic 2. @@ -1061,7 +1061,7 @@ cdef number *sa2si_GFqNTLGF2E(FFgf2eE elem, ring *_ring): return n1 -cdef number *sa2si_GFq_generic(object elem, ring *_ring): +cdef number *sa2si_GFq_generic(object elem, ring *_ring) noexcept: """ Create a singular number from a sage element of a generic finite field. @@ -1126,7 +1126,7 @@ cdef number *sa2si_GFq_generic(object elem, ring *_ring): return n1 -cdef number *sa2si_transext_QQ(object elem, ring *_ring): +cdef number *sa2si_transext_QQ(object elem, ring *_ring) noexcept: """ Create a singular number from a sage element of a transcendental extension of the rationals. @@ -1276,7 +1276,7 @@ cdef number *sa2si_transext_QQ(object elem, ring *_ring): return n1 -cdef number *sa2si_transext_FF(object elem, ring *_ring): +cdef number *sa2si_transext_FF(object elem, ring *_ring) noexcept: """ Create a singular number from a sage element of a transcendental extension of a prime field. @@ -1377,7 +1377,7 @@ cdef number *sa2si_transext_FF(object elem, ring *_ring): return n1 -cdef number *sa2si_NF(object elem, ring *_ring): +cdef number *sa2si_NF(object elem, ring *_ring) noexcept: """ Create a singular number from a sage element of a number field. @@ -1469,7 +1469,7 @@ cdef number *sa2si_NF(object elem, ring *_ring): return n1 -cdef number *sa2si_ZZ(Integer d, ring *_ring): +cdef number *sa2si_ZZ(Integer d, ring *_ring) noexcept: """ Create a singular number from a sage Integer. @@ -1500,7 +1500,7 @@ cdef number *sa2si_ZZ(Integer d, ring *_ring): mpz_set(n, d.value) return n -cdef inline number *sa2si_ZZmod(IntegerMod_abstract d, ring *_ring): +cdef inline number *sa2si_ZZmod(IntegerMod_abstract d, ring *_ring) noexcept: """ Create a singular number from a sage element of a IntegerModRing. @@ -1582,7 +1582,7 @@ cdef inline number *sa2si_ZZmod(IntegerMod_abstract d, ring *_ring): else: raise ValueError -cdef object si2sa(number *n, ring *_ring, object base): +cdef object si2sa(number *n, ring *_ring, object base) noexcept: r""" Create a sage number from a singular one @@ -1633,7 +1633,7 @@ cdef object si2sa(number *n, ring *_ring, object base): else: raise ValueError("cannot convert from SINGULAR number") -cdef number *sa2si(Element elem, ring * _ring): +cdef number *sa2si(Element elem, ring * _ring) noexcept: r""" Create a singular number from a sage one. @@ -1681,7 +1681,7 @@ cdef number *sa2si(Element elem, ring * _ring): raise ValueError("cannot convert to SINGULAR number") -cdef object si2sa_intvec(intvec *v): +cdef object si2sa_intvec(intvec *v) noexcept: r""" create a sage tuple from a singular vector of integers @@ -1744,7 +1744,7 @@ cdef int overflow_check(unsigned long e, ring *_ring) except -1: if unlikely(e > _ring.bitmask): raise OverflowError("exponent overflow (%d)"%(e)) -cdef init_libsingular(): +cdef init_libsingular() noexcept: """ This initializes the SINGULAR library. This is a hack to some extent. @@ -1812,7 +1812,7 @@ saved_PATH = os.environ["PATH"] init_libsingular() os.environ["PATH"] = saved_PATH -cdef void libsingular_error_callback(const_char_ptr s): +cdef void libsingular_error_callback(const_char_ptr s) noexcept: _s = char_to_str(s) error_messages.append(_s) diff --git a/src/sage/libs/sirocco.pyx b/src/sage/libs/sirocco.pyx index 117d714c5d5..8cca0892c55 100644 --- a/src/sage/libs/sirocco.pyx +++ b/src/sage/libs/sirocco.pyx @@ -27,7 +27,7 @@ cdef extern from "sirocco.h": double* homotopyPath_comps(int degree, double *_coef, double _y0R, double _y0I, int nothercomps, int *degreescomps, double *_coefscomps) -cpdef list[list] contpath_mp(int deg, list values, RealNumber y0r, RealNumber y0i, int prec): +cpdef list[list] contpath_mp(int deg, list values, RealNumber y0r, RealNumber y0i, int prec) noexcept: """ Mimics :func:`contpath`, but with the following differences: @@ -88,7 +88,7 @@ cpdef list[list] contpath_mp(int deg, list values, RealNumber y0r, RealNumber y0 free(rop) return l -cpdef list[list] contpath_mp_comps(int deg, list values, RealNumber y0r, RealNumber y0i, int prec, list otherdegs, list othercoefs): +cpdef list[list] contpath_mp_comps(int deg, list values, RealNumber y0r, RealNumber y0i, int prec, list otherdegs, list othercoefs) noexcept: """ Mimics :func:`contpath`, but with the following differences: @@ -167,7 +167,7 @@ cpdef list[list] contpath_mp_comps(int deg, list values, RealNumber y0r, RealNum return l -cpdef list[list] contpath(int deg, list values, double y0r, double y0i): +cpdef list[list] contpath(int deg, list values, double y0r, double y0i) noexcept: """ INPUT: @@ -222,7 +222,7 @@ cpdef list[list] contpath(int deg, list values, double y0r, double y0i): free(c_values) return l -cpdef list[list] contpath_comps(int deg, list values, double y0r, double y0i, list otherdegrees, list othercoefs): +cpdef list[list] contpath_comps(int deg, list values, double y0r, double y0i, list otherdegrees, list othercoefs) noexcept: """ INPUT: diff --git a/src/sage/libs/symmetrica/sb.pxi b/src/sage/libs/symmetrica/sb.pxi index b884d33dafd..31faf7e3d96 100644 --- a/src/sage/libs/symmetrica/sb.pxi +++ b/src/sage/libs/symmetrica/sb.pxi @@ -12,7 +12,7 @@ cdef extern from 'symmetrica/def.h': INT mult_schubert_polynom(OP a,OP b,OP c) -cdef object _check_schubert(object a, OP ca): +cdef object _check_schubert(object a, OP ca) noexcept: if a in Permutations(): if isinstance(a, builtinlist): a = Permutation(a) diff --git a/src/sage/libs/symmetrica/symmetrica.pxi b/src/sage/libs/symmetrica/symmetrica.pxi index 95f9e52fbda..60c3ec23070 100644 --- a/src/sage/libs/symmetrica/symmetrica.pxi +++ b/src/sage/libs/symmetrica/symmetrica.pxi @@ -385,7 +385,7 @@ cdef object two, fifteen, thirty, zero, sage_maxint cdef int maxint = 2147483647 -cdef void late_import(): +cdef void late_import() noexcept: global matrix_constructor, \ Integer, \ Tableau, \ @@ -467,7 +467,7 @@ cdef void late_import(): sage_maxint = Integer(maxint) ########################################## -cdef object _py(OP a): +cdef object _py(OP a) noexcept: cdef OBJECTKIND objk objk = s_o_k(a) if objk == INTEGER: @@ -569,7 +569,7 @@ cdef int _op_int(object x, OP a) except -1: M_I_I(x, a) return 0 -cdef object _py_int(OP a): +cdef object _py_int(OP a) noexcept: late_import() return Integer(S_I_I(a)) @@ -597,7 +597,7 @@ cdef int _op_longint(object x, OP a) except -1: freeall(op_maxint_long) return 0 -cdef object _py_longint(OP a): +cdef object _py_longint(OP a) noexcept: late_import() cdef longint *x = S_O_S(a).ob_longint cdef loc *l = x.floc @@ -620,7 +620,7 @@ cdef object _py_longint(OP a): ########### #Fractions# ########### -cdef object _py_fraction(OP a): +cdef object _py_fraction(OP a) noexcept: return _py(S_B_O(a))/_py(S_B_U(a)) cdef int _op_fraction(object f, OP a) except -1: @@ -632,14 +632,14 @@ cdef int _op_fraction(object f, OP a) except -1: ######### #Vectors# ######### -cdef object _py_vector(OP a): +cdef object _py_vector(OP a) noexcept: cdef INT i res = [] for i from 0 <= i < s_v_li(a): res.append( _py(s_v_i(a, i))) return res -cdef void* _op_il_vector(object l, OP a): +cdef void* _op_il_vector(object l, OP a) noexcept: cdef INT length, i length = len(l) @@ -650,7 +650,7 @@ cdef void* _op_il_vector(object l, OP a): ######### #Numbers# ######### -cdef object _py_sq_radical(OP a): +cdef object _py_sq_radical(OP a) noexcept: late_import() cdef OP ptr @@ -674,7 +674,7 @@ cdef object _py_sq_radical(OP a): ############ #Partitions# ############ -cdef void* _op_partition(object p, OP a): +cdef void* _op_partition(object p, OP a) noexcept: cdef int n, i, j if not EMPTYP(a): @@ -689,7 +689,7 @@ cdef void* _op_partition(object p, OP a): _op_integer(p[i], S_PA_I(a,j)) j = j + 1 -cdef object _py_partition(OP a): +cdef object _py_partition(OP a) noexcept: cdef INT n, i late_import() res = [] @@ -701,7 +701,7 @@ cdef object _py_partition(OP a): ################ #Skew Partition# ################ -cdef void* _op_skew_partition(object p, OP a): +cdef void* _op_skew_partition(object p, OP a) noexcept: cdef OP gross, klein gross = callocobject() klein = callocobject() @@ -709,14 +709,14 @@ cdef void* _op_skew_partition(object p, OP a): _op_partition(p[1], klein) b_gk_spa(gross, klein, a) -cdef object _py_skew_partition(OP a): +cdef object _py_skew_partition(OP a) noexcept: late_import() return SkewPartition( [ _py_partition(s_spa_g(a)), _py_partition(s_spa_k(a)) ] ) ############## #Permutations# ############## -cdef void* _op_permutation(object p, OP a): +cdef void* _op_permutation(object p, OP a) noexcept: cdef int n, i, j if not EMPTYP(a): @@ -727,7 +727,7 @@ cdef void* _op_permutation(object p, OP a): for i from 0 <= i < n: _op_integer(p[i], s_p_i(a,i)) -cdef object _py_permutation(OP a): +cdef object _py_permutation(OP a) noexcept: late_import() cdef INT n, i res = [] @@ -743,7 +743,7 @@ cdef object _py_permutation(OP a): ####### #Lists# ####### -cdef object _py_list(OP a): +cdef object _py_list(OP a) noexcept: cdef OP x x = a res = [] @@ -761,7 +761,7 @@ cdef object _py_list(OP a): ############# #Polynomials# ############# -cdef object _py_polynom(OP a): +cdef object _py_polynom(OP a) noexcept: late_import() cdef int maxneeded = 0, i = 0 cdef OP pointer = a @@ -792,7 +792,7 @@ cdef object _py_polynom(OP a): return P(d) -cdef object _py_polynom_alphabet(OP a, object alphabet, object length): +cdef object _py_polynom_alphabet(OP a, object alphabet, object length) noexcept: """ Converts a symmetrica multivariate polynomial a to a Sage multivariate polynomials. Alphabet specifies the names of the variables which are @@ -828,7 +828,7 @@ cdef object _py_polynom_alphabet(OP a, object alphabet, object length): pointer = s_po_n(pointer) return res -cdef object _op_polynom(object d, OP res): +cdef object _op_polynom(object d, OP res) noexcept: late_import() poly_ring = d.parent() @@ -865,7 +865,7 @@ cdef object _op_polynom(object d, OP res): ####################################### #Schur symmetric functions and friends# ####################################### -cdef object _py_schur(OP a): +cdef object _py_schur(OP a) noexcept: late_import() z_elt = _py_schur_general(a) if len(z_elt) == 0: @@ -879,10 +879,10 @@ cdef object _py_schur(OP a): z._monomial_coefficients = z_elt return z -cdef void* _op_schur(object d, OP res): +cdef void* _op_schur(object d, OP res) noexcept: _op_schur_general(d, res) -cdef object _py_monomial(OP a): #Monomial symmetric functions +cdef object _py_monomial(OP a) noexcept: #Monomial symmetric functions late_import() z_elt = _py_schur_general(a) if len(z_elt) == 0: @@ -895,14 +895,14 @@ cdef object _py_monomial(OP a): #Monomial symmetric functions z._monomial_coefficients = z_elt return z -cdef void* _op_monomial(object d, OP res): #Monomial symmetric functions +cdef void* _op_monomial(object d, OP res) noexcept: #Monomial symmetric functions cdef OP pointer = res _op_schur_general(d, res) while pointer != NULL: c_o_k(pointer, MONOMIAL) pointer = s_s_n(pointer) -cdef object _py_powsym(OP a): #Power-sum symmetric functions +cdef object _py_powsym(OP a) noexcept: #Power-sum symmetric functions late_import() z_elt = _py_schur_general(a) if len(z_elt) == 0: @@ -915,7 +915,7 @@ cdef object _py_powsym(OP a): #Power-sum symmetric functions z._monomial_coefficients = z_elt return z -cdef void* _op_powsym(object d, OP res): #Power-sum symmetric functions +cdef void* _op_powsym(object d, OP res) noexcept: #Power-sum symmetric functions cdef OP pointer = res _op_schur_general(d, res) while pointer != NULL: @@ -923,7 +923,7 @@ cdef void* _op_powsym(object d, OP res): #Power-sum symmetric functions pointer = s_s_n(pointer) -cdef object _py_elmsym(OP a): #Elementary symmetric functions +cdef object _py_elmsym(OP a) noexcept: #Elementary symmetric functions late_import() z_elt = _py_schur_general(a) if len(z_elt) == 0: @@ -936,7 +936,7 @@ cdef object _py_elmsym(OP a): #Elementary symmetric functions z._monomial_coefficients = z_elt return z -cdef void* _op_elmsym(object d, OP res): #Elementary symmetric functions +cdef void* _op_elmsym(object d, OP res) noexcept: #Elementary symmetric functions cdef OP pointer = res _op_schur_general(d, res) while pointer != NULL: @@ -944,7 +944,7 @@ cdef void* _op_elmsym(object d, OP res): #Elementary symmetric functions pointer = s_s_n(pointer) -cdef object _py_homsym(OP a): #Homogenous symmetric functions +cdef object _py_homsym(OP a) noexcept: #Homogenous symmetric functions late_import() z_elt = _py_schur_general(a) if len(z_elt) == 0: @@ -957,7 +957,7 @@ cdef object _py_homsym(OP a): #Homogenous symmetric functions z._monomial_coefficients = z_elt return z -cdef void* _op_homsym(object d, OP res): #Homogenous symmetric functions +cdef void* _op_homsym(object d, OP res) noexcept: #Homogenous symmetric functions cdef OP pointer = res _op_schur_general(d, res) while pointer != NULL: @@ -965,7 +965,7 @@ cdef void* _op_homsym(object d, OP res): #Homogenous symmetric functions pointer = s_s_n(pointer) -cdef object _py_schur_general(OP a): +cdef object _py_schur_general(OP a) noexcept: cdef OP pointer = a d = {} if a == NULL: @@ -975,13 +975,13 @@ cdef object _py_schur_general(OP a): pointer = s_s_n(pointer) return d -cdef void* _op_schur_general(object d, OP res): +cdef void* _op_schur_general(object d, OP res) noexcept: if isinstance(d, dict): _op_schur_general_dict(d, res) else: _op_schur_general_sf(d, res) -cdef void* _op_schur_general_sf(object f, OP res): +cdef void* _op_schur_general_sf(object f, OP res) noexcept: late_import() base_ring = f.parent().base_ring() if not ( base_ring is QQ or base_ring is ZZ ): @@ -989,7 +989,7 @@ cdef void* _op_schur_general_sf(object f, OP res): _op_schur_general_dict( f.monomial_coefficients(), res) -cdef void* _op_schur_general_dict(object d, OP res): +cdef void* _op_schur_general_dict(object d, OP res) noexcept: late_import() cdef OP next @@ -1022,19 +1022,19 @@ cdef void* _op_schur_general_dict(object d, OP res): ###################### #Schubert Polynomials# ###################### -cdef void* _op_schubert_general(object d, OP res): +cdef void* _op_schubert_general(object d, OP res) noexcept: if isinstance(d, dict): _op_schubert_dict(d, res) else: _op_schubert_sp(d, res) -cdef void* _op_schubert_perm(object a, OP res): +cdef void* _op_schubert_perm(object a, OP res) noexcept: cdef OP caperm = callocobject() _op_permutation(a, caperm) m_perm_sch(caperm, res) freeall(caperm) -cdef void* _op_schubert_sp(object f, OP res): +cdef void* _op_schubert_sp(object f, OP res) noexcept: late_import() base_ring = f.parent().base_ring() if not ( base_ring is QQ or base_ring is ZZ ): @@ -1042,7 +1042,7 @@ cdef void* _op_schubert_sp(object f, OP res): _op_schubert_dict( f.monomial_coefficients(), res) -cdef void* _op_schubert_dict(object d, OP res): +cdef void* _op_schubert_dict(object d, OP res) noexcept: late_import() cdef OP next @@ -1069,7 +1069,7 @@ cdef void* _op_schubert_dict(object d, OP res): insert(next, res, NULL, NULL) -cdef object _py_schubert(OP a): +cdef object _py_schubert(OP a) noexcept: late_import() cdef OP pointer = a cdef dict z_elt = {} @@ -1096,7 +1096,7 @@ cdef object _py_schubert(OP a): ########## #Matrices# ########## -cdef object _py_matrix(OP a): +cdef object _py_matrix(OP a) noexcept: late_import() @@ -1119,7 +1119,7 @@ cdef object _py_matrix(OP a): return matrix_constructor(res) -cdef void* _op_matrix(object a, OP res): +cdef void* _op_matrix(object a, OP res) noexcept: #FIXME: only constructs integer matrices cdef INT i,j,rows, cols @@ -1136,7 +1136,7 @@ cdef void* _op_matrix(object a, OP res): ########## #Tableaux# ########## -cdef object _py_tableau(OP t): +cdef object _py_tableau(OP t) noexcept: late_import() diff --git a/src/sage/matrix/action.pyx b/src/sage/matrix/action.pyx index 5c6296a1c35..849163a511f 100644 --- a/src/sage/matrix/action.pyx +++ b/src/sage/matrix/action.pyx @@ -203,7 +203,7 @@ cdef class MatrixMatrixAction(MatrixMulAction): return MatrixSpace(base, self.G.nrows(), self.underlying_set().ncols(), sparse = self.G.is_sparse() and self.underlying_set().is_sparse()) - cpdef _act_(self, g, s): + cpdef _act_(self, g, s) noexcept: """ EXAMPLES: @@ -313,7 +313,7 @@ cdef class MatrixVectorAction(MatrixMulAction): self.underlying_set().degree())) return FreeModule(base, self.G.nrows(), sparse = self.G.is_sparse()) - cpdef _act_(self, g, s): + cpdef _act_(self, g, s) noexcept: cdef Matrix A = g cdef Vector v = s if A._parent._base is not self._codomain._base: @@ -364,7 +364,7 @@ cdef class VectorMatrixAction(MatrixMulAction): self.underlying_set().degree())) return FreeModule(base, self.G.ncols(), sparse = self.G.is_sparse()) - cpdef _act_(self, g, s): + cpdef _act_(self, g, s) noexcept: cdef Matrix A = g cdef Vector v = s if A._parent._base is not self._codomain._base: @@ -423,7 +423,7 @@ cdef class MatrixPolymapAction(MatrixMulAction): return End(self.underlying_set().domain().change_ring(base)) return Hom(self.underlying_set().domain().change_ring(base), self.underlying_set().codomain().change_ring(base)) - cpdef _act_(self, mat, f): + cpdef _act_(self, mat, f) noexcept: """ Call the action @@ -496,7 +496,7 @@ cdef class PolymapMatrixAction(MatrixMulAction): return End(self.underlying_set().domain().change_ring(base)) return Hom(self.underlying_set().domain().change_ring(base), self.underlying_set().codomain().change_ring(base)) - cpdef _act_(self, mat, f): + cpdef _act_(self, mat, f) noexcept: """ Call the action. @@ -564,7 +564,7 @@ cdef class MatrixSchemePointAction(MatrixMulAction): amb = self.underlying_set().codomain() return amb.change_ring(base)(base) - cpdef _act_(self, mat, P): + cpdef _act_(self, mat, P) noexcept: """ Action of matrices on scheme points. diff --git a/src/sage/matrix/args.pxd b/src/sage/matrix/args.pxd index 581f89b0cc5..fc26bc35914 100644 --- a/src/sage/matrix/args.pxd +++ b/src/sage/matrix/args.pxd @@ -33,7 +33,7 @@ cdef class SparseEntry: cdef public object entry -cdef inline SparseEntry make_SparseEntry(long i, long j, entry): +cdef inline SparseEntry make_SparseEntry(long i, long j, entry) noexcept: e = SparseEntry.__new__(SparseEntry) e.i = i e.j = j @@ -53,18 +53,18 @@ cdef class MatrixArgs: cdef public dict kwds # **kwds for MatrixSpace() cdef bint is_finalized - cpdef Matrix matrix(self, bint convert=?) - cpdef list list(self, bint convert=?) - cpdef dict dict(self, bint convert=?) + cpdef Matrix matrix(self, bint convert=?) noexcept + cpdef list list(self, bint convert=?) noexcept + cpdef dict dict(self, bint convert=?) noexcept - cdef inline bint ref_safe(self): + cdef inline bint ref_safe(self) noexcept: """ Can we safely return self.entries without making a copy? A refcount of 1 means that self.entries is the only reference. """ return (self.entries).ob_refcnt == 1 - cdef inline bint need_to_convert(self, x): + cdef inline bint need_to_convert(self, x) noexcept: """Is ``x`` not an element of ``self.base``?""" if not isinstance(x, Element): return True @@ -119,4 +119,4 @@ cdef class MatrixArgs: cdef int set_seq_flat(self, entries) except -1 -cpdef MatrixArgs MatrixArgs_init(space, entries) +cpdef MatrixArgs MatrixArgs_init(space, entries) noexcept diff --git a/src/sage/matrix/args.pyx b/src/sage/matrix/args.pyx index c5a121743a5..bdb6eb796dd 100644 --- a/src/sage/matrix/args.pyx +++ b/src/sage/matrix/args.pyx @@ -39,7 +39,7 @@ except ImportError: CommutativeMonoids = monoids.Monoids().Commutative() -cdef inline bint element_is_scalar(Element x): +cdef inline bint element_is_scalar(Element x) noexcept: """ Should this element be considered a scalar (as opposed to a vector)? """ @@ -606,7 +606,7 @@ cdef class MatrixArgs: self.finalize() return self.nrows * self.ncols - cpdef Matrix matrix(self, bint convert=True): + cpdef Matrix matrix(self, bint convert=True) noexcept: """ Return the entries of the matrix as a Sage Matrix. @@ -694,7 +694,7 @@ cdef class MatrixArgs: self.typ = MA_ENTRIES_MATRIX return M - cpdef list list(self, bint convert=True): + cpdef list list(self, bint convert=True) noexcept: """ Return the entries of the matrix as a flat list of scalars. @@ -761,7 +761,7 @@ cdef class MatrixArgs: self.typ = MA_ENTRIES_SEQ_FLAT return L - cpdef dict dict(self, bint convert=True): + cpdef dict dict(self, bint convert=True) noexcept: """ Return the entries of the matrix as a dict. The keys of this dict are the non-zero positions ``(i,j)``. The corresponding @@ -1360,7 +1360,7 @@ cdef class MatrixArgs: return MA_ENTRIES_SEQ_SEQ -cpdef MatrixArgs MatrixArgs_init(space, entries): +cpdef MatrixArgs MatrixArgs_init(space, entries) noexcept: """ Construct a :class:`MatrixArgs` object from a matrix space and entries. This is the typical use in a matrix constructor. diff --git a/src/sage/matrix/compute_J_ideal.py b/src/sage/matrix/compute_J_ideal.py index 3055f283a78..1983e16c0f5 100644 --- a/src/sage/matrix/compute_J_ideal.py +++ b/src/sage/matrix/compute_J_ideal.py @@ -334,7 +334,7 @@ def __init__(self, B): """ from sage.rings.polynomial.polynomial_ring import polygen - super(ComputeMinimalPolynomials, self).__init__() + super().__init__() if not B.is_square(): raise TypeError("square matrix required") diff --git a/src/sage/matrix/matrix0.pxd b/src/sage/matrix/matrix0.pxd index fe320458130..d2276ef486d 100644 --- a/src/sage/matrix/matrix0.pxd +++ b/src/sage/matrix/matrix0.pxd @@ -21,8 +21,8 @@ cdef class Matrix(sage.structure.element.Matrix): cdef public object _base_ring cdef bint _is_immutable - cpdef _add_(self, other) - cpdef _sub_(self, other) + cpdef _add_(self, other) noexcept + cpdef _sub_(self, other) noexcept cdef bint _will_use_strassen(self, Matrix right) except -2 cdef bint _will_use_strassen_echelon(self) except -2 @@ -31,37 +31,37 @@ cdef class Matrix(sage.structure.element.Matrix): # Implementation of hash function cdef long _hash_(self) except -1 - cdef void get_hash_constants(self, long C[5]) + cdef void get_hash_constants(self, long C[5]) noexcept # Cache cdef public object _cache cdef long hash # cached hash value - cdef void clear_cache(self) - cdef fetch(self, key) - cdef cache(self, key, x) + cdef void clear_cache(self) noexcept + cdef fetch(self, key) noexcept + cdef cache(self, key, x) noexcept # Mutability and bounds checking - cdef check_bounds(self, Py_ssize_t i, Py_ssize_t j) - cdef check_mutability(self) - cdef check_bounds_and_mutability(self, Py_ssize_t i, Py_ssize_t j) + cdef check_bounds(self, Py_ssize_t i, Py_ssize_t j) noexcept + cdef check_mutability(self) noexcept + cdef check_bounds_and_mutability(self, Py_ssize_t i, Py_ssize_t j) noexcept # Unsafe entry access - cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, object x) - cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) - cdef _coerce_element(self, x) + cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, object x) noexcept + cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept + cdef _coerce_element(self, x) noexcept cdef bint get_is_zero_unsafe(self, Py_ssize_t i, Py_ssize_t j) except -1 # Row and column operations - cdef check_row_bounds(self, Py_ssize_t r1, Py_ssize_t r2) - cdef check_column_bounds(self, Py_ssize_t c1, Py_ssize_t c2) - cdef check_row_bounds_and_mutability(self, Py_ssize_t r1, Py_ssize_t r2) - cdef check_column_bounds_and_mutability(self, Py_ssize_t c1, Py_ssize_t c2) - cdef swap_rows_c(self, Py_ssize_t r1, Py_ssize_t r2) - cdef swap_columns_c(self, Py_ssize_t c1, Py_ssize_t c2) - cdef add_multiple_of_row_c(self, Py_ssize_t i, Py_ssize_t j, s, Py_ssize_t col_start) - cdef add_multiple_of_column_c(self, Py_ssize_t i, Py_ssize_t j, s, Py_ssize_t row_start) - cdef rescale_row_c(self, Py_ssize_t i, s, Py_ssize_t start_col) - cdef rescale_col_c(self, Py_ssize_t i, s, Py_ssize_t start_row) + cdef check_row_bounds(self, Py_ssize_t r1, Py_ssize_t r2) noexcept + cdef check_column_bounds(self, Py_ssize_t c1, Py_ssize_t c2) noexcept + cdef check_row_bounds_and_mutability(self, Py_ssize_t r1, Py_ssize_t r2) noexcept + cdef check_column_bounds_and_mutability(self, Py_ssize_t c1, Py_ssize_t c2) noexcept + cdef swap_rows_c(self, Py_ssize_t r1, Py_ssize_t r2) noexcept + cdef swap_columns_c(self, Py_ssize_t c1, Py_ssize_t c2) noexcept + cdef add_multiple_of_row_c(self, Py_ssize_t i, Py_ssize_t j, s, Py_ssize_t col_start) noexcept + cdef add_multiple_of_column_c(self, Py_ssize_t i, Py_ssize_t j, s, Py_ssize_t row_start) noexcept + cdef rescale_row_c(self, Py_ssize_t i, s, Py_ssize_t start_col) noexcept + cdef rescale_col_c(self, Py_ssize_t i, s, Py_ssize_t start_row) noexcept # Helper function for inverse of sparse matrices - cdef build_inverse_from_augmented_sparse(self, A) + cdef build_inverse_from_augmented_sparse(self, A) noexcept diff --git a/src/sage/matrix/matrix0.pyx b/src/sage/matrix/matrix0.pyx index dfb3d0090b2..d7a0487e6cd 100644 --- a/src/sage/matrix/matrix0.pyx +++ b/src/sage/matrix/matrix0.pyx @@ -334,14 +334,14 @@ cdef class Matrix(sage.structure.element.Matrix): """ self.clear_cache() - cdef void clear_cache(self): + cdef void clear_cache(self) noexcept: """ Clear the properties cache. """ self._cache = None self.hash = -1 - cdef fetch(self, key): + cdef fetch(self, key) noexcept: """ Try to get an element from the cache; if there isn't anything there, return None. @@ -353,7 +353,7 @@ cdef class Matrix(sage.structure.element.Matrix): except KeyError: return None - cdef cache(self, key, x): + cdef cache(self, key, x) noexcept: """ Record x in the cache with given key. """ @@ -380,7 +380,7 @@ cdef class Matrix(sage.structure.element.Matrix): # Mutability and bounds checking ########################################################### - cdef check_bounds(self, Py_ssize_t i, Py_ssize_t j): + cdef check_bounds(self, Py_ssize_t i, Py_ssize_t j) noexcept: """ This function gets called when you're about to access the i,j entry of this matrix. If i, j are out of range, an IndexError is @@ -389,7 +389,7 @@ cdef class Matrix(sage.structure.element.Matrix): if i<0 or i >= self._nrows or j<0 or j >= self._ncols: raise IndexError("matrix index out of range") - cdef check_mutability(self): + cdef check_mutability(self) noexcept: """ This function gets called when you're about to change this matrix. @@ -403,7 +403,7 @@ cdef class Matrix(sage.structure.element.Matrix): else: self._cache = None - cdef check_bounds_and_mutability(self, Py_ssize_t i, Py_ssize_t j): + cdef check_bounds_and_mutability(self, Py_ssize_t i, Py_ssize_t j) noexcept: """ This function gets called when you're about to set the i,j entry of this matrix. If i or j is out of range, an :class:`IndexError` @@ -516,7 +516,7 @@ cdef class Matrix(sage.structure.element.Matrix): # Entry access # The first two must be overloaded in the derived class ########################################################### - cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, object x): + cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, object x) noexcept: """ Set entry quickly without doing any bounds checking. Calling this with invalid arguments is allowed to produce a segmentation fault. @@ -526,7 +526,7 @@ cdef class Matrix(sage.structure.element.Matrix): """ raise NotImplementedError("this must be defined in the derived class (type=%s)" % type(self)) - cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j): + cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept: """ Entry access, but fast since it might be without bounds checking. @@ -1562,7 +1562,7 @@ cdef class Matrix(sage.structure.element.Matrix): - cdef _coerce_element(self, x): + cdef _coerce_element(self, x) noexcept: """ Return coercion of x into the base ring of self. """ @@ -2431,11 +2431,11 @@ cdef class Matrix(sage.structure.element.Matrix): # involve multiplication outside base ring, including # with_ versions of these methods for this situation ################################################### - cdef check_row_bounds(self, Py_ssize_t r1, Py_ssize_t r2): + cdef check_row_bounds(self, Py_ssize_t r1, Py_ssize_t r2) noexcept: if r1 < 0 or r1 >= self._nrows or r2 < 0 or r2 >= self._nrows: raise IndexError("matrix row index out of range") - cdef check_row_bounds_and_mutability(self, Py_ssize_t r1, Py_ssize_t r2): + cdef check_row_bounds_and_mutability(self, Py_ssize_t r1, Py_ssize_t r2) noexcept: if self._is_immutable: raise ValueError("Matrix is immutable; please change a copy instead (i.e., use copy(M) to change a copy of M).") else: @@ -2443,11 +2443,11 @@ cdef class Matrix(sage.structure.element.Matrix): if r1 < 0 or r1 >= self._nrows or r2 < 0 or r2 >= self._nrows: raise IndexError("matrix row index out of range") - cdef check_column_bounds(self, Py_ssize_t c1, Py_ssize_t c2): + cdef check_column_bounds(self, Py_ssize_t c1, Py_ssize_t c2) noexcept: if c1 < 0 or c1 >= self._ncols or c2 < 0 or c2 >= self._ncols: raise IndexError("matrix column index out of range") - cdef check_column_bounds_and_mutability(self, Py_ssize_t c1, Py_ssize_t c2): + cdef check_column_bounds_and_mutability(self, Py_ssize_t c1, Py_ssize_t c2) noexcept: if self._is_immutable: raise ValueError("Matrix is immutable; please change a copy instead (i.e., use copy(M) to change a copy of M).") else: @@ -2633,7 +2633,7 @@ cdef class Matrix(sage.structure.element.Matrix): temp.swap_columns_c(cycle[0], elt) return temp - cdef swap_columns_c(self, Py_ssize_t c1, Py_ssize_t c2): + cdef swap_columns_c(self, Py_ssize_t c1, Py_ssize_t c2) noexcept: cdef Py_ssize_t r for r from 0 <= r < self._nrows: a = self.get_unsafe(r, c2) @@ -2815,7 +2815,7 @@ cdef class Matrix(sage.structure.element.Matrix): temp.swap_rows_c(cycle[0], elt) return temp - cdef swap_rows_c(self, Py_ssize_t r1, Py_ssize_t r2): + cdef swap_rows_c(self, Py_ssize_t r1, Py_ssize_t r2) noexcept: cdef Py_ssize_t c for c from 0 <= c < self._ncols: a = self.get_unsafe(r2, c) @@ -2950,7 +2950,7 @@ cdef class Matrix(sage.structure.element.Matrix): except TypeError: raise TypeError('Multiplying row by %s element cannot be done over %s, use change_ring or with_added_multiple_of_row instead.' % (s.parent(), self.base_ring())) - cdef add_multiple_of_row_c(self, Py_ssize_t i, Py_ssize_t j, s, Py_ssize_t start_col): + cdef add_multiple_of_row_c(self, Py_ssize_t i, Py_ssize_t j, s, Py_ssize_t start_col) noexcept: cdef Py_ssize_t c for c from start_col <= c < self._ncols: self.set_unsafe(i, c, self.get_unsafe(i, c) + s*self.get_unsafe(j, c)) @@ -3035,7 +3035,7 @@ cdef class Matrix(sage.structure.element.Matrix): except TypeError: raise TypeError('Multiplying column by %s element cannot be done over %s, use change_ring or with_added_multiple_of_column instead.' % (s.parent(), self.base_ring())) - cdef add_multiple_of_column_c(self, Py_ssize_t i, Py_ssize_t j, s, Py_ssize_t start_row): + cdef add_multiple_of_column_c(self, Py_ssize_t i, Py_ssize_t j, s, Py_ssize_t start_row) noexcept: cdef Py_ssize_t r for r from start_row <= r < self._nrows: self.set_unsafe(r, i, self.get_unsafe(r, i) + s*self.get_unsafe(r, j)) @@ -3150,7 +3150,7 @@ cdef class Matrix(sage.structure.element.Matrix): except TypeError: raise TypeError('Rescaling row by %s element cannot be done over %s, use change_ring or with_rescaled_row instead.' % (s.parent(), self.base_ring())) - cdef rescale_row_c(self, Py_ssize_t i, s, Py_ssize_t start_col): + cdef rescale_row_c(self, Py_ssize_t i, s, Py_ssize_t start_col) noexcept: cdef Py_ssize_t j for j from start_col <= j < self._ncols: self.set_unsafe(i, j, self.get_unsafe(i, j)*s) @@ -3265,7 +3265,7 @@ cdef class Matrix(sage.structure.element.Matrix): except TypeError: raise TypeError('Rescaling column by %s element cannot be done over %s, use change_ring or with_rescaled_col instead.' % (s.parent(), self.base_ring())) - cdef rescale_col_c(self, Py_ssize_t i, s, Py_ssize_t start_row): + cdef rescale_col_c(self, Py_ssize_t i, s, Py_ssize_t start_row) noexcept: cdef Py_ssize_t j for j from start_row <= j < self._nrows: self.set_unsafe(j, i, self.get_unsafe(j, i)*s) @@ -5038,7 +5038,7 @@ cdef class Matrix(sage.structure.element.Matrix): ################################################### # Arithmetic ################################################### - cdef _vector_times_matrix_(self, Vector v): + cdef _vector_times_matrix_(self, Vector v) noexcept: r""" Return the vector times matrix product. @@ -5095,7 +5095,7 @@ cdef class Matrix(sage.structure.element.Matrix): return sum([v[i] * self.row(i, from_list=True) for i in range(self._nrows)], M(0)) - cdef _matrix_times_vector_(self, Vector v): + cdef _matrix_times_vector_(self, Vector v) noexcept: """ EXAMPLES:: @@ -5206,7 +5206,7 @@ cdef class Matrix(sage.structure.element.Matrix): MS = self.matrix_space(n, m) return MS(X).transpose() - cpdef _add_(self, _right): + cpdef _add_(self, _right) noexcept: """ Add two matrices with the same parent. @@ -5230,7 +5230,7 @@ cdef class Matrix(sage.structure.element.Matrix): A.set_unsafe(i,j,self.get_unsafe(i,j)._add_(right.get_unsafe(i,j))) return A - cpdef _sub_(self, _right): + cpdef _sub_(self, _right) noexcept: """ Subtract two matrices with the same parent. @@ -5296,7 +5296,7 @@ cdef class Matrix(sage.structure.element.Matrix): """ return self.change_ring(self._base_ring.quotient_ring(p)) - cpdef _rmul_(self, Element left): + cpdef _rmul_(self, Element left) noexcept: """ EXAMPLES:: @@ -5334,7 +5334,7 @@ cdef class Matrix(sage.structure.element.Matrix): ans.set_unsafe(r, c, x * self.get_unsafe(r, c)) return ans - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: """ EXAMPLES: @@ -5378,7 +5378,7 @@ cdef class Matrix(sage.structure.element.Matrix): ans.set_unsafe(r, c, self.get_unsafe(r, c) * x) return ans - cdef sage.structure.element.Matrix _matrix_times_matrix_(self, sage.structure.element.Matrix right): + cdef sage.structure.element.Matrix _matrix_times_matrix_(self, sage.structure.element.Matrix right) noexcept: r""" Return the product of two matrices. @@ -5771,7 +5771,7 @@ cdef class Matrix(sage.structure.element.Matrix): raise ZeroDivisionError("input matrix must be nonsingular") return A.matrix_from_columns(list(range(self._ncols, 2 * self._ncols))) - cdef build_inverse_from_augmented_sparse(self, A): + cdef build_inverse_from_augmented_sparse(self, A) noexcept: # We can directly use the dict entries of A cdef Py_ssize_t i, nrows cdef dict data = A._dict() @@ -6038,7 +6038,7 @@ cdef class Matrix(sage.structure.element.Matrix): return -2 return h - cdef void get_hash_constants(self, long C[5]): + cdef void get_hash_constants(self, long C[5]) noexcept: """ Get constants for the hash algorithm. """ @@ -6074,7 +6074,7 @@ cdef class Matrix(sage.structure.element.Matrix): # C[0] = (1 - m * (m - 1)/2) * C[2] - (m - 1) * C[1] C[0] = (1 - mm) * C[2] - (m - 1) * C[1] - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Compare two matrices. diff --git a/src/sage/matrix/matrix1.pxd b/src/sage/matrix/matrix1.pxd index 28eb1ca5b84..666cd4e6240 100644 --- a/src/sage/matrix/matrix1.pxd +++ b/src/sage/matrix/matrix1.pxd @@ -1,7 +1,7 @@ from .matrix0 cimport Matrix as Matrix0 cdef class Matrix(Matrix0): - cdef _stack_impl(self, bottom) + cdef _stack_impl(self, bottom) noexcept - cpdef row_ambient_module(self, base_ring=*, sparse=*) - cpdef column_ambient_module(self, base_ring=*, sparse=*) + cpdef row_ambient_module(self, base_ring=*, sparse=*) noexcept + cpdef column_ambient_module(self, base_ring=*, sparse=*) noexcept diff --git a/src/sage/matrix/matrix1.pyx b/src/sage/matrix/matrix1.pyx index 2ee50b25b7b..14a8538a535 100644 --- a/src/sage/matrix/matrix1.pyx +++ b/src/sage/matrix/matrix1.pyx @@ -854,7 +854,7 @@ cdef class Matrix(Matrix0): ############################################################################################# # rows, columns, sparse_rows, sparse_columns, dense_rows, dense_columns, row, column ############################################################################################# - cpdef row_ambient_module(self, base_ring=None, sparse=None): + cpdef row_ambient_module(self, base_ring=None, sparse=None) noexcept: r""" Return the free module that contains the rows of the matrix. @@ -911,7 +911,7 @@ cdef class Matrix(Matrix0): deprecation(32984, 'the method _row_ambient_module is deprecated use row_ambient_module (without underscore) instead') return self.row_ambient_module(base_ring) - cpdef column_ambient_module(self, base_ring=None, sparse=None): + cpdef column_ambient_module(self, base_ring=None, sparse=None) noexcept: r""" Return the free module that contains the columns of the matrix. @@ -1747,7 +1747,7 @@ cdef class Matrix(Matrix0): Z._subdivide_on_stack(self, other) return Z - cdef _stack_impl(self, bottom): + cdef _stack_impl(self, bottom) noexcept: """ Implementation of :meth:`stack`. diff --git a/src/sage/matrix/matrix2.pxd b/src/sage/matrix/matrix2.pxd index 6f99ff58d02..ad5bf85df04 100644 --- a/src/sage/matrix/matrix2.pxd +++ b/src/sage/matrix/matrix2.pxd @@ -15,10 +15,10 @@ Generic matrices from .matrix1 cimport Matrix as Matrix1 cdef class Matrix(Matrix1): - cdef _det_by_minors(self, Py_ssize_t level) - cdef _pf_bfl(self) + cdef _det_by_minors(self, Py_ssize_t level) noexcept + cdef _pf_bfl(self) noexcept cdef bint _is_positive_definite_or_semidefinite(self, bint semi) except -1 - cdef tuple _block_ldlt(self, bint classical) - cpdef _echelon(self, str algorithm) - cpdef _echelon_in_place(self, str algorithm) - cpdef matrix_window(self, Py_ssize_t row=*, Py_ssize_t col=*, Py_ssize_t nrows=*, Py_ssize_t ncols=*, bint check=*) + cdef tuple _block_ldlt(self, bint classical) noexcept + cpdef _echelon(self, str algorithm) noexcept + cpdef _echelon_in_place(self, str algorithm) noexcept + cpdef matrix_window(self, Py_ssize_t row=*, Py_ssize_t col=*, Py_ssize_t nrows=*, Py_ssize_t ncols=*, bint check=*) noexcept diff --git a/src/sage/matrix/matrix2.pyx b/src/sage/matrix/matrix2.pyx index f63ed12ce26..8af0889927f 100644 --- a/src/sage/matrix/matrix2.pyx +++ b/src/sage/matrix/matrix2.pyx @@ -2189,7 +2189,7 @@ cdef class Matrix(Matrix1): self.cache('det', d) return d - cdef _det_by_minors(self, Py_ssize_t level): + cdef _det_by_minors(self, Py_ssize_t level) noexcept: """ Compute the determinant of the upper-left level x level submatrix of self. Does not handle degenerate cases, level MUST be >= 2 @@ -2559,7 +2559,7 @@ cdef class Matrix(Matrix1): return res - cdef _pf_bfl(self): + cdef _pf_bfl(self) noexcept: r""" Computes the Pfaffian of ``self`` using the Baer-Faddeev-LeVerrier algorithm. @@ -7944,7 +7944,7 @@ cdef class Matrix(Matrix1): else: return E - cpdef _echelon(self, str algorithm): + cpdef _echelon(self, str algorithm) noexcept: """ Return the echelon form of ``self`` using ``algorithm``. @@ -8024,7 +8024,7 @@ cdef class Matrix(Matrix1): """ return self._echelon('classical') - cpdef _echelon_in_place(self, str algorithm): + cpdef _echelon_in_place(self, str algorithm) noexcept: """ Transform ``self`` into echelon form and return the pivots of ``self``. @@ -8847,7 +8847,7 @@ cdef class Matrix(Matrix1): cpdef matrix_window(self, Py_ssize_t row=0, Py_ssize_t col=0, Py_ssize_t nrows=-1, Py_ssize_t ncols=-1, - bint check=1): + bint check=1) noexcept: """ Return the requested matrix window. @@ -14041,7 +14041,7 @@ cdef class Matrix(Matrix1): raise ValueError(msg.format(d)) return L, vector(L.base_ring(), d) - cdef tuple _block_ldlt(self, bint classical): + cdef tuple _block_ldlt(self, bint classical) noexcept: r""" Perform a user-unfriendly block-`LDL^{T}` factorization of the Hermitian matrix `A` diff --git a/src/sage/matrix/matrix_cdv.pxd b/src/sage/matrix/matrix_cdv.pxd index f7684da49f2..2deb72f25a2 100644 --- a/src/sage/matrix/matrix_cdv.pxd +++ b/src/sage/matrix/matrix_cdv.pxd @@ -1,3 +1,3 @@ from sage.matrix.matrix_generic_dense cimport Matrix_generic_dense -cpdef hessenbergize_cdvf(Matrix_generic_dense) +cpdef hessenbergize_cdvf(Matrix_generic_dense) noexcept diff --git a/src/sage/matrix/matrix_cdv.pyx b/src/sage/matrix/matrix_cdv.pyx index dfbdb053328..6faf51eb6ad 100644 --- a/src/sage/matrix/matrix_cdv.pyx +++ b/src/sage/matrix/matrix_cdv.pyx @@ -20,7 +20,7 @@ from sage.rings.infinity import Infinity # We assume that H is square -cpdef hessenbergize_cdvf(Matrix_generic_dense H): +cpdef hessenbergize_cdvf(Matrix_generic_dense H) noexcept: r""" Replace `H` with an Hessenberg form of it. diff --git a/src/sage/matrix/matrix_complex_ball_dense.pxd b/src/sage/matrix/matrix_complex_ball_dense.pxd index fab9172f8b2..622925a0ee9 100644 --- a/src/sage/matrix/matrix_complex_ball_dense.pxd +++ b/src/sage/matrix/matrix_complex_ball_dense.pxd @@ -3,11 +3,11 @@ from .matrix_dense cimport Matrix_dense from sage.matrix.matrix_generic_dense cimport Matrix_generic_dense from sage.structure.parent cimport Parent -cdef void matrix_to_acb_mat(acb_mat_t target, source) +cdef void matrix_to_acb_mat(acb_mat_t target, source) noexcept cdef Matrix_generic_dense acb_mat_to_matrix( - acb_mat_t source, Parent CIF) + acb_mat_t source, Parent CIF) noexcept cdef class Matrix_complex_ball_dense(Matrix_dense): cdef acb_mat_t value - cdef Matrix_complex_ball_dense _new(self, Py_ssize_t nrows, Py_ssize_t ncols) - cpdef _pow_int(self, n) + cdef Matrix_complex_ball_dense _new(self, Py_ssize_t nrows, Py_ssize_t ncols) noexcept + cpdef _pow_int(self, n) noexcept diff --git a/src/sage/matrix/matrix_complex_ball_dense.pyx b/src/sage/matrix/matrix_complex_ball_dense.pyx index 3f56772a663..22366b5f1f2 100644 --- a/src/sage/matrix/matrix_complex_ball_dense.pyx +++ b/src/sage/matrix/matrix_complex_ball_dense.pyx @@ -56,7 +56,7 @@ from sage.misc.superseded import experimental from sage.rings.polynomial import polynomial_ring_constructor -cdef void matrix_to_acb_mat(acb_mat_t target, source): +cdef void matrix_to_acb_mat(acb_mat_t target, source) noexcept: """ Convert a matrix containing :class:`ComplexIntervalFieldElement` to an ``acb_mat_t``. @@ -80,14 +80,14 @@ cdef void matrix_to_acb_mat(acb_mat_t target, source): ComplexIntervalFieldElement_to_acb(acb_mat_entry(target, r, c), source[r][c]) -cdef ComplexIntervalFieldElement _to_CIF(acb_t source, ComplexIntervalFieldElement template): +cdef ComplexIntervalFieldElement _to_CIF(acb_t source, ComplexIntervalFieldElement template) noexcept: cdef ComplexIntervalFieldElement result result = template._new() acb_to_ComplexIntervalFieldElement( result, source) return result -cdef Matrix_generic_dense acb_mat_to_matrix(acb_mat_t source, Parent CIF): +cdef Matrix_generic_dense acb_mat_to_matrix(acb_mat_t source, Parent CIF) noexcept: """ Convert an ``acb_mat_t`` to a matrix containing :class:`ComplexIntervalFieldElement`. @@ -114,7 +114,7 @@ cdef Matrix_generic_dense acb_mat_to_matrix(acb_mat_t source, Parent CIF): for c in range(ncols)] for r in range(nrows)]) -cdef inline long prec(Matrix_complex_ball_dense mat): +cdef inline long prec(Matrix_complex_ball_dense mat) noexcept: return mat._base_ring._prec cdef class Matrix_complex_ball_dense(Matrix_dense): @@ -158,7 +158,7 @@ cdef class Matrix_complex_ball_dense(Matrix_dense): """ acb_mat_clear(self.value) - cdef Matrix_complex_ball_dense _new(self, Py_ssize_t nrows, Py_ssize_t ncols): + cdef Matrix_complex_ball_dense _new(self, Py_ssize_t nrows, Py_ssize_t ncols) noexcept: r""" Return a new matrix over the same base ring. """ @@ -252,7 +252,7 @@ cdef class Matrix_complex_ball_dense(Matrix_dense): z = se.entry acb_set(acb_mat_entry(self.value, se.i, se.j), z.value) - cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, object x): + cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, object x) noexcept: """ Set position ``i``, ``j`` of this matrix to ``x``. @@ -278,7 +278,7 @@ cdef class Matrix_complex_ball_dense(Matrix_dense): """ acb_set(acb_mat_entry(self.value, i, j), ( x).value) - cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j): + cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept: """ Return ``(i, j)`` entry of this matrix as a new ComplexBall. @@ -307,7 +307,7 @@ cdef class Matrix_complex_ball_dense(Matrix_dense): acb_set(z.value, acb_mat_entry(self.value, i, j)) return z - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: r""" EXAMPLES:: @@ -401,7 +401,7 @@ cdef class Matrix_complex_ball_dense(Matrix_dense): sig_off() return res - cpdef _add_(self, other): + cpdef _add_(self, other) noexcept: r""" TESTS:: @@ -414,7 +414,7 @@ cdef class Matrix_complex_ball_dense(Matrix_dense): sig_off() return res - cpdef _sub_(self, other): + cpdef _sub_(self, other) noexcept: r""" TESTS:: @@ -427,7 +427,7 @@ cdef class Matrix_complex_ball_dense(Matrix_dense): sig_off() return res - cpdef _lmul_(self, Element a): + cpdef _lmul_(self, Element a) noexcept: r""" TESTS:: @@ -440,7 +440,7 @@ cdef class Matrix_complex_ball_dense(Matrix_dense): sig_off() return res - cpdef _rmul_(self, Element a): + cpdef _rmul_(self, Element a) noexcept: r""" TESTS:: @@ -449,7 +449,7 @@ cdef class Matrix_complex_ball_dense(Matrix_dense): """ return self._lmul_(a) - cdef _matrix_times_matrix_(self, Matrix other): + cdef _matrix_times_matrix_(self, Matrix other) noexcept: r""" TESTS:: @@ -462,7 +462,7 @@ cdef class Matrix_complex_ball_dense(Matrix_dense): sig_off() return res - cpdef _pow_int(self, n): + cpdef _pow_int(self, n) noexcept: r""" Return the ``n``-th power of this matrix. @@ -961,7 +961,7 @@ cdef class Matrix_complex_ball_dense(Matrix_dense): sig_off() return res -cdef _acb_vec_to_list(acb_ptr vec, long n, Parent parent): +cdef _acb_vec_to_list(acb_ptr vec, long n, Parent parent) noexcept: cdef ComplexBall b res = [] for i in range(n): diff --git a/src/sage/matrix/matrix_cyclo_dense.pxd b/src/sage/matrix/matrix_cyclo_dense.pxd index 4bbb862355e..1ce4e1e1cfd 100644 --- a/src/sage/matrix/matrix_cyclo_dense.pxd +++ b/src/sage/matrix/matrix_cyclo_dense.pxd @@ -12,5 +12,5 @@ cdef class Matrix_cyclo_dense(Matrix_dense): cdef int _n cdef _randomize_rational_column_unsafe(Matrix_cyclo_dense self, - Py_ssize_t col, mpz_t nump1, mpz_t denp1, distribution=?) + Py_ssize_t col, mpz_t nump1, mpz_t denp1, distribution=?) noexcept diff --git a/src/sage/matrix/matrix_cyclo_dense.pyx b/src/sage/matrix/matrix_cyclo_dense.pyx index a49bb6240e6..c3ec3ebf81a 100644 --- a/src/sage/matrix/matrix_cyclo_dense.pyx +++ b/src/sage/matrix/matrix_cyclo_dense.pyx @@ -159,7 +159,7 @@ cdef class Matrix_cyclo_dense(Matrix_dense): QQmat = Matrix_rational_dense(QQspace, L, False, False) self._matrix = QQmat.transpose() - cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, value): + cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, value) noexcept: """ Set the ij-th entry of self. @@ -286,7 +286,7 @@ cdef class Matrix_cyclo_dense(Matrix_dense): mpz_clear(numer) mpz_clear(denom) - cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j): + cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept: """ Get the ij-th of self. @@ -488,7 +488,7 @@ cdef class Matrix_cyclo_dense(Matrix_dense): # * _dict -- sparse dictionary of underlying elements (need not be a copy) ######################################################################## - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Return the sum of two dense cyclotomic matrices. @@ -516,7 +516,7 @@ cdef class Matrix_cyclo_dense(Matrix_dense): A._matrix = self._matrix + (right)._matrix return A - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Return the difference of two dense cyclotomic matrices. @@ -543,7 +543,7 @@ cdef class Matrix_cyclo_dense(Matrix_dense): A._matrix = self._matrix - (right)._matrix return A - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: """ Multiply a dense cyclotomic matrix by a scalar. @@ -584,7 +584,7 @@ cdef class Matrix_cyclo_dense(Matrix_dense): A._matrix = T * self._matrix return A - cdef _matrix_times_matrix_(self, baseMatrix right): + cdef _matrix_times_matrix_(self, baseMatrix right) noexcept: """ Return the product of two cyclotomic dense matrices. @@ -719,7 +719,7 @@ cdef class Matrix_cyclo_dense(Matrix_dense): """ return hash(self._matrix) - cpdef _richcmp_(self, right, int op): + cpdef _richcmp_(self, right, int op) noexcept: """ Implement comparison of two cyclotomic matrices with identical parents. @@ -977,7 +977,7 @@ cdef class Matrix_cyclo_dense(Matrix_dense): return ht cdef _randomize_rational_column_unsafe(Matrix_cyclo_dense self, - Py_ssize_t col, mpz_t nump1, mpz_t denp1, distribution=None): + Py_ssize_t col, mpz_t nump1, mpz_t denp1, distribution=None) noexcept: """ Randomizes all entries in column ``col``. This is a helper method used in the implementation of dense matrices over cyclotomic fields. diff --git a/src/sage/matrix/matrix_dense.pxd b/src/sage/matrix/matrix_dense.pxd index 310ee33b0b7..3343438682b 100644 --- a/src/sage/matrix/matrix_dense.pxd +++ b/src/sage/matrix/matrix_dense.pxd @@ -1,4 +1,4 @@ from .matrix cimport Matrix cdef class Matrix_dense(Matrix): - cdef void set_unsafe_int(self, Py_ssize_t i, Py_ssize_t j, int value) + cdef void set_unsafe_int(self, Py_ssize_t i, Py_ssize_t j, int value) noexcept diff --git a/src/sage/matrix/matrix_dense.pyx b/src/sage/matrix/matrix_dense.pyx index 0f5089b5122..29b6f4faae2 100644 --- a/src/sage/matrix/matrix_dense.pyx +++ b/src/sage/matrix/matrix_dense.pyx @@ -16,10 +16,10 @@ import sage.structure.sequence cdef class Matrix_dense(matrix.Matrix): - cdef bint is_sparse_c(self): + cdef bint is_sparse_c(self) noexcept: return 0 - cdef bint is_dense_c(self): + cdef bint is_dense_c(self) noexcept: return 1 def __copy__(self): @@ -32,7 +32,7 @@ cdef class Matrix_dense(matrix.Matrix): A.subdivide(*self.subdivisions()) return A - cdef void set_unsafe_int(self, Py_ssize_t i, Py_ssize_t j, int value): + cdef void set_unsafe_int(self, Py_ssize_t i, Py_ssize_t j, int value) noexcept: self.set_unsafe(i, j, value) def _pickle(self): @@ -53,7 +53,7 @@ cdef class Matrix_dense(matrix.Matrix): else: raise RuntimeError("unknown matrix version (=%s)" % version) - cpdef _richcmp_(self, right, int op): + cpdef _richcmp_(self, right, int op) noexcept: """ EXAMPLES:: diff --git a/src/sage/matrix/matrix_double_dense.pyx b/src/sage/matrix/matrix_double_dense.pyx index bf8ade78c14..f4312a479e5 100644 --- a/src/sage/matrix/matrix_double_dense.pyx +++ b/src/sage/matrix/matrix_double_dense.pyx @@ -146,7 +146,7 @@ cdef class Matrix_double_dense(Matrix_numpy_dense): # LEVEL 2 functionality # * def _pickle # * def _unpickle - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Add two matrices together. @@ -169,7 +169,7 @@ cdef class Matrix_double_dense(Matrix_numpy_dense): M._matrix_numpy = _left._matrix_numpy + _right._matrix_numpy return M - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Return self - right @@ -220,7 +220,7 @@ cdef class Matrix_double_dense(Matrix_numpy_dense): # def _pickle(self): #unsure how to implement # def _unpickle(self, data, int version): # use version >= 0 #unsure how to implement ###################################################################### - cdef sage.structure.element.Matrix _matrix_times_matrix_(self, sage.structure.element.Matrix right): + cdef sage.structure.element.Matrix _matrix_times_matrix_(self, sage.structure.element.Matrix right) noexcept: r""" Multiply ``self * right`` as matrices. @@ -3557,7 +3557,7 @@ cdef class Matrix_double_dense(Matrix_numpy_dense): posdef = self.fetch(cache_str) return posdef - cdef _vector_times_matrix_(self,Vector v): + cdef _vector_times_matrix_(self,Vector v) noexcept: if self._nrows == 0 or self._ncols == 0: return self.row_ambient_module().zero_vector() global numpy @@ -3570,7 +3570,7 @@ cdef class Matrix_double_dense(Matrix_numpy_dense): ans = numpy.dot(v_numpy,self._matrix_numpy) return M(ans) - cdef _matrix_times_vector_(self,Vector v): + cdef _matrix_times_vector_(self,Vector v) noexcept: if self._nrows == 0 or self._ncols == 0: return self.column_ambient_module().zero_vector() diff --git a/src/sage/matrix/matrix_gap.pxd b/src/sage/matrix/matrix_gap.pxd index 0667c158df8..bb4801258cf 100644 --- a/src/sage/matrix/matrix_gap.pxd +++ b/src/sage/matrix/matrix_gap.pxd @@ -4,6 +4,6 @@ from sage.libs.gap.element cimport GapElement cdef class Matrix_gap(Matrix_dense): cdef GapElement _libgap - cpdef GapElement gap(self) - cdef Matrix_gap _new(self, Py_ssize_t nrows, Py_ssize_t ncols) + cpdef GapElement gap(self) noexcept + cdef Matrix_gap _new(self, Py_ssize_t nrows, Py_ssize_t ncols) noexcept diff --git a/src/sage/matrix/matrix_gap.pyx b/src/sage/matrix/matrix_gap.pyx index f3f77dcbe15..853cb0626a1 100644 --- a/src/sage/matrix/matrix_gap.pyx +++ b/src/sage/matrix/matrix_gap.pyx @@ -122,7 +122,7 @@ cdef class Matrix_gap(Matrix_dense): mat.append(row) self._libgap = libgap(mat) - cdef Matrix_gap _new(self, Py_ssize_t nrows, Py_ssize_t ncols): + cdef Matrix_gap _new(self, Py_ssize_t nrows, Py_ssize_t ncols) noexcept: if nrows == self._nrows and ncols == self._ncols: P = self._parent else: @@ -163,7 +163,7 @@ cdef class Matrix_gap(Matrix_dense): """ return self._parent, (self.list(),) - cpdef GapElement gap(self): + cpdef GapElement gap(self) noexcept: r""" Return the underlying gap object. @@ -181,10 +181,10 @@ cdef class Matrix_gap(Matrix_dense): """ return self._libgap - cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j): + cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept: return self._base_ring(self._libgap[i,j]) - cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, object x): + cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, object x) noexcept: r""" TESTS:: @@ -201,7 +201,7 @@ cdef class Matrix_gap(Matrix_dense): """ self._libgap[i,j] = x - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: r""" Compare ``self`` and ``right``. @@ -280,7 +280,7 @@ cdef class Matrix_gap(Matrix_dense): else: return Matrix_dense.__invert__(self) - cpdef _add_(left, right): + cpdef _add_(left, right) noexcept: r""" TESTS:: @@ -293,7 +293,7 @@ cdef class Matrix_gap(Matrix_dense): ans._libgap = left._libgap + ( right)._libgap return ans - cpdef _sub_(left, right): + cpdef _sub_(left, right) noexcept: r""" TESTS:: @@ -306,7 +306,7 @@ cdef class Matrix_gap(Matrix_dense): ans._libgap = left._libgap - ( right)._libgap return ans - cdef Matrix _matrix_times_matrix_(left, Matrix right): + cdef Matrix _matrix_times_matrix_(left, Matrix right) noexcept: r""" TESTS:: diff --git a/src/sage/matrix/matrix_generic_dense.pxd b/src/sage/matrix/matrix_generic_dense.pxd index 74994a27d72..86963fe05df 100644 --- a/src/sage/matrix/matrix_generic_dense.pxd +++ b/src/sage/matrix/matrix_generic_dense.pxd @@ -2,4 +2,4 @@ from .matrix_dense cimport Matrix_dense cdef class Matrix_generic_dense(Matrix_dense): cdef list _entries - cdef Matrix_generic_dense _new(self, Py_ssize_t nrows, Py_ssize_t ncols) + cdef Matrix_generic_dense _new(self, Py_ssize_t nrows, Py_ssize_t ncols) noexcept diff --git a/src/sage/matrix/matrix_generic_dense.pyx b/src/sage/matrix/matrix_generic_dense.pyx index 9c16ac3c486..3e51e0d1703 100644 --- a/src/sage/matrix/matrix_generic_dense.pyx +++ b/src/sage/matrix/matrix_generic_dense.pyx @@ -81,7 +81,7 @@ cdef class Matrix_generic_dense(matrix_dense.Matrix_dense): ma = MatrixArgs_init(parent, entries) self._entries = ma.list(coerce) - cdef Matrix_generic_dense _new(self, Py_ssize_t nrows, Py_ssize_t ncols): + cdef Matrix_generic_dense _new(self, Py_ssize_t nrows, Py_ssize_t ncols) noexcept: r""" Return a new dense matrix with no entries set. """ @@ -93,10 +93,10 @@ cdef class Matrix_generic_dense(matrix_dense.Matrix_dense): cdef type t = type(self) return t.__new__(t, MS) - cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, value): + cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, value) noexcept: self._entries[i*self._ncols + j] = value - cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j): + cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept: return self._entries[i*self._ncols + j] @@ -209,7 +209,7 @@ cdef class Matrix_generic_dense(matrix_dense.Matrix_dense): @cython.boundscheck(False) @cython.wraparound(False) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Add two generic dense matrices with the same parent. @@ -233,7 +233,7 @@ cdef class Matrix_generic_dense(matrix_dense.Matrix_dense): @cython.boundscheck(False) @cython.wraparound(False) - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Subtract two generic dense matrices with the same parent. diff --git a/src/sage/matrix/matrix_generic_sparse.pyx b/src/sage/matrix/matrix_generic_sparse.pyx index 4cd7cecc7e8..2570d08b55d 100644 --- a/src/sage/matrix/matrix_generic_sparse.pyx +++ b/src/sage/matrix/matrix_generic_sparse.pyx @@ -187,7 +187,7 @@ cdef class Matrix_generic_sparse(matrix_sparse.Matrix_sparse): """ return bool(self._entries) - cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, value): + cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, value) noexcept: if not value: try: del self._entries[(i,j)] @@ -196,7 +196,7 @@ cdef class Matrix_generic_sparse(matrix_sparse.Matrix_sparse): else: self._entries[(i,j)] = value - cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j): + cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept: return self._entries.get((i,j), self._zero) cdef bint get_is_zero_unsafe(self, Py_ssize_t i, Py_ssize_t j) except -1: @@ -247,7 +247,7 @@ cdef class Matrix_generic_sparse(matrix_sparse.Matrix_sparse): # x * _dict -- copy of the sparse dictionary of underlying elements ######################################################################## - cpdef _add_(self, _other): + cpdef _add_(self, _other) noexcept: """ EXAMPLES:: diff --git a/src/sage/matrix/matrix_gf2e_dense.pxd b/src/sage/matrix/matrix_gf2e_dense.pxd index c8d81d279f9..70391868740 100644 --- a/src/sage/matrix/matrix_gf2e_dense.pxd +++ b/src/sage/matrix/matrix_gf2e_dense.pxd @@ -9,6 +9,6 @@ cdef class Matrix_gf2e_dense(Matrix_dense): cdef object _zero cdef m4ri_word _zero_word # m4ri_word representation of _zero - cpdef Matrix_gf2e_dense _multiply_newton_john(Matrix_gf2e_dense self, Matrix_gf2e_dense right) - cpdef Matrix_gf2e_dense _multiply_karatsuba(Matrix_gf2e_dense self, Matrix_gf2e_dense right) - cpdef Matrix_gf2e_dense _multiply_strassen(Matrix_gf2e_dense self, Matrix_gf2e_dense right, cutoff=*) + cpdef Matrix_gf2e_dense _multiply_newton_john(Matrix_gf2e_dense self, Matrix_gf2e_dense right) noexcept + cpdef Matrix_gf2e_dense _multiply_karatsuba(Matrix_gf2e_dense self, Matrix_gf2e_dense right) noexcept + cpdef Matrix_gf2e_dense _multiply_strassen(Matrix_gf2e_dense self, Matrix_gf2e_dense right, cutoff=*) noexcept diff --git a/src/sage/matrix/matrix_gf2e_dense.pyx b/src/sage/matrix/matrix_gf2e_dense.pyx index 977dbd0d6b5..25db5315598 100644 --- a/src/sage/matrix/matrix_gf2e_dense.pyx +++ b/src/sage/matrix/matrix_gf2e_dense.pyx @@ -128,7 +128,7 @@ cdef class M4RIE_finite_field: if self.ff: gf2e_free(self.ff) -cdef m4ri_word poly_to_word(f): +cdef m4ri_word poly_to_word(f) noexcept: return f.to_integer() @@ -232,7 +232,7 @@ cdef class Matrix_gf2e_dense(matrix_dense.Matrix_dense): se = t mzed_write_elem(self._entries, se.i, se.j, poly_to_word(se.entry)) - cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, value): + cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, value) noexcept: """ A[i,j] = value without bound checks @@ -259,7 +259,7 @@ cdef class Matrix_gf2e_dense(matrix_dense.Matrix_dense): """ mzed_write_elem(self._entries, i, j, poly_to_word(value)) - cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j): + cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept: """ Get A[i,j] without bound checks. @@ -298,7 +298,7 @@ cdef class Matrix_gf2e_dense(matrix_dense.Matrix_dense): """ return mzed_read_elem(self._entries, i, j) == self._zero_word - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Return A+B @@ -324,7 +324,7 @@ cdef class Matrix_gf2e_dense(matrix_dense.Matrix_dense): return A - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ EXAMPLES:: @@ -385,7 +385,7 @@ cdef class Matrix_gf2e_dense(matrix_dense.Matrix_dense): sig_off() return ans - cdef _matrix_times_matrix_(self, Matrix right): + cdef _matrix_times_matrix_(self, Matrix right) noexcept: """ Return A*B @@ -428,7 +428,7 @@ cdef class Matrix_gf2e_dense(matrix_dense.Matrix_dense): sig_off() return ans - cpdef Matrix_gf2e_dense _multiply_newton_john(Matrix_gf2e_dense self, Matrix_gf2e_dense right): + cpdef Matrix_gf2e_dense _multiply_newton_john(Matrix_gf2e_dense self, Matrix_gf2e_dense right) noexcept: """ Return A*B using Newton-John tables. @@ -490,7 +490,7 @@ cdef class Matrix_gf2e_dense(matrix_dense.Matrix_dense): sig_off() return ans - cpdef Matrix_gf2e_dense _multiply_karatsuba(Matrix_gf2e_dense self, Matrix_gf2e_dense right): + cpdef Matrix_gf2e_dense _multiply_karatsuba(Matrix_gf2e_dense self, Matrix_gf2e_dense right) noexcept: r""" Matrix multiplication using Karatsuba over polynomials with matrix coefficients over GF(2). @@ -538,7 +538,7 @@ cdef class Matrix_gf2e_dense(matrix_dense.Matrix_dense): sig_off() return ans - cpdef Matrix_gf2e_dense _multiply_strassen(Matrix_gf2e_dense self, Matrix_gf2e_dense right, cutoff=0): + cpdef Matrix_gf2e_dense _multiply_strassen(Matrix_gf2e_dense self, Matrix_gf2e_dense right, cutoff=0) noexcept: """ Winograd-Strassen matrix multiplication with Newton-John multiplication as base case. @@ -592,7 +592,7 @@ cdef class Matrix_gf2e_dense(matrix_dense.Matrix_dense): sig_off() return ans - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: """ Return ``a*B`` for ``a`` an element of the base field. @@ -625,7 +625,7 @@ cdef class Matrix_gf2e_dense(matrix_dense.Matrix_dense): """ return self.__copy__() - cpdef _richcmp_(self, right, int op): + cpdef _richcmp_(self, right, int op) noexcept: """ EXAMPLES:: @@ -993,7 +993,7 @@ cdef class Matrix_gf2e_dense(matrix_dense.Matrix_dense): return A - cdef rescale_row_c(self, Py_ssize_t row, multiple, Py_ssize_t start_col): + cdef rescale_row_c(self, Py_ssize_t row, multiple, Py_ssize_t start_col) noexcept: """ Return ``multiple * self[row][start_col:]`` @@ -1034,7 +1034,7 @@ cdef class Matrix_gf2e_dense(matrix_dense.Matrix_dense): mzed_rescale_row(self._entries, row, start_col, x) - cdef add_multiple_of_row_c(self, Py_ssize_t row_to, Py_ssize_t row_from, multiple, Py_ssize_t start_col): + cdef add_multiple_of_row_c(self, Py_ssize_t row_to, Py_ssize_t row_from, multiple, Py_ssize_t start_col) noexcept: """ Compute ``self[row_to][start_col:] += multiple * self[row_from][start_col:]``. @@ -1068,7 +1068,7 @@ cdef class Matrix_gf2e_dense(matrix_dense.Matrix_dense): mzed_add_multiple_of_row(self._entries, row_to, self._entries, row_from, x, start_col) - cdef swap_rows_c(self, Py_ssize_t row1, Py_ssize_t row2): + cdef swap_rows_c(self, Py_ssize_t row1, Py_ssize_t row2) noexcept: """ Swap rows ``row1`` and ``row2``. @@ -1092,7 +1092,7 @@ cdef class Matrix_gf2e_dense(matrix_dense.Matrix_dense): """ mzed_row_swap(self._entries, row1, row2) - cdef swap_columns_c(self, Py_ssize_t col1, Py_ssize_t col2): + cdef swap_columns_c(self, Py_ssize_t col1, Py_ssize_t col2) noexcept: """ Swap columns ``col1`` and ``col2``. @@ -1189,7 +1189,7 @@ cdef class Matrix_gf2e_dense(matrix_dense.Matrix_dense): A._entries = mzed_concat(A._entries, self._entries, right._entries) return A - cdef _stack_impl(self, bottom): + cdef _stack_impl(self, bottom) noexcept: r""" Stack ``self`` on top of ``bottom``. diff --git a/src/sage/matrix/matrix_gfpn_dense.pxd b/src/sage/matrix/matrix_gfpn_dense.pxd index 7a457876b9a..8c435b8ea2f 100644 --- a/src/sage/matrix/matrix_gfpn_dense.pxd +++ b/src/sage/matrix/matrix_gfpn_dense.pxd @@ -18,20 +18,20 @@ from sage.libs.meataxe cimport * cdef class FieldConverter_class: cdef field # A function converting an int to a field element cdef FEL zero_FEL # the FEL representation of zero - cpdef fel_to_field(self, FEL x) + cpdef fel_to_field(self, FEL x) noexcept cpdef FEL field_to_fel(self, x) except 255 -cdef FieldConverter_class FieldConverter(field) +cdef FieldConverter_class FieldConverter(field) noexcept cdef class Matrix_gfpn_dense(Matrix_dense): cdef Matrix_t *Data cdef readonly FieldConverter_class _converter - cdef set_slice_unsafe(self, Py_ssize_t i, Matrix_gfpn_dense S) - cdef inline int get_unsafe_int(self, Py_ssize_t i, Py_ssize_t j) - cpdef Matrix_gfpn_dense get_slice(self, Py_ssize_t i, Py_ssize_t j) - cpdef list _rowlist_(self, i, j=*) - cpdef Matrix_gfpn_dense _multiply_classical(Matrix_gfpn_dense self, Matrix_gfpn_dense right) - cpdef Matrix_gfpn_dense _multiply_strassen(Matrix_gfpn_dense self, Matrix_gfpn_dense right, cutoff=*) + cdef set_slice_unsafe(self, Py_ssize_t i, Matrix_gfpn_dense S) noexcept + cdef inline int get_unsafe_int(self, Py_ssize_t i, Py_ssize_t j) noexcept + cpdef Matrix_gfpn_dense get_slice(self, Py_ssize_t i, Py_ssize_t j) noexcept + cpdef list _rowlist_(self, i, j=*) noexcept + cpdef Matrix_gfpn_dense _multiply_classical(Matrix_gfpn_dense self, Matrix_gfpn_dense right) noexcept + cpdef Matrix_gfpn_dense _multiply_strassen(Matrix_gfpn_dense self, Matrix_gfpn_dense right, cutoff=*) noexcept -cdef Matrix_gfpn_dense new_mtx(Matrix_t* mat, Matrix_gfpn_dense template) +cdef Matrix_gfpn_dense new_mtx(Matrix_t* mat, Matrix_gfpn_dense template) noexcept diff --git a/src/sage/matrix/matrix_gfpn_dense.pyx b/src/sage/matrix/matrix_gfpn_dense.pyx index 8e8e4d7336b..e680412ea0a 100644 --- a/src/sage/matrix/matrix_gfpn_dense.pyx +++ b/src/sage/matrix/matrix_gfpn_dense.pyx @@ -122,7 +122,7 @@ cdef class FieldConverter_class: self.field = field._cache.fetch_int self.zero_FEL = self.field_to_fel(field.zero()) - cpdef fel_to_field(self, FEL x): + cpdef fel_to_field(self, FEL x) noexcept: """ Fetch a python int into the field. @@ -214,7 +214,7 @@ cdef class PrimeFieldConverter_class(FieldConverter_class): """ self.field = field - cpdef fel_to_field(self, FEL x): + cpdef fel_to_field(self, FEL x) noexcept: """ Fetch a python int into the field. @@ -253,7 +253,7 @@ cdef class PrimeFieldConverter_class(FieldConverter_class): cdef dict _converter_cache = {} -cdef FieldConverter_class FieldConverter(field): +cdef FieldConverter_class FieldConverter(field) noexcept: """ Return a :class:`FieldConverter_class` or :class:`PrimeFieldConverter_class` instance, depending whether the field is prime or not. @@ -282,7 +282,7 @@ cdef FieldConverter_class FieldConverter(field): ## ###################################### -cdef Matrix_gfpn_dense new_mtx(Matrix_t* mat, Matrix_gfpn_dense template): +cdef Matrix_gfpn_dense new_mtx(Matrix_t* mat, Matrix_gfpn_dense template) noexcept: """ Create a new ``Matrix_gfpn_dense`` from a meataxe matrix @@ -550,7 +550,7 @@ cdef class Matrix_gfpn_dense(Matrix_dense): else: return mtx_unpickle, (0, 0, 0, '', not self._is_immutable) - cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j): + cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept: """ Get an element without checking. @@ -571,7 +571,7 @@ cdef class Matrix_gfpn_dense(Matrix_dense): FfSetField(self.Data.Field) return self._converter.fel_to_field(FfExtract(MatGetPtr(self.Data,i), j)) - cdef inline int get_unsafe_int(self, Py_ssize_t i, Py_ssize_t j): + cdef inline int get_unsafe_int(self, Py_ssize_t i, Py_ssize_t j) noexcept: # NOTE: # It is essential that you call FfSetField and FfSetNoc YOURSELF # and that you assert that the matrix is not empty! @@ -593,7 +593,7 @@ cdef class Matrix_gfpn_dense(Matrix_dense): FfSetField(self.Data.Field) return FfExtract(MatGetPtr(self.Data,i), j) == self._converter.zero_FEL - cpdef Matrix_gfpn_dense get_slice(self, Py_ssize_t i, Py_ssize_t j): + cpdef Matrix_gfpn_dense get_slice(self, Py_ssize_t i, Py_ssize_t j) noexcept: """ Return a horizontal slice of this matrix. @@ -630,7 +630,7 @@ cdef class Matrix_gfpn_dense(Matrix_dense): sig_off() return new_mtx(mat, self) - cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, value): + cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, value) noexcept: """ Set values without bound checking. @@ -661,14 +661,14 @@ cdef class Matrix_gfpn_dense(Matrix_dense): FfSetField(self.Data.Field) FfInsert(MatGetPtr(self.Data,i), j, self._converter.field_to_fel(value)) - cdef void set_unsafe_int(self, Py_ssize_t i, Py_ssize_t j, int value): + cdef void set_unsafe_int(self, Py_ssize_t i, Py_ssize_t j, int value) noexcept: # NOTE: # It is essential that you call FfSetField and FfSetNoc YOURSELF # and that you assert that the matrix is not empty! # This method is here for speed! FfInsert(FfGetPtr(self.Data.Data,i), j, FfFromInt(value)) - cdef set_slice_unsafe(self, Py_ssize_t i, Matrix_gfpn_dense S): + cdef set_slice_unsafe(self, Py_ssize_t i, Matrix_gfpn_dense S) noexcept: # Overwrite the self[i:i+S.nrows()] by the contents of S. # # NOTE: @@ -807,7 +807,7 @@ cdef class Matrix_gfpn_dense(Matrix_dense): ################## ## comparison - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Compare two :class:`Matrix_gfpn_dense` matrices. @@ -866,7 +866,7 @@ cdef class Matrix_gfpn_dense(Matrix_dense): return rich_to_bool(op, -1) return rich_to_bool(op, 0) - cpdef list _rowlist_(self, i, j=-1): + cpdef list _rowlist_(self, i, j=-1) noexcept: """ Return rows as a flat list of python ints. @@ -966,7 +966,7 @@ cdef class Matrix_gfpn_dense(Matrix_dense): ######################### ## Arithmetics - cdef rescale_row_c(self, Py_ssize_t i, s, Py_ssize_t start_col): + cdef rescale_row_c(self, Py_ssize_t i, s, Py_ssize_t start_col) noexcept: """ Rescale row number `i` in-place by multiplication with the scalar `s`. @@ -1042,7 +1042,7 @@ cdef class Matrix_gfpn_dense(Matrix_dense): FfSetNoc(noc) FfMulRow(row_head, c) - cdef add_multiple_of_row_c(self, Py_ssize_t row_to, Py_ssize_t row_from, multiple, Py_ssize_t start_col): + cdef add_multiple_of_row_c(self, Py_ssize_t row_to, Py_ssize_t row_from, multiple, Py_ssize_t start_col) noexcept: """ Add the ``multiple``-fold of row ``row_from`` in-place to row ``row_to``, beginning with ``start_col`` @@ -1112,7 +1112,7 @@ cdef class Matrix_gfpn_dense(Matrix_dense): FfSetNoc(noc) FfAddMulRow(row_to_head, row_from_head, c) - cdef swap_rows_c(self, Py_ssize_t row1, Py_ssize_t row2): + cdef swap_rows_c(self, Py_ssize_t row1, Py_ssize_t row2) noexcept: """ Swap the rows ``row1`` and ``row2`` in-place. @@ -1156,7 +1156,7 @@ cdef class Matrix_gfpn_dense(Matrix_dense): raise ValueError("self must be a square matrix") return self._converter.fel_to_field(MatTrace(self.Data)) - cdef _stack_impl(self, bottom): + cdef _stack_impl(self, bottom) noexcept: r""" Stack ``self`` on top of ``bottom``. @@ -1197,7 +1197,7 @@ cdef class Matrix_gfpn_dense(Matrix_dense): sig_off() return new_mtx(mat, self) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ TESTS:: @@ -1224,7 +1224,7 @@ cdef class Matrix_gfpn_dense(Matrix_dense): sig_off() return new_mtx(mat, self) - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ TESTS:: @@ -1273,7 +1273,7 @@ cdef class Matrix_gfpn_dense(Matrix_dense): raise ValueError("The matrix must not be empty") return self._lmul_(self._base_ring(-1)) - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: """ EXAMPLES:: @@ -1316,7 +1316,7 @@ cdef class Matrix_gfpn_dense(Matrix_dense): # asymptotically faster. So, we used it by default. return 0 - cpdef Matrix_gfpn_dense _multiply_classical(Matrix_gfpn_dense self, Matrix_gfpn_dense right): + cpdef Matrix_gfpn_dense _multiply_classical(Matrix_gfpn_dense self, Matrix_gfpn_dense right) noexcept: """ Multiplication using the cubic school book multiplication algorithm. @@ -1345,7 +1345,7 @@ cdef class Matrix_gfpn_dense(Matrix_dense): sig_off() return new_mtx(mat, self) - cpdef Matrix_gfpn_dense _multiply_strassen(Matrix_gfpn_dense self, Matrix_gfpn_dense right, cutoff=0): + cpdef Matrix_gfpn_dense _multiply_strassen(Matrix_gfpn_dense self, Matrix_gfpn_dense right, cutoff=0) noexcept: """ Matrix multiplication using the asymptotically fast Strassen-Winograd algorithm. @@ -1381,7 +1381,7 @@ cdef class Matrix_gfpn_dense(Matrix_dense): sig_off() return new_mtx(mat, self) - cdef _mul_long(self, long n): + cdef _mul_long(self, long n) noexcept: """ Multiply an MTX matrix with a field element represented by an integer. @@ -1599,7 +1599,7 @@ cdef class Matrix_gfpn_dense(Matrix_dense): self.cache("left_kernel_matrix", OUT) return OUT - cpdef _echelon_in_place(self, str algorithm): + cpdef _echelon_in_place(self, str algorithm) noexcept: """ Change this matrix into echelon form, using classical Gaussian elimination, and return the pivots. diff --git a/src/sage/matrix/matrix_integer_dense.pxd b/src/sage/matrix/matrix_integer_dense.pxd index 50d83753454..d606deacc45 100644 --- a/src/sage/matrix/matrix_integer_dense.pxd +++ b/src/sage/matrix/matrix_integer_dense.pxd @@ -11,16 +11,16 @@ cdef class Matrix_integer_dense(Matrix_dense): cdef fmpz_mat_t _matrix cdef object _pivots cdef int mpz_height(self, mpz_t height) except -1 - cdef _mod_int_c(self, mod_int modulus) - cdef _mod_two(self) - cdef _pickle_version0(self) - cdef _unpickle_version0(self, data) - cpdef _export_as_string(self, int base=?) - cdef void set_unsafe_mpz(self, Py_ssize_t i, Py_ssize_t j, const mpz_t value) - cdef void set_unsafe_double(self, Py_ssize_t i, Py_ssize_t j, double value) - cdef inline void get_unsafe_mpz(self, Py_ssize_t i, Py_ssize_t j, mpz_t value) - cdef inline int get_unsafe_int(self, Py_ssize_t i, Py_ssize_t j) - cdef inline double get_unsafe_double(self, Py_ssize_t i, Py_ssize_t j) + cdef _mod_int_c(self, mod_int modulus) noexcept + cdef _mod_two(self) noexcept + cdef _pickle_version0(self) noexcept + cdef _unpickle_version0(self, data) noexcept + cpdef _export_as_string(self, int base=?) noexcept + cdef void set_unsafe_mpz(self, Py_ssize_t i, Py_ssize_t j, const mpz_t value) noexcept + cdef void set_unsafe_double(self, Py_ssize_t i, Py_ssize_t j, double value) noexcept + cdef inline void get_unsafe_mpz(self, Py_ssize_t i, Py_ssize_t j, mpz_t value) noexcept + cdef inline int get_unsafe_int(self, Py_ssize_t i, Py_ssize_t j) noexcept + cdef inline double get_unsafe_double(self, Py_ssize_t i, Py_ssize_t j) noexcept # HNF Modn cdef int _hnf_modn(Matrix_integer_dense self, Matrix_integer_dense res, @@ -28,7 +28,7 @@ cdef class Matrix_integer_dense(Matrix_dense): cdef int* _hnf_modn_impl(Matrix_integer_dense self, unsigned int det, Py_ssize_t nrows, Py_ssize_t ncols) except NULL - cdef Matrix_integer_dense _new(self, Py_ssize_t nrows, Py_ssize_t ncols) + cdef Matrix_integer_dense _new(self, Py_ssize_t nrows, Py_ssize_t ncols) noexcept -cpdef _lift_crt(Matrix_integer_dense M, residues, moduli=*) +cpdef _lift_crt(Matrix_integer_dense M, residues, moduli=*) noexcept diff --git a/src/sage/matrix/matrix_integer_dense.pyx b/src/sage/matrix/matrix_integer_dense.pyx index 2dbeea17a3b..207aa73a592 100644 --- a/src/sage/matrix/matrix_integer_dense.pyx +++ b/src/sage/matrix/matrix_integer_dense.pyx @@ -163,7 +163,7 @@ cdef inline mpz_t * fmpz_mat_to_mpz_array(fmpz_mat_t m) except? NULL: return entries -cdef inline void mpz_array_clear(mpz_t * a, size_t length): +cdef inline void mpz_array_clear(mpz_t * a, size_t length) noexcept: cdef size_t i for i in range(length): mpz_clear(a[i]) @@ -311,7 +311,7 @@ cdef class Matrix_integer_dense(Matrix_dense): z = se.entry fmpz_set_mpz(fmpz_mat_entry(self._matrix, se.i, se.j), z.value) - cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, object x): + cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, object x) noexcept: """ Set position i,j of this matrix to ``x``. @@ -337,7 +337,7 @@ cdef class Matrix_integer_dense(Matrix_dense): """ self.set_unsafe_mpz(i, j, (x).value) - cdef void set_unsafe_mpz(self, Py_ssize_t i, Py_ssize_t j, const mpz_t value): + cdef void set_unsafe_mpz(self, Py_ssize_t i, Py_ssize_t j, const mpz_t value) noexcept: """ Set position i,j of this matrix to ``value``. @@ -362,19 +362,19 @@ cdef class Matrix_integer_dense(Matrix_dense): """ fmpz_set_mpz(fmpz_mat_entry(self._matrix,i,j), value) - cdef void set_unsafe_int(self, Py_ssize_t i, Py_ssize_t j, int value): + cdef void set_unsafe_int(self, Py_ssize_t i, Py_ssize_t j, int value) noexcept: """ Set position i,j of this matrix to ``value``. """ fmpz_set_si(fmpz_mat_entry(self._matrix,i,j), value) - cdef void set_unsafe_double(self, Py_ssize_t i, Py_ssize_t j, double value): + cdef void set_unsafe_double(self, Py_ssize_t i, Py_ssize_t j, double value) noexcept: """ Set position i,j of this matrix to ``value``. """ fmpz_set_d(fmpz_mat_entry(self._matrix,i,j), value) - cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j): + cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept: """ Return the (i, j) entry of self as a new Integer. @@ -402,7 +402,7 @@ cdef class Matrix_integer_dense(Matrix_dense): self.get_unsafe_mpz(i, j, z.value) return z - cdef inline void get_unsafe_mpz(self, Py_ssize_t i, Py_ssize_t j, mpz_t value): + cdef inline void get_unsafe_mpz(self, Py_ssize_t i, Py_ssize_t j, mpz_t value) noexcept: """ Copy entry i,j of the matrix ``self`` to ``value``. @@ -428,7 +428,7 @@ cdef class Matrix_integer_dense(Matrix_dense): """ fmpz_get_mpz(value,fmpz_mat_entry(self._matrix, i, j)) - cdef inline int get_unsafe_int(self, Py_ssize_t i, Py_ssize_t j): + cdef inline int get_unsafe_int(self, Py_ssize_t i, Py_ssize_t j) noexcept: """ Return the (i, j) entry of self as a new Integer. @@ -439,7 +439,7 @@ cdef class Matrix_integer_dense(Matrix_dense): """ return fmpz_get_si(fmpz_mat_entry(self._matrix, i, j)) - cdef inline double get_unsafe_double(self, Py_ssize_t i, Py_ssize_t j): + cdef inline double get_unsafe_double(self, Py_ssize_t i, Py_ssize_t j) noexcept: """ Return the (i, j) entry of self as a new Integer. @@ -490,7 +490,7 @@ cdef class Matrix_integer_dense(Matrix_dense): """ return self._pickle_version0(), 0 - cdef _pickle_version0(self): + cdef _pickle_version0(self) noexcept: """ EXAMPLES:: @@ -500,7 +500,7 @@ cdef class Matrix_integer_dense(Matrix_dense): """ return str_to_bytes(self._export_as_string(32), 'ascii') - cpdef _export_as_string(self, int base=10): + cpdef _export_as_string(self, int base=10) noexcept: """ Return space separated string of the entries in this matrix, in the given base. This is optimized for speed. @@ -585,7 +585,7 @@ cdef class Matrix_integer_dense(Matrix_dense): else: raise RuntimeError("unknown matrix version (=%s)"%version) - cdef _unpickle_version0(self, data): + cdef _unpickle_version0(self, data) noexcept: cdef Py_ssize_t i, j, n, k data = data.split() n = self._nrows * self._ncols @@ -611,7 +611,7 @@ cdef class Matrix_integer_dense(Matrix_dense): # LEVEL 1 helpers: # These function support the implementation of the level 1 functionality. ######################################################################## - cdef Matrix_integer_dense _new(self, Py_ssize_t nrows, Py_ssize_t ncols): + cdef Matrix_integer_dense _new(self, Py_ssize_t nrows, Py_ssize_t ncols) noexcept: """ Return a new matrix over the integers from given parent All memory is allocated for this matrix, but its @@ -820,7 +820,7 @@ cdef class Matrix_integer_dense(Matrix_dense): fmpz_clear(s) return M - cdef sage.structure.element.Matrix _matrix_times_matrix_(self, sage.structure.element.Matrix right): + cdef sage.structure.element.Matrix _matrix_times_matrix_(self, sage.structure.element.Matrix right) noexcept: cdef Matrix_integer_dense M if self._ncols != right._nrows: @@ -833,7 +833,7 @@ cdef class Matrix_integer_dense(Matrix_dense): sig_off() return M - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: """ EXAMPLES:: @@ -853,7 +853,7 @@ cdef class Matrix_integer_dense(Matrix_dense): sig_off() return M - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Add two dense matrices over ZZ. @@ -878,7 +878,7 @@ cdef class Matrix_integer_dense(Matrix_dense): sig_off() return M - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Subtract two dense matrices over ZZ. @@ -1018,7 +1018,7 @@ cdef class Matrix_integer_dense(Matrix_dense): sig_off() return M - cpdef _richcmp_(self, right, int op): + cpdef _richcmp_(self, right, int op) noexcept: r""" Compare ``self`` with ``right``, examining entries in lexicographic (row major) ordering. @@ -1052,7 +1052,7 @@ cdef class Matrix_integer_dense(Matrix_dense): return rich_to_bool(op, 0) # TODO: Implement better - cdef _vector_times_matrix_(self, Vector v): + cdef _vector_times_matrix_(self, Vector v) noexcept: """ Return the vector times matrix product. @@ -1577,7 +1577,7 @@ cdef class Matrix_integer_dense(Matrix_dense): else: return self._mod_int_c(modulus) - cdef _mod_two(self): + cdef _mod_two(self) noexcept: """ TESTS: @@ -1591,7 +1591,7 @@ cdef class Matrix_integer_dense(Matrix_dense): MS = matrix_space.MatrixSpace(GF(2), self._nrows, self._ncols) return Matrix_mod2_dense(MS, self, True, True) - cdef _mod_int_c(self, mod_int p): + cdef _mod_int_c(self, mod_int p) noexcept: from .matrix_modn_dense_float import MAX_MODULUS as MAX_MODULUS_FLOAT from .matrix_modn_dense_double import MAX_MODULUS as MAX_MODULUS_DOUBLE @@ -1678,7 +1678,7 @@ cdef class Matrix_integer_dense(Matrix_dense): sig_free(entry_list) return res - cpdef _echelon_in_place(self, str algorithm): + cpdef _echelon_in_place(self, str algorithm) noexcept: cdef Matrix_integer_dense E E = self.echelon_form() sig_on() @@ -5245,7 +5245,7 @@ cdef class Matrix_integer_dense(Matrix_dense): fmpz_get_mpz(v._entries[j], fmpz_mat_entry(self._matrix, j, i)) return v - cdef _stack_impl(self, bottom): + cdef _stack_impl(self, bottom) noexcept: r""" Return the matrix ``self`` on top of ``bottom``:: @@ -5946,7 +5946,7 @@ cdef class Matrix_integer_dense(Matrix_dense): return ComputeMinimalPolynomials(self).integer_valued_polynomials_generators() -cdef inline GEN pari_GEN(Matrix_integer_dense B): +cdef inline GEN pari_GEN(Matrix_integer_dense B) noexcept: r""" Create the PARI GEN object on the stack defined by the integer matrix B. This is used internally by the function for conversion @@ -5959,7 +5959,7 @@ cdef inline GEN pari_GEN(Matrix_integer_dense B): return A -cdef extract_hnf_from_pari_matrix(Matrix_integer_dense self, Gen H, bint include_zero_rows): +cdef extract_hnf_from_pari_matrix(Matrix_integer_dense self, Gen H, bint include_zero_rows) noexcept: cdef mpz_t tmp mpz_init(tmp) @@ -5981,7 +5981,7 @@ cdef extract_hnf_from_pari_matrix(Matrix_integer_dense self, Gen H, bint include return B -cdef _clear_columns(Matrix_integer_dense A, pivots, Py_ssize_t n): +cdef _clear_columns(Matrix_integer_dense A, pivots, Py_ssize_t n) noexcept: # Clear all columns cdef Py_ssize_t i, k, p, l, m = A._ncols cdef fmpz_t c,t @@ -6004,7 +6004,7 @@ cdef _clear_columns(Matrix_integer_dense A, pivots, Py_ssize_t n): sig_off() -cpdef _lift_crt(Matrix_integer_dense M, residues, moduli=None): +cpdef _lift_crt(Matrix_integer_dense M, residues, moduli=None) noexcept: """ INPUT: diff --git a/src/sage/matrix/matrix_integer_sparse.pxd b/src/sage/matrix/matrix_integer_sparse.pxd index 43e3b98c4f0..d69b4879dc5 100644 --- a/src/sage/matrix/matrix_integer_sparse.pxd +++ b/src/sage/matrix/matrix_integer_sparse.pxd @@ -5,4 +5,4 @@ from .matrix_sparse cimport Matrix_sparse cdef class Matrix_integer_sparse(Matrix_sparse): cdef mpz_vector* _matrix - cdef _mod_int_c(self, mod_int p) + cdef _mod_int_c(self, mod_int p) noexcept diff --git a/src/sage/matrix/matrix_integer_sparse.pyx b/src/sage/matrix/matrix_integer_sparse.pyx index f4320fcd914..0712500e67d 100644 --- a/src/sage/matrix/matrix_integer_sparse.pyx +++ b/src/sage/matrix/matrix_integer_sparse.pyx @@ -109,10 +109,10 @@ cdef class Matrix_integer_sparse(Matrix_sparse): if z: mpz_vector_set_entry(&self._matrix[se.i], se.j, z.value) - cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, x): + cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, x) noexcept: mpz_vector_set_entry(&self._matrix[i], j, ( x).value) - cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j): + cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept: cdef Integer x x = Integer() mpz_vector_get_entry(x.value, &self._matrix[i], j) @@ -159,7 +159,7 @@ cdef class Matrix_integer_sparse(Matrix_sparse): # def _multiply_classical(left, matrix.Matrix _right): # def _list(self): - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: """ EXAMPLES:: @@ -181,7 +181,7 @@ cdef class Matrix_integer_sparse(Matrix_sparse): mpz_vector_scalar_multiply(M_row, self_row, _x.value) return M - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: cdef Py_ssize_t i cdef Matrix_integer_sparse M @@ -195,7 +195,7 @@ cdef class Matrix_integer_sparse(Matrix_sparse): mpz_clear(mul) return M - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: cdef Py_ssize_t i cdef Matrix_integer_sparse M @@ -230,7 +230,7 @@ cdef class Matrix_integer_sparse(Matrix_sparse): self.cache('dict', d) return d - cdef sage.structure.element.Matrix _matrix_times_matrix_(self, sage.structure.element.Matrix _right): + cdef sage.structure.element.Matrix _matrix_times_matrix_(self, sage.structure.element.Matrix _right) noexcept: """ Return the product of the sparse integer matrices ``self`` and ``_right``. @@ -380,7 +380,7 @@ cdef class Matrix_integer_sparse(Matrix_sparse): """ return self._mod_int_c(modulus) - cdef _mod_int_c(self, mod_int p): + cdef _mod_int_c(self, mod_int p) noexcept: cdef Py_ssize_t i, j cdef Matrix_modn_sparse res cdef mpz_vector* self_row diff --git a/src/sage/matrix/matrix_mod2_dense.pxd b/src/sage/matrix/matrix_mod2_dense.pxd index ea3575ef3be..82df8116a5c 100644 --- a/src/sage/matrix/matrix_mod2_dense.pxd +++ b/src/sage/matrix/matrix_mod2_dense.pxd @@ -6,8 +6,8 @@ cdef class Matrix_mod2_dense(Matrix_dense): cdef object _one cdef object _zero - cpdef Matrix_mod2_dense _multiply_m4rm(Matrix_mod2_dense self, Matrix_mod2_dense right, int k) - cpdef Matrix_mod2_dense _multiply_strassen(Matrix_mod2_dense self, Matrix_mod2_dense right, int cutoff) + cpdef Matrix_mod2_dense _multiply_m4rm(Matrix_mod2_dense self, Matrix_mod2_dense right, int k) noexcept + cpdef Matrix_mod2_dense _multiply_strassen(Matrix_mod2_dense self, Matrix_mod2_dense right, int cutoff) noexcept # For conversion to other systems - cpdef _export_as_string(self) + cpdef _export_as_string(self) noexcept diff --git a/src/sage/matrix/matrix_mod2_dense.pyx b/src/sage/matrix/matrix_mod2_dense.pyx index 6365eb271aa..98708b4e9fb 100644 --- a/src/sage/matrix/matrix_mod2_dense.pyx +++ b/src/sage/matrix/matrix_mod2_dense.pyx @@ -329,16 +329,16 @@ cdef class Matrix_mod2_dense(matrix_dense.Matrix_dense): # dense or sparse return h # this exists for compatibility with matrix_modn_dense - cdef void set_unsafe_int(self, Py_ssize_t i, Py_ssize_t j, int value): + cdef void set_unsafe_int(self, Py_ssize_t i, Py_ssize_t j, int value) noexcept: """ Set the (i,j) entry of self to the int value. """ mzd_write_bit(self._entries, i, j, int(value)) - cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, value): + cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, value) noexcept: mzd_write_bit(self._entries, i, j, int(value)) - cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j): + cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept: if mzd_read_bit(self._entries, i, j): return self._one else: @@ -521,7 +521,7 @@ cdef class Matrix_mod2_dense(matrix_dense.Matrix_dense): # dense or sparse # def _pickle(self): # def _unpickle(self, data, int version): # use version >= 0 - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Matrix addition. @@ -559,7 +559,7 @@ cdef class Matrix_mod2_dense(matrix_dense.Matrix_dense): # dense or sparse return A - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Matrix addition. @@ -575,7 +575,7 @@ cdef class Matrix_mod2_dense(matrix_dense.Matrix_dense): # dense or sparse """ return self._add_(right) - cdef _matrix_times_vector_(self, Vector v): + cdef _matrix_times_vector_(self, Vector v) noexcept: """ EXAMPLES:: @@ -620,7 +620,7 @@ cdef class Matrix_mod2_dense(matrix_dense.Matrix_dense): # dense or sparse sig_off() return c - cdef _matrix_times_matrix_(self, Matrix right): + cdef _matrix_times_matrix_(self, Matrix right) noexcept: """ Matrix multiplication. @@ -633,7 +633,7 @@ cdef class Matrix_mod2_dense(matrix_dense.Matrix_dense): # dense or sparse return self._multiply_strassen(right, 0) - cpdef Matrix_mod2_dense _multiply_m4rm(Matrix_mod2_dense self, Matrix_mod2_dense right, int k): + cpdef Matrix_mod2_dense _multiply_m4rm(Matrix_mod2_dense self, Matrix_mod2_dense right, int k) noexcept: """ Multiply matrices using the 'Method of the Four Russians Multiplication' (M4RM) or Konrod's method. @@ -762,7 +762,7 @@ cdef class Matrix_mod2_dense(matrix_dense.Matrix_dense): # dense or sparse A._entries = mzd_mul_naive(A._entries, self._entries,(right)._entries) return A - cpdef Matrix_mod2_dense _multiply_strassen(Matrix_mod2_dense self, Matrix_mod2_dense right, int cutoff): + cpdef Matrix_mod2_dense _multiply_strassen(Matrix_mod2_dense self, Matrix_mod2_dense right, int cutoff) noexcept: r""" Strassen-Winograd `O(n^{2.807})` multiplication [Str1969]_. @@ -1237,7 +1237,7 @@ cdef class Matrix_mod2_dense(matrix_dense.Matrix_dense): # dense or sparse mzd_write_bit(self._entries, i, j, 1) sig_off() - cdef rescale_row_c(self, Py_ssize_t row, multiple, Py_ssize_t start_col): + cdef rescale_row_c(self, Py_ssize_t row, multiple, Py_ssize_t start_col) noexcept: """ EXAMPLES:: @@ -1250,7 +1250,7 @@ cdef class Matrix_mod2_dense(matrix_dense.Matrix_dense): # dense or sparse mzd_row_clear_offset(self._entries, row, start_col) cdef add_multiple_of_row_c(self, Py_ssize_t row_to, Py_ssize_t row_from, multiple, - Py_ssize_t start_col): + Py_ssize_t start_col) noexcept: """ EXAMPLES:: @@ -1263,7 +1263,7 @@ cdef class Matrix_mod2_dense(matrix_dense.Matrix_dense): # dense or sparse if int(multiple) % 2: mzd_row_add_offset(self._entries, row_to, row_from, start_col) - cdef swap_rows_c(self, Py_ssize_t row1, Py_ssize_t row2): + cdef swap_rows_c(self, Py_ssize_t row1, Py_ssize_t row2) noexcept: """ EXAMPLES:: @@ -1279,7 +1279,7 @@ cdef class Matrix_mod2_dense(matrix_dense.Matrix_dense): # dense or sparse """ mzd_row_swap(self._entries, row1, row2) - cdef swap_columns_c(self, Py_ssize_t col1, Py_ssize_t col2): + cdef swap_columns_c(self, Py_ssize_t col1, Py_ssize_t col2) noexcept: """ EXAMPLES:: @@ -1408,7 +1408,7 @@ cdef class Matrix_mod2_dense(matrix_dense.Matrix_dense): # dense or sparse A.subdivide(*self.subdivisions()) return A - cpdef _richcmp_(self, right, int op): + cpdef _richcmp_(self, right, int op) noexcept: """ Compare ``self`` with ``right``. @@ -1557,7 +1557,7 @@ cdef class Matrix_mod2_dense(matrix_dense.Matrix_dense): # dense or sparse Z._subdivide_on_augment(self, other) return Z - cdef _stack_impl(self, bottom): + cdef _stack_impl(self, bottom) noexcept: r""" Stack ``self`` on top of ``bottom``. @@ -1744,7 +1744,7 @@ cdef class Matrix_mod2_dense(matrix_dense.Matrix_dense): # dense or sparse gdImageDestroy(im) return unpickle_matrix_mod2_dense_v2, (r,c, data, size, self._is_immutable) - cpdef _export_as_string(self): + cpdef _export_as_string(self) noexcept: """ Return space separated string of the entries in this matrix. @@ -1953,7 +1953,7 @@ for i from 0 <= i < 256: # gmp's ULONG_PARITY may use special # assembly instructions, could be faster -cpdef inline unsigned long parity(m4ri_word a): +cpdef inline unsigned long parity(m4ri_word a) noexcept: """ Return the parity of the number of bits in a. @@ -1973,7 +1973,7 @@ cpdef inline unsigned long parity(m4ri_word a): a ^= a >> 8 return parity_table[a & 0xFF] -cdef inline unsigned long parity_mask(m4ri_word a): +cdef inline unsigned long parity_mask(m4ri_word a) noexcept: return -parity(a) diff --git a/src/sage/matrix/matrix_modn_dense_double.pyx b/src/sage/matrix/matrix_modn_dense_double.pyx index 12bc79159d3..858c3fcb887 100644 --- a/src/sage/matrix/matrix_modn_dense_double.pyx +++ b/src/sage/matrix/matrix_modn_dense_double.pyx @@ -73,7 +73,7 @@ cdef class Matrix_modn_dense_double(Matrix_modn_dense_template): # note that INTEGER_MOD_INT32_LIMIT is ceil(sqrt(2^31-1)) < 94906266 self._fits_int32 = ((self).p <= INTEGER_MOD_INT32_LIMIT) - cdef void set_unsafe_int(self, Py_ssize_t i, Py_ssize_t j, int value): + cdef void set_unsafe_int(self, Py_ssize_t i, Py_ssize_t j, int value) noexcept: r""" Set the (i,j) entry of self to the int value. @@ -101,7 +101,7 @@ cdef class Matrix_modn_dense_double(Matrix_modn_dense_template): """ self._matrix[i][j] = value - cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, x): + cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, x) noexcept: r""" Set the (i,j) entry with no bounds-checking, or any other checks. @@ -136,7 +136,7 @@ cdef class Matrix_modn_dense_double(Matrix_modn_dense_template): else: self._matrix[i][j] = (x).ivalue - cdef IntegerMod_abstract get_unsafe(self, Py_ssize_t i, Py_ssize_t j): + cdef IntegerMod_abstract get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept: r""" Return the (i,j) entry with no bounds-checking. diff --git a/src/sage/matrix/matrix_modn_dense_float.pyx b/src/sage/matrix/matrix_modn_dense_float.pyx index 8744cf494e3..325e492f5fb 100644 --- a/src/sage/matrix/matrix_modn_dense_float.pyx +++ b/src/sage/matrix/matrix_modn_dense_float.pyx @@ -67,7 +67,7 @@ cdef class Matrix_modn_dense_float(Matrix_modn_dense_template): """ self._get_template = self._base_ring.zero() - cdef void set_unsafe_int(self, Py_ssize_t i, Py_ssize_t j, int value): + cdef void set_unsafe_int(self, Py_ssize_t i, Py_ssize_t j, int value) noexcept: r""" Set the (i,j) entry of self to the int value. @@ -91,7 +91,7 @@ cdef class Matrix_modn_dense_float(Matrix_modn_dense_template): """ self._matrix[i][j] = value - cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, x): + cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, x) noexcept: r""" Set the (i,j) entry with no bounds-checking, or any other checks. @@ -121,7 +121,7 @@ cdef class Matrix_modn_dense_float(Matrix_modn_dense_template): """ self._matrix[i][j] = (x).ivalue - cdef IntegerMod_int get_unsafe(self, Py_ssize_t i, Py_ssize_t j): + cdef IntegerMod_int get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept: r""" Return the (i,j) entry with no bounds-checking. diff --git a/src/sage/matrix/matrix_modn_dense_template.pxi b/src/sage/matrix/matrix_modn_dense_template.pxi index 66618d2cbf1..55cff5b9ac7 100644 --- a/src/sage/matrix/matrix_modn_dense_template.pxi +++ b/src/sage/matrix/matrix_modn_dense_template.pxi @@ -131,7 +131,7 @@ from sage.cpython.string cimport char_to_str cdef long num = 1 cdef bint little_endian = ((&num))[0] -cdef inline celement_invert(celement a, celement n): +cdef inline celement_invert(celement a, celement n) noexcept: """ Invert the finite field element `a` modulo `n`. """ @@ -172,7 +172,7 @@ cdef inline bint linbox_is_zero(celement modulus, celement* entries, Py_ssize_t return 0 return 1 -cdef inline linbox_echelonize(celement modulus, celement* entries, Py_ssize_t nrows, Py_ssize_t ncols): +cdef inline linbox_echelonize(celement modulus, celement* entries, Py_ssize_t nrows, Py_ssize_t ncols) noexcept: """ Return the reduced row echelon form of this matrix. """ @@ -213,7 +213,7 @@ cdef inline linbox_echelonize(celement modulus, celement* entries, Py_ssize_t nr del F return r, pivots -cdef inline linbox_echelonize_efd(celement modulus, celement* entries, Py_ssize_t nrows, Py_ssize_t ncols): +cdef inline linbox_echelonize_efd(celement modulus, celement* entries, Py_ssize_t nrows, Py_ssize_t ncols) noexcept: # See trac #13878: This is to avoid sending invalid data to linbox, # which would yield a segfault in Sage's debug version. TODO: Fix # that bug upstream. @@ -276,7 +276,7 @@ cdef inline int linbox_rank(celement modulus, celement* entries, Py_ssize_t nrow del F return r -cdef inline celement linbox_det(celement modulus, celement* entries, Py_ssize_t n): +cdef inline celement linbox_det(celement modulus, celement* entries, Py_ssize_t n) noexcept: """ Return the determinant of this matrix. """ @@ -299,7 +299,7 @@ cdef inline celement linbox_det(celement modulus, celement* entries, Py_ssize_t del F return d -cdef inline celement linbox_matrix_matrix_multiply(celement modulus, celement* ans, celement* A, celement* B, Py_ssize_t m, Py_ssize_t n, Py_ssize_t k) : +cdef inline celement linbox_matrix_matrix_multiply(celement modulus, celement* ans, celement* A, celement* B, Py_ssize_t m, Py_ssize_t n, Py_ssize_t k) noexcept: """ C = A*B """ @@ -327,7 +327,7 @@ cdef inline celement linbox_matrix_matrix_multiply(celement modulus, celement* a del F -cdef inline int linbox_matrix_vector_multiply(celement modulus, celement* C, celement* A, celement* b, Py_ssize_t m, Py_ssize_t n, FFLAS_TRANSPOSE trans): +cdef inline int linbox_matrix_vector_multiply(celement modulus, celement* C, celement* A, celement* b, Py_ssize_t m, Py_ssize_t n, FFLAS_TRANSPOSE trans) noexcept: """ C = A*v """ @@ -347,7 +347,7 @@ cdef inline int linbox_matrix_vector_multiply(celement modulus, celement* C, cel del F -cdef inline linbox_minpoly(celement modulus, Py_ssize_t nrows, celement* entries): +cdef inline linbox_minpoly(celement modulus, Py_ssize_t nrows, celement* entries) noexcept: """ Compute the minimal polynomial. """ @@ -368,7 +368,7 @@ cdef inline linbox_minpoly(celement modulus, Py_ssize_t nrows, celement* entries del F return l -cdef inline linbox_charpoly(celement modulus, Py_ssize_t nrows, celement* entries): +cdef inline linbox_charpoly(celement modulus, Py_ssize_t nrows, celement* entries) noexcept: """ Compute the characteristic polynomial. """ @@ -396,7 +396,7 @@ cdef inline linbox_charpoly(celement modulus, Py_ssize_t nrows, celement* entrie return l -cpdef __matrix_from_rows_of_matrices(X): +cpdef __matrix_from_rows_of_matrices(X) noexcept: """ Return a matrix whose row ``i`` is constructed from the entries of matrix ``X[i]``. @@ -802,7 +802,7 @@ cdef class Matrix_modn_dense_template(Matrix_dense): sig_off() return M - cpdef _lmul_(self, Element left): + cpdef _lmul_(self, Element left) noexcept: """ EXAMPLES:: @@ -856,7 +856,7 @@ cdef class Matrix_modn_dense_template(Matrix_dense): return A - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: r""" Add two dense matrices over `\Z/n\Z` @@ -900,7 +900,7 @@ cdef class Matrix_modn_dense_template(Matrix_dense): return M - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: r""" Subtract two dense matrices over `\Z/n\Z` @@ -936,7 +936,7 @@ cdef class Matrix_modn_dense_template(Matrix_dense): sig_off() return M - cpdef _richcmp_(self, right, int op): + cpdef _richcmp_(self, right, int op) noexcept: r""" Compare two dense matrices over `\Z/n\Z`. @@ -988,7 +988,7 @@ cdef class Matrix_modn_dense_template(Matrix_dense): sig_off() return rich_to_bool(op, 0) - cdef _matrix_times_matrix_(self, Matrix right): + cdef _matrix_times_matrix_(self, Matrix right) noexcept: """ return ``self*right`` @@ -1146,7 +1146,7 @@ cdef class Matrix_modn_dense_template(Matrix_dense): return ans - cdef _vector_times_matrix_(self, Vector v): + cdef _vector_times_matrix_(self, Vector v) noexcept: """ ``v*self`` @@ -1203,7 +1203,7 @@ cdef class Matrix_modn_dense_template(Matrix_dense): sig_free(_c) return c - cdef _matrix_times_vector_(self, Vector v): + cdef _matrix_times_vector_(self, Vector v) noexcept: """ ``self*v`` @@ -2283,7 +2283,7 @@ cdef class Matrix_modn_dense_template(Matrix_dense): else: return Matrix_dense.determinant(self) - cdef xgcd_eliminate(self, celement * row1, celement* row2, Py_ssize_t start_col): + cdef xgcd_eliminate(self, celement * row1, celement* row2, Py_ssize_t start_col) noexcept: r""" Reduces ``row1`` and ``row2`` by a unimodular transformation using the xgcd relation between their first coefficients ``a`` and @@ -2325,7 +2325,7 @@ cdef class Matrix_modn_dense_template(Matrix_dense): row1[i] = tmp return g - cdef rescale_row_c(self, Py_ssize_t row, multiple, Py_ssize_t start_col): + cdef rescale_row_c(self, Py_ssize_t row, multiple, Py_ssize_t start_col) noexcept: """ Rescale ``self[row]`` by ``multiple`` but only start at column index ``start_col``. @@ -2376,7 +2376,7 @@ cdef class Matrix_modn_dense_template(Matrix_dense): for i from start_col <= i < self._ncols: v[i] = (v[i]*multiple) % p - cdef rescale_col_c(self, Py_ssize_t col, multiple, Py_ssize_t start_row): + cdef rescale_col_c(self, Py_ssize_t col, multiple, Py_ssize_t start_row) noexcept: """ EXAMPLES:: @@ -2419,7 +2419,7 @@ cdef class Matrix_modn_dense_template(Matrix_dense): for i from start_row <= i < self._nrows: self._matrix[i][col] = (self._matrix[i][col]*multiple) % p - cdef add_multiple_of_row_c(self, Py_ssize_t row_to, Py_ssize_t row_from, multiple, Py_ssize_t start_col): + cdef add_multiple_of_row_c(self, Py_ssize_t row_to, Py_ssize_t row_from, multiple, Py_ssize_t start_col) noexcept: """ Add ``multiple`` times ``self[row_from]`` to ``self[row_to]`` statting in column ``start_col``. @@ -2456,7 +2456,7 @@ cdef class Matrix_modn_dense_template(Matrix_dense): for i from start_col <= i < nc: v_to[i] = ((multiple) * v_from[i] + v_to[i]) % p - cdef add_multiple_of_column_c(self, Py_ssize_t col_to, Py_ssize_t col_from, multiple, Py_ssize_t start_row): + cdef add_multiple_of_column_c(self, Py_ssize_t col_to, Py_ssize_t col_from, multiple, Py_ssize_t start_row) noexcept: """ Add ``multiple`` times ``self[row_from]`` to ``self[row_to]`` statting in column ``start_col``. @@ -2491,7 +2491,7 @@ cdef class Matrix_modn_dense_template(Matrix_dense): for i from start_row <= i < self._nrows: m[i][col_to] = (m[i][col_to] + (multiple) * m[i][col_from]) %p - cdef swap_rows_c(self, Py_ssize_t row1, Py_ssize_t row2): + cdef swap_rows_c(self, Py_ssize_t row1, Py_ssize_t row2) noexcept: """ EXAMPLES:: @@ -2509,7 +2509,7 @@ cdef class Matrix_modn_dense_template(Matrix_dense): r1[i] = r2[i] r2[i] = temp - cdef swap_columns_c(self, Py_ssize_t col1, Py_ssize_t col2): + cdef swap_columns_c(self, Py_ssize_t col1, Py_ssize_t col2) noexcept: """ EXAMPLES:: @@ -2678,7 +2678,7 @@ cdef class Matrix_modn_dense_template(Matrix_dense): return 'Matrix(%s,%s,%s,StringToIntegerSequence("%s"))'%( s, self._nrows, self._ncols, self._export_as_string()) - cpdef _export_as_string(self): + cpdef _export_as_string(self) noexcept: """ Return space separated string of the entries in this matrix. @@ -2830,7 +2830,7 @@ cdef class Matrix_modn_dense_template(Matrix_dense): return M - cdef _stack_impl(self, bottom): + cdef _stack_impl(self, bottom) noexcept: r""" Implementation of :meth:`stack` by returning a new matrix formed by appending the matrix ``bottom`` beneath ``self``. @@ -3230,7 +3230,7 @@ cdef class Matrix_modn_dense_template(Matrix_dense): _matrix_from_rows_of_matrices = staticmethod(__matrix_from_rows_of_matrices) - cdef int _copy_row_to_mod_int_array(self, mod_int *to, Py_ssize_t i): + cdef int _copy_row_to_mod_int_array(self, mod_int *to, Py_ssize_t i) noexcept: cdef Py_ssize_t j cdef celement *_from = self._entries+(i*self._ncols) for j in range(self._ncols): diff --git a/src/sage/matrix/matrix_modn_dense_template_header.pxi b/src/sage/matrix/matrix_modn_dense_template_header.pxi index 84f4d10c29c..18e149fb5de 100644 --- a/src/sage/matrix/matrix_modn_dense_template_header.pxi +++ b/src/sage/matrix/matrix_modn_dense_template_header.pxi @@ -9,6 +9,6 @@ cdef class Matrix_modn_dense_template(Matrix_dense): cdef celement **_matrix cdef celement *_entries cdef mod_int p - cdef xgcd_eliminate (self, celement * row1, celement* row2, Py_ssize_t start_col) - cpdef _export_as_string(self) - cdef int _copy_row_to_mod_int_array(self, mod_int *to, Py_ssize_t i) + cdef xgcd_eliminate (self, celement * row1, celement* row2, Py_ssize_t start_col) noexcept + cpdef _export_as_string(self) noexcept + cdef int _copy_row_to_mod_int_array(self, mod_int *to, Py_ssize_t i) noexcept diff --git a/src/sage/matrix/matrix_modn_sparse.pxd b/src/sage/matrix/matrix_modn_sparse.pxd index dded069b3d8..37dd99bf5f3 100644 --- a/src/sage/matrix/matrix_modn_sparse.pxd +++ b/src/sage/matrix/matrix_modn_sparse.pxd @@ -4,4 +4,4 @@ from sage.modules.vector_modn_sparse cimport * cdef class Matrix_modn_sparse(Matrix_sparse): cdef c_vector_modint* rows cdef public int p - cdef swap_rows_c(self, Py_ssize_t n1, Py_ssize_t n2) + cdef swap_rows_c(self, Py_ssize_t n1, Py_ssize_t n2) noexcept diff --git a/src/sage/matrix/matrix_modn_sparse.pyx b/src/sage/matrix/matrix_modn_sparse.pyx index 9c12d6b9e1d..235fc4e7b81 100644 --- a/src/sage/matrix/matrix_modn_sparse.pyx +++ b/src/sage/matrix/matrix_modn_sparse.pyx @@ -173,10 +173,10 @@ cdef class Matrix_modn_sparse(Matrix_sparse): if z: set_entry(&self.rows[se.i], se.j, z) - cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, value): + cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, value) noexcept: set_entry(&self.rows[i], j, ( value).ivalue) - cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j): + cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept: cdef IntegerMod_int n n = IntegerMod_int.__new__(IntegerMod_int) IntegerMod_abstract.__init__(n, self._base_ring) @@ -255,7 +255,7 @@ cdef class Matrix_modn_sparse(Matrix_sparse): else: raise ValueError("unknown matrix format") - cdef Matrix _matrix_times_matrix_(self, Matrix _right): + cdef Matrix _matrix_times_matrix_(self, Matrix _right) noexcept: """ This code is implicitly called for multiplying self by another sparse matrix. @@ -392,7 +392,7 @@ cdef class Matrix_modn_sparse(Matrix_sparse): self.check_bounds_and_mutability(r2,0) self.swap_rows_c(r1, r2) - cdef swap_rows_c(self, Py_ssize_t n1, Py_ssize_t n2): + cdef swap_rows_c(self, Py_ssize_t n1, Py_ssize_t n2) noexcept: """ Swap the rows in positions n1 and n2. No bounds checking. """ @@ -401,7 +401,7 @@ cdef class Matrix_modn_sparse(Matrix_sparse): self.rows[n1] = self.rows[n2] self.rows[n2] = tmp - cpdef _echelon_in_place(self, str algorithm): + cpdef _echelon_in_place(self, str algorithm) noexcept: """ Replace self by its reduction to reduced row echelon form. diff --git a/src/sage/matrix/matrix_numpy_dense.pxd b/src/sage/matrix/matrix_numpy_dense.pxd index a0ec36c9228..fafc6fda5f7 100644 --- a/src/sage/matrix/matrix_numpy_dense.pxd +++ b/src/sage/matrix/matrix_numpy_dense.pxd @@ -8,5 +8,5 @@ cdef class Matrix_numpy_dense(Matrix_dense): cdef object _python_dtype cdef object _sage_dtype cdef object _sage_vector_dtype - cdef Matrix_numpy_dense _new(self, int nrows=*, int ncols=*) + cdef Matrix_numpy_dense _new(self, int nrows=*, int ncols=*) noexcept cdef cnumpy.ndarray _matrix_numpy diff --git a/src/sage/matrix/matrix_numpy_dense.pyx b/src/sage/matrix/matrix_numpy_dense.pyx index 31ffaa0a51c..d0e55fa927a 100644 --- a/src/sage/matrix/matrix_numpy_dense.pyx +++ b/src/sage/matrix/matrix_numpy_dense.pyx @@ -145,7 +145,7 @@ cdef class Matrix_numpy_dense(Matrix_dense): for j in range(ma.ncols): self.set_unsafe(i, j, next(it)) - cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, object value): + cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, object value) noexcept: """ Set the (i,j) entry to value without any bounds checking, mutability checking, etc. @@ -169,7 +169,7 @@ cdef class Matrix_numpy_dense(Matrix_dense): self._python_dtype(value)) #TODO: Throw an error if status == -1 - cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j): + cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept: """ Get the (i,j) entry without any bounds checking, etc. """ @@ -177,7 +177,7 @@ cdef class Matrix_numpy_dense(Matrix_dense): return self._sage_dtype(cnumpy.PyArray_GETITEM(self._matrix_numpy, cnumpy.PyArray_GETPTR2(self._matrix_numpy, i, j))) - cdef Matrix_numpy_dense _new(self, int nrows=-1, int ncols=-1): + cdef Matrix_numpy_dense _new(self, int nrows=-1, int ncols=-1) noexcept: """ Return a new uninitialized matrix with same parent as ``self``. diff --git a/src/sage/matrix/matrix_rational_dense.pxd b/src/sage/matrix/matrix_rational_dense.pxd index 5b59339d6f1..64d2c646e51 100644 --- a/src/sage/matrix/matrix_rational_dense.pxd +++ b/src/sage/matrix/matrix_rational_dense.pxd @@ -8,14 +8,14 @@ cdef class Matrix_rational_dense(Matrix_dense): cdef int fmpz_height(self, fmpz_t height) except -1 # cdef int _rescale(self, mpq_t a) except -1 - cdef _pickle_version0(self) - cdef _unpickle_version0(self, data) - cpdef _export_as_string(self, int base=?) + cdef _pickle_version0(self) noexcept + cdef _unpickle_version0(self, data) noexcept + cpdef _export_as_string(self, int base=?) noexcept - cdef _add_ui_unsafe_assuming_int(self, Py_ssize_t i, Py_ssize_t j, unsigned long int n) - cdef _sub_ui_unsafe_assuming_int(self, Py_ssize_t i, Py_ssize_t j, unsigned long int n) + cdef _add_ui_unsafe_assuming_int(self, Py_ssize_t i, Py_ssize_t j, unsigned long int n) noexcept + cdef _sub_ui_unsafe_assuming_int(self, Py_ssize_t i, Py_ssize_t j, unsigned long int n) noexcept - cdef inline Matrix_rational_dense _new_matrix(self, Py_ssize_t nrows, Py_ssize_t ncols) + cdef inline Matrix_rational_dense _new_matrix(self, Py_ssize_t nrows, Py_ssize_t ncols) noexcept cdef class MatrixWindow: cdef Matrix_rational_dense _matrix diff --git a/src/sage/matrix/matrix_rational_dense.pyx b/src/sage/matrix/matrix_rational_dense.pyx index c9e1d87b049..4f1e5e415e1 100644 --- a/src/sage/matrix/matrix_rational_dense.pyx +++ b/src/sage/matrix/matrix_rational_dense.pyx @@ -147,7 +147,7 @@ cdef class Matrix_rational_dense(Matrix_dense): fmpq_mat_init(self._matrix, self._nrows, self._ncols) sig_off() - cdef inline Matrix_rational_dense _new_matrix(self, Py_ssize_t nrows, Py_ssize_t ncols): + cdef inline Matrix_rational_dense _new_matrix(self, Py_ssize_t nrows, Py_ssize_t ncols) noexcept: if nrows == self._nrows and ncols == self._ncols: parent = self._parent else: @@ -255,10 +255,10 @@ cdef class Matrix_rational_dense(Matrix_dense): tmp) fmpq_clear(tmp) - cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, value): + cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, value) noexcept: fmpq_set_mpq(fmpq_mat_entry(self._matrix, i, j), ( value).value) - cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j): + cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept: cdef Rational x x = Rational.__new__(Rational) fmpq_get_mpq(x.value, fmpq_mat_entry(self._matrix, i, j)) @@ -275,14 +275,14 @@ cdef class Matrix_rational_dense(Matrix_dense): """ return fmpq_is_zero(fmpq_mat_entry(self._matrix, i,j)) - cdef _add_ui_unsafe_assuming_int(self, Py_ssize_t i, Py_ssize_t j, unsigned long int n): + cdef _add_ui_unsafe_assuming_int(self, Py_ssize_t i, Py_ssize_t j, unsigned long int n) noexcept: # doesn't check immutability # doesn't do bounds checks. # assumes that self[i,j] is an integer. cdef fmpz * entry = fmpq_numref(fmpq_mat_entry(self._matrix, i, j)) fmpz_add_ui(entry, entry, n) - cdef _sub_ui_unsafe_assuming_int(self, Py_ssize_t i, Py_ssize_t j, unsigned long int n): + cdef _sub_ui_unsafe_assuming_int(self, Py_ssize_t i, Py_ssize_t j, unsigned long int n) noexcept: # doesn't check immutability # doesn't do bounds checks. # assumes that self[i,j] is an integer. @@ -298,10 +298,10 @@ cdef class Matrix_rational_dense(Matrix_dense): else: raise RuntimeError("unknown matrix version (=%s)" % version) - cdef _pickle_version0(self): + cdef _pickle_version0(self) noexcept: return self._export_as_string(32) - cpdef _export_as_string(self, int base=10): + cpdef _export_as_string(self, int base=10) noexcept: """ Return space separated string of the entries in this matrix, in the given base. This is optimized for speed. @@ -356,7 +356,7 @@ cdef class Matrix_rational_dense(Matrix_dense): sig_free(s) return data - cdef _unpickle_version0(self, data): + cdef _unpickle_version0(self, data) noexcept: r""" TESTS:: @@ -398,7 +398,7 @@ cdef class Matrix_rational_dense(Matrix_dense): # * _dict -- sparse dictionary of underlying elements (need not be a copy) # ####################################################################### - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: """ EXAMPLES:: @@ -417,7 +417,7 @@ cdef class Matrix_rational_dense(Matrix_dense): fmpq_clear(x) return M - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Add two dense matrices over QQ. @@ -440,7 +440,7 @@ cdef class Matrix_rational_dense(Matrix_dense): sig_off() return ans - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Subtract two dense matrices over QQ. @@ -461,7 +461,7 @@ cdef class Matrix_rational_dense(Matrix_dense): sig_off() return ans - cpdef _richcmp_(self, right, int op): + cpdef _richcmp_(self, right, int op) noexcept: r""" TESTS:: @@ -502,7 +502,7 @@ cdef class Matrix_rational_dense(Matrix_dense): return rich_to_bool(op, -1) return rich_to_bool(op, 0) - cdef _vector_times_matrix_(self, Vector v): + cdef _vector_times_matrix_(self, Vector v) noexcept: r""" Return the vector times matrix product. @@ -1127,7 +1127,7 @@ cdef class Matrix_rational_dense(Matrix_dense): self.cache('minpoly', g) return g - cdef sage.structure.element.Matrix _matrix_times_matrix_(self, sage.structure.element.Matrix right): + cdef sage.structure.element.Matrix _matrix_times_matrix_(self, sage.structure.element.Matrix right) noexcept: """ EXAMPLES:: @@ -1809,7 +1809,7 @@ cdef class Matrix_rational_dense(Matrix_dense): fmpq_mat_swap(self._matrix, (E)._matrix) return pivots - cdef swap_rows_c(self, Py_ssize_t r1, Py_ssize_t r2): + cdef swap_rows_c(self, Py_ssize_t r1, Py_ssize_t r2) noexcept: """ EXAMPLES:: @@ -1825,7 +1825,7 @@ cdef class Matrix_rational_dense(Matrix_dense): fmpq_swap(fmpq_mat_entry(self._matrix, r1, c), fmpq_mat_entry(self._matrix, r2, c)) - cdef swap_columns_c(self, Py_ssize_t c1, Py_ssize_t c2): + cdef swap_columns_c(self, Py_ssize_t c1, Py_ssize_t c2) noexcept: """ EXAMPLES:: @@ -2947,7 +2947,7 @@ cdef class Matrix_rational_dense(Matrix_dense): return A.LLL(*args, **kwargs) / d -cdef new_matrix_from_pari_GEN(parent, GEN d): +cdef new_matrix_from_pari_GEN(parent, GEN d) noexcept: """ Given a PARI GEN with ``t_INT`` or ``t_FRAC entries, create a :class:`Matrix_rational_dense` from it. diff --git a/src/sage/matrix/matrix_rational_sparse.pyx b/src/sage/matrix/matrix_rational_sparse.pyx index 06b9689e849..497c58408b7 100644 --- a/src/sage/matrix/matrix_rational_sparse.pyx +++ b/src/sage/matrix/matrix_rational_sparse.pyx @@ -93,10 +93,10 @@ cdef class Matrix_rational_sparse(Matrix_sparse): if z: mpq_vector_set_entry(&self._matrix[se.i], se.j, z.value) - cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, x): + cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, x) noexcept: mpq_vector_set_entry(&self._matrix[i], j, ( x).value) - cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j): + cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept: cdef Rational x x = Rational() mpq_vector_get_entry(x.value, &self._matrix[i], j) @@ -168,7 +168,7 @@ cdef class Matrix_rational_sparse(Matrix_sparse): # * _list -- list of underlying elements (need not be a copy) # * x _dict -- sparse dictionary of underlying elements (need not be a copy) - cdef sage.structure.element.Matrix _matrix_times_matrix_(self, sage.structure.element.Matrix _right): + cdef sage.structure.element.Matrix _matrix_times_matrix_(self, sage.structure.element.Matrix _right) noexcept: cdef Matrix_rational_sparse right, ans right = _right diff --git a/src/sage/matrix/matrix_real_double_dense.pxd b/src/sage/matrix/matrix_real_double_dense.pxd index a6b2ad32ffc..3be163114c5 100644 --- a/src/sage/matrix/matrix_real_double_dense.pxd +++ b/src/sage/matrix/matrix_real_double_dense.pxd @@ -1,5 +1,5 @@ from .matrix_double_dense cimport Matrix_double_dense cdef class Matrix_real_double_dense(Matrix_double_dense): - cdef set_unsafe_double(self, Py_ssize_t i, Py_ssize_t j, double value) - cdef double get_unsafe_double(self, Py_ssize_t i, Py_ssize_t j) + cdef set_unsafe_double(self, Py_ssize_t i, Py_ssize_t j, double value) noexcept + cdef double get_unsafe_double(self, Py_ssize_t i, Py_ssize_t j) noexcept diff --git a/src/sage/matrix/matrix_real_double_dense.pyx b/src/sage/matrix/matrix_real_double_dense.pyx index eeff7658041..542638ed17d 100644 --- a/src/sage/matrix/matrix_real_double_dense.pyx +++ b/src/sage/matrix/matrix_real_double_dense.pyx @@ -99,7 +99,7 @@ cdef class Matrix_real_double_dense(Matrix_double_dense): self.__create_matrix__() return - cdef set_unsafe_double(self, Py_ssize_t i, Py_ssize_t j, double value): + cdef set_unsafe_double(self, Py_ssize_t i, Py_ssize_t j, double value) noexcept: """ Set the (i,j) entry to value without any type checking or bound checking. @@ -110,7 +110,7 @@ cdef class Matrix_real_double_dense(Matrix_double_dense): """ self.set_unsafe(i,j,value) - cdef double get_unsafe_double(self, Py_ssize_t i, Py_ssize_t j): + cdef double get_unsafe_double(self, Py_ssize_t i, Py_ssize_t j) noexcept: """ Get the (i,j) entry without any type checking or bound checking. diff --git a/src/sage/matrix/matrix_space.py b/src/sage/matrix/matrix_space.py index c307f4c28e4..279eba44511 100644 --- a/src/sage/matrix/matrix_space.py +++ b/src/sage/matrix/matrix_space.py @@ -2355,8 +2355,7 @@ def some_elements(self): ) """ yield self.an_element() - for g in self.gens(): - yield g + yield from self.gens() def _magma_init_(self, magma): r""" diff --git a/src/sage/matrix/matrix_sparse.pyx b/src/sage/matrix/matrix_sparse.pyx index 15f4cb093ee..a98c6bfe64c 100644 --- a/src/sage/matrix/matrix_sparse.pyx +++ b/src/sage/matrix/matrix_sparse.pyx @@ -27,10 +27,10 @@ import sage.matrix.matrix_space cdef class Matrix_sparse(matrix.Matrix): - cdef bint is_sparse_c(self): + cdef bint is_sparse_c(self) noexcept: return 1 - cdef bint is_dense_c(self): + cdef bint is_dense_c(self) noexcept: return 0 def change_ring(self, ring): @@ -301,7 +301,7 @@ cdef class Matrix_sparse(matrix.Matrix): return left.new_matrix(left._nrows, right._ncols, entries=e, coerce=False, copy=False) - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: """ Left scalar multiplication. Internal usage only. @@ -370,7 +370,7 @@ cdef class Matrix_sparse(matrix.Matrix): else: raise RuntimeError("unknown matrix version (=%s)" % version) - cpdef _richcmp_(self, right, int op): + cpdef _richcmp_(self, right, int op) noexcept: """ Rich comparison. @@ -968,7 +968,7 @@ cdef class Matrix_sparse(matrix.Matrix): A.set_unsafe(new_row, new_col, entry) return A - cdef _stack_impl(self, bottom): + cdef _stack_impl(self, bottom) noexcept: r""" Stack ``self`` on top of ``bottom``:: @@ -1119,7 +1119,7 @@ cdef class Matrix_sparse(matrix.Matrix): Z._subdivide_on_augment(self, other) return Z - cdef _vector_times_matrix_(self, Vector v): + cdef _vector_times_matrix_(self, Vector v) noexcept: """ Return the vector times matrix product. @@ -1152,7 +1152,7 @@ cdef class Matrix_sparse(matrix.Matrix): s[j] += v[i] * a return s - cdef _matrix_times_vector_(self, Vector v): + cdef _matrix_times_vector_(self, Vector v) noexcept: """ Return the matrix times vector product. @@ -1210,6 +1210,6 @@ cdef class Matrix_sparse(matrix.Matrix): @cython.wraparound(False) # Return v[i][j] where v is a list of tuples. # No checking is done, make sure you feed it valid input! -cdef inline Py_ssize_t get_ij(v, Py_ssize_t i, Py_ssize_t j): +cdef inline Py_ssize_t get_ij(v, Py_ssize_t i, Py_ssize_t j) noexcept: t = (v)[i] return (t)[j] diff --git a/src/sage/matrix/matrix_window.pxd b/src/sage/matrix/matrix_window.pxd index 6b7ce409d45..523f0d2b235 100644 --- a/src/sage/matrix/matrix_window.pxd +++ b/src/sage/matrix/matrix_window.pxd @@ -6,30 +6,30 @@ cdef class MatrixWindow: cdef object _cached_zero # YOU *REALLY SHOULD* OVERRIDE THESE: - cpdef add(MatrixWindow self, MatrixWindow A) - cpdef subtract(MatrixWindow self, MatrixWindow A) - cpdef set_to_sum(MatrixWindow self, MatrixWindow A, MatrixWindow B) - cpdef set_to_diff(MatrixWindow self, MatrixWindow A, MatrixWindow B) - cpdef set_to_prod(MatrixWindow self, MatrixWindow A, MatrixWindow B) - cpdef add_prod(MatrixWindow self, MatrixWindow A, MatrixWindow B) - cpdef subtract_prod(MatrixWindow self, MatrixWindow A, MatrixWindow B) + cpdef add(MatrixWindow self, MatrixWindow A) noexcept + cpdef subtract(MatrixWindow self, MatrixWindow A) noexcept + cpdef set_to_sum(MatrixWindow self, MatrixWindow A, MatrixWindow B) noexcept + cpdef set_to_diff(MatrixWindow self, MatrixWindow A, MatrixWindow B) noexcept + cpdef set_to_prod(MatrixWindow self, MatrixWindow A, MatrixWindow B) noexcept + cpdef add_prod(MatrixWindow self, MatrixWindow A, MatrixWindow B) noexcept + cpdef subtract_prod(MatrixWindow self, MatrixWindow A, MatrixWindow B) noexcept - cpdef bint element_is_zero(MatrixWindow self, Py_ssize_t i, Py_ssize_t j) - cpdef set_to(MatrixWindow self, MatrixWindow A) - cpdef set_to_zero(MatrixWindow self) + cpdef bint element_is_zero(MatrixWindow self, Py_ssize_t i, Py_ssize_t j) noexcept + cpdef set_to(MatrixWindow self, MatrixWindow A) noexcept + cpdef set_to_zero(MatrixWindow self) noexcept # FOR BETTER SPEED, OVERRIDE ANY SUBSET OF THESE (OPTIONAL): - cpdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, x) - cpdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) - cpdef to_matrix(MatrixWindow self) - cpdef new_empty_window(MatrixWindow self, Py_ssize_t nrows, Py_ssize_t ncols) + cpdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, x) noexcept + cpdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept + cpdef to_matrix(MatrixWindow self) noexcept + cpdef new_empty_window(MatrixWindow self, Py_ssize_t nrows, Py_ssize_t ncols) noexcept # NO BENEFIT TO OVERRIDING THESE: cpdef MatrixWindow matrix_window(MatrixWindow self, Py_ssize_t row, Py_ssize_t col, - Py_ssize_t n_rows, Py_ssize_t n_cols) + Py_ssize_t n_rows, Py_ssize_t n_cols) noexcept cpdef MatrixWindow new_matrix_window(MatrixWindow self, Matrix matrix, Py_ssize_t row, Py_ssize_t col, - Py_ssize_t n_rows, Py_ssize_t n_cols) - cpdef matrix(MatrixWindow self) - cpdef swap_rows(MatrixWindow self, Py_ssize_t a, Py_ssize_t b) - cdef object _zero(self) + Py_ssize_t n_rows, Py_ssize_t n_cols) noexcept + cpdef matrix(MatrixWindow self) noexcept + cpdef swap_rows(MatrixWindow self, Py_ssize_t a, Py_ssize_t b) noexcept + cdef object _zero(self) noexcept diff --git a/src/sage/matrix/matrix_window.pyx b/src/sage/matrix/matrix_window.pyx index e6046919191..671eee0a845 100644 --- a/src/sage/matrix/matrix_window.pyx +++ b/src/sage/matrix/matrix_window.pyx @@ -22,7 +22,7 @@ cdef class MatrixWindow: cpdef MatrixWindow new_matrix_window(MatrixWindow self, Matrix matrix, Py_ssize_t row, Py_ssize_t col, - Py_ssize_t n_rows, Py_ssize_t n_cols): + Py_ssize_t n_rows, Py_ssize_t n_cols) noexcept: """ This method is here only to provide a fast cdef way of constructing new matrix windows. The only implicit assumption @@ -47,13 +47,13 @@ cdef class MatrixWindow: self._nrows = nrows self._ncols = ncols - cdef object _zero(self): + cdef object _zero(self) noexcept: if self._cached_zero is None: self._cached_zero = self._matrix.base_ring()(0) # expensive return self._cached_zero cpdef MatrixWindow matrix_window(MatrixWindow self, Py_ssize_t row, Py_ssize_t col, - Py_ssize_t n_rows, Py_ssize_t n_cols): + Py_ssize_t n_rows, Py_ssize_t n_cols) noexcept: """ Returns a matrix window relative to this window of the underlying matrix. @@ -62,7 +62,7 @@ cdef class MatrixWindow: return self return self.new_matrix_window(self._matrix, self._row + row, self._col + col, n_rows, n_cols) - cpdef new_empty_window(MatrixWindow self, Py_ssize_t nrows, Py_ssize_t ncols): + cpdef new_empty_window(MatrixWindow self, Py_ssize_t nrows, Py_ssize_t ncols) noexcept: a = self._matrix.new_matrix(nrows, ncols) return self.new_matrix_window(a, 0, 0, nrows, ncols) @@ -79,10 +79,10 @@ cdef class MatrixWindow: raise TypeError("Parents must be equal.") self.set_to(src) - cpdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, x): + cpdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, x) noexcept: self._matrix.set_unsafe(i + self._row, j + self._col, x) - cpdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j): + cpdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j) noexcept: return self._matrix.get_unsafe(i + self._row, j + self._col) def __setitem__(self, ij, x): @@ -119,14 +119,14 @@ cdef class MatrixWindow: i = ij return self.row(i) - cpdef matrix(MatrixWindow self): + cpdef matrix(MatrixWindow self) noexcept: """ Returns the underlying matrix that this window is a view of. """ return self._matrix - cpdef to_matrix(MatrixWindow self): + cpdef to_matrix(MatrixWindow self) noexcept: """ Returns an actual matrix object representing this view. """ @@ -142,7 +142,7 @@ cdef class MatrixWindow: def ncols(MatrixWindow self): return self._ncols - cpdef set_to(MatrixWindow self, MatrixWindow A): + cpdef set_to(MatrixWindow self, MatrixWindow A) noexcept: """ Change self, making it equal A. """ @@ -154,14 +154,14 @@ cdef class MatrixWindow: self.set_unsafe(i, j, A.get_unsafe(i, j)) return 0 - cpdef set_to_zero(MatrixWindow self): + cpdef set_to_zero(MatrixWindow self) noexcept: cdef Py_ssize_t i, j z = self._zero() for i from 0 <= i < self._nrows: for j from 0 <= j < self._ncols: self.set_unsafe(i, j, z) - cpdef add(MatrixWindow self, MatrixWindow A): + cpdef add(MatrixWindow self, MatrixWindow A) noexcept: cdef Py_ssize_t i, j if self._nrows != A._nrows or self._ncols != A._ncols: raise ArithmeticError("incompatible dimensions") @@ -169,7 +169,7 @@ cdef class MatrixWindow: for j from 0 <= j < self._ncols: self.set_unsafe(i, j, self.get_unsafe(i, j) + A.get_unsafe(i, j)) - cpdef subtract(MatrixWindow self, MatrixWindow A): + cpdef subtract(MatrixWindow self, MatrixWindow A) noexcept: cdef Py_ssize_t i, j if self._nrows != A._nrows or self._ncols != A._ncols: raise ArithmeticError("incompatible dimensions") @@ -177,7 +177,7 @@ cdef class MatrixWindow: for j from 0 <= j < self._ncols: self.set_unsafe(i, j, self.get_unsafe(i, j) - A.get_unsafe(i, j)) - cpdef set_to_sum(MatrixWindow self, MatrixWindow A, MatrixWindow B): + cpdef set_to_sum(MatrixWindow self, MatrixWindow A, MatrixWindow B) noexcept: cdef Py_ssize_t i, j if self._nrows != A._nrows or self._ncols != A._ncols: raise ArithmeticError("incompatible dimensions") @@ -187,13 +187,13 @@ cdef class MatrixWindow: for j from 0 <= j < self._ncols: self.set_unsafe(i, j, A.get_unsafe(i, j) + B.get_unsafe(i, j)) - cpdef set_to_diff(MatrixWindow self, MatrixWindow A, MatrixWindow B): + cpdef set_to_diff(MatrixWindow self, MatrixWindow A, MatrixWindow B) noexcept: cdef Py_ssize_t i, j for i from 0 <= i < self._nrows: for j from 0 <= j < self._ncols: self.set_unsafe(i, j, A.get_unsafe(i, j) - B.get_unsafe(i, j)) - cpdef set_to_prod(MatrixWindow self, MatrixWindow A, MatrixWindow B): + cpdef set_to_prod(MatrixWindow self, MatrixWindow A, MatrixWindow B) noexcept: cdef Py_ssize_t i, j, k if A._ncols != B._nrows or self._nrows != A._nrows or self._ncols != B._ncols: raise ArithmeticError("incompatible dimensions") @@ -204,7 +204,7 @@ cdef class MatrixWindow: s = s + A.get_unsafe(i, k) * B.get_unsafe(k, j) self.set_unsafe(i, j, s) - cpdef add_prod(MatrixWindow self, MatrixWindow A, MatrixWindow B): + cpdef add_prod(MatrixWindow self, MatrixWindow A, MatrixWindow B) noexcept: cdef Py_ssize_t i, j, k if A._ncols != B._nrows or self._nrows != A._nrows or self._ncols != B._ncols: raise ArithmeticError("incompatible dimensions") @@ -215,7 +215,7 @@ cdef class MatrixWindow: s = s + A.get_unsafe(i, k) * B.get_unsafe(k, j) self.set_unsafe(i, j, s) - cpdef subtract_prod(MatrixWindow self, MatrixWindow A, MatrixWindow B): + cpdef subtract_prod(MatrixWindow self, MatrixWindow A, MatrixWindow B) noexcept: cdef Py_ssize_t i, j, k if A._ncols != B._nrows or self._nrows != A._nrows or self._ncols != B._ncols: raise ArithmeticError("incompatible dimensions") @@ -226,7 +226,7 @@ cdef class MatrixWindow: s = s - A.get_unsafe(i, k) * B.get_unsafe(k, j) self.set_unsafe(i, j, s) - cpdef swap_rows(MatrixWindow self, Py_ssize_t a, Py_ssize_t b): + cpdef swap_rows(MatrixWindow self, Py_ssize_t a, Py_ssize_t b) noexcept: self._matrix.swap_rows_c(self._row + a, self._row + b) def echelon_in_place(MatrixWindow self): @@ -238,5 +238,5 @@ cdef class MatrixWindow: self.set_to(echelon.matrix_window()) return echelon.pivots() - cpdef bint element_is_zero(MatrixWindow self, Py_ssize_t i, Py_ssize_t j): + cpdef bint element_is_zero(MatrixWindow self, Py_ssize_t i, Py_ssize_t j) noexcept: return self._matrix.get_unsafe(i+self._row, j+self._col) == self._zero() diff --git a/src/sage/matrix/strassen.pyx b/src/sage/matrix/strassen.pyx index 13a8c152fd9..9e2797c9925 100644 --- a/src/sage/matrix/strassen.pyx +++ b/src/sage/matrix/strassen.pyx @@ -50,7 +50,7 @@ def strassen_window_multiply(C, A,B, cutoff): cdef strassen_window_multiply_c(MatrixWindow C, MatrixWindow A, - MatrixWindow B, Py_ssize_t cutoff): + MatrixWindow B, Py_ssize_t cutoff) noexcept: # todo -- I'm not sure how to interpret "cutoff". Should it be... # (a) the minimum side length of the matrices (currently implemented below) # (b) the maximum side length of the matrices @@ -235,7 +235,7 @@ cdef strassen_window_multiply_c(MatrixWindow C, MatrixWindow A, C_bulk = C.matrix_window(0, 0, A_sub_nrows << 1, B_sub_ncols << 1) C_bulk.add_prod(A_last_col, B_last_row) -cdef subtract_strassen_product(MatrixWindow result, MatrixWindow A, MatrixWindow B, Py_ssize_t cutoff): +cdef subtract_strassen_product(MatrixWindow result, MatrixWindow A, MatrixWindow B, Py_ssize_t cutoff) noexcept: cdef MatrixWindow to_sub if (cutoff == -1 or result.ncols() <= cutoff or result.nrows() <= cutoff): result.subtract_prod(A, B) @@ -311,7 +311,7 @@ def strassen_echelon(MatrixWindow A, cutoff): sig_off() -cdef strassen_echelon_c(MatrixWindow A, Py_ssize_t cutoff, Py_ssize_t mul_cutoff): +cdef strassen_echelon_c(MatrixWindow A, Py_ssize_t cutoff, Py_ssize_t mul_cutoff) noexcept: # The following notation will be used in the comments below, which should be understood to give # the general idea of what's going on, as if there were no inconvenient non-pivot columns. # The original matrix is given by [ A B ] diff --git a/src/sage/matroids/basis_exchange_matroid.pxd b/src/sage/matroids/basis_exchange_matroid.pxd index 28cc7ad868c..b762fd9ed9d 100644 --- a/src/sage/matroids/basis_exchange_matroid.pxd +++ b/src/sage/matroids/basis_exchange_matroid.pxd @@ -15,86 +15,86 @@ cdef class BasisExchangeMatroid(Matroid): cdef _weak_invariant_var, _strong_invariant_var, _heuristic_invariant_var cdef SetSystem _weak_partition_var, _strong_partition_var, _heuristic_partition_var - cdef _relabel(self, l) + cdef _relabel(self, l) noexcept - cdef _pack(self, bitset_t, X) - cdef __unpack(self, bitset_t) + cdef _pack(self, bitset_t, X) noexcept + cdef __unpack(self, bitset_t) noexcept cdef bint _is_exchange_pair(self, long x, long y) except -1 cdef int _exchange(self, long x, long y) except -1 cdef int _move(self, bitset_t X, bitset_t Y) except -1 - cdef __fundamental_cocircuit(self, bitset_t, long x) - cdef __fundamental_circuit(self, bitset_t, long y) + cdef __fundamental_cocircuit(self, bitset_t, long x) noexcept + cdef __fundamental_circuit(self, bitset_t, long y) noexcept - cdef __max_independent(self, bitset_t, bitset_t) - cdef __circuit(self, bitset_t, bitset_t) - cdef __closure(self, bitset_t, bitset_t) - cdef __max_coindependent(self, bitset_t, bitset_t) - cdef __cocircuit(self, bitset_t, bitset_t) - cdef _coclosure_internal(self, bitset_t, bitset_t) + cdef __max_independent(self, bitset_t, bitset_t) noexcept + cdef __circuit(self, bitset_t, bitset_t) noexcept + cdef __closure(self, bitset_t, bitset_t) noexcept + cdef __max_coindependent(self, bitset_t, bitset_t) noexcept + cdef __cocircuit(self, bitset_t, bitset_t) noexcept + cdef _coclosure_internal(self, bitset_t, bitset_t) noexcept - cdef __augment(self, bitset_t, bitset_t, bitset_t) + cdef __augment(self, bitset_t, bitset_t, bitset_t) noexcept cdef bint __is_independent(self, bitset_t F) except -1 - cdef __move_current_basis(self, bitset_t, bitset_t) - - cdef bint _set_current_basis(self, F) - - cpdef groundset(self) - cpdef groundset_list(self) - cpdef full_rank(self) - cpdef full_corank(self) - - cpdef basis(self) - cpdef _move_current_basis(self, X, Y) - - cpdef _max_independent(self, F) - cpdef _rank(self, F) - cpdef _circuit(self, F) - cpdef _fundamental_circuit(self, B, e) - cpdef _closure(self, F) - - cpdef _max_coindependent(self, F) - cpdef _corank(self, F) - cpdef _cocircuit(self, F) - cpdef _fundamental_cocircuit(self, B, e) - cpdef _coclosure(self, F) - - cpdef _augment(self, X, Y) - cpdef _is_independent(self, F) - - cpdef f_vector(self) - cdef _f_vector_rec(self, object f_vec, bitset_t* flats, bitset_t* todo, long elt, long rnk) - cpdef flats(self, R) - cdef _flats_rec(self, SetSystem Rflats, long R, bitset_t* flats, bitset_t* todo, long elt, long rnk) - cpdef coflats(self, R) - cdef _coflats_rec(self, SetSystem Rcoflats, long R, bitset_t* coflats, bitset_t* todo, long elt, long cornk) - cdef _flat_element_inv(self, long k) - cdef _flat_element_inv_rec(self, object f_inc, long R, bitset_t* flats, bitset_t* todo, long elt, long i) - - cpdef bases_count(self) - cpdef independent_r_sets(self, long r) - cpdef bases(self) - cpdef dependent_r_sets(self, long r) - cpdef nonbases(self) - - cpdef nonspanning_circuits(self) - cpdef cocircuits(self) - cpdef circuits(self) - - cpdef _characteristic_setsystem(self) - cpdef _weak_invariant(self) - cpdef _weak_partition(self) - cpdef _strong_invariant(self) - cpdef _strong_partition(self) - cpdef _heuristic_invariant(self) - cpdef _heuristic_partition(self) - cdef _flush(self) - - cpdef _equitable_partition(self, P=*) - cpdef _is_isomorphic(self, other, certificate=*) - cpdef _isomorphism(self, other) - cpdef _is_isomorphism(self, other, morphism) - cdef bint __is_isomorphism(self, BasisExchangeMatroid other, morphism) - - cpdef is_valid(self) - -cdef bint nxksrd(bitset_s *b, long n, long k, bint succ) + cdef __move_current_basis(self, bitset_t, bitset_t) noexcept + + cdef bint _set_current_basis(self, F) noexcept + + cpdef groundset(self) noexcept + cpdef groundset_list(self) noexcept + cpdef full_rank(self) noexcept + cpdef full_corank(self) noexcept + + cpdef basis(self) noexcept + cpdef _move_current_basis(self, X, Y) noexcept + + cpdef _max_independent(self, F) noexcept + cpdef _rank(self, F) noexcept + cpdef _circuit(self, F) noexcept + cpdef _fundamental_circuit(self, B, e) noexcept + cpdef _closure(self, F) noexcept + + cpdef _max_coindependent(self, F) noexcept + cpdef _corank(self, F) noexcept + cpdef _cocircuit(self, F) noexcept + cpdef _fundamental_cocircuit(self, B, e) noexcept + cpdef _coclosure(self, F) noexcept + + cpdef _augment(self, X, Y) noexcept + cpdef _is_independent(self, F) noexcept + + cpdef f_vector(self) noexcept + cdef _f_vector_rec(self, object f_vec, bitset_t* flats, bitset_t* todo, long elt, long rnk) noexcept + cpdef flats(self, R) noexcept + cdef _flats_rec(self, SetSystem Rflats, long R, bitset_t* flats, bitset_t* todo, long elt, long rnk) noexcept + cpdef coflats(self, R) noexcept + cdef _coflats_rec(self, SetSystem Rcoflats, long R, bitset_t* coflats, bitset_t* todo, long elt, long cornk) noexcept + cdef _flat_element_inv(self, long k) noexcept + cdef _flat_element_inv_rec(self, object f_inc, long R, bitset_t* flats, bitset_t* todo, long elt, long i) noexcept + + cpdef bases_count(self) noexcept + cpdef independent_r_sets(self, long r) noexcept + cpdef bases(self) noexcept + cpdef dependent_r_sets(self, long r) noexcept + cpdef nonbases(self) noexcept + + cpdef nonspanning_circuits(self) noexcept + cpdef cocircuits(self) noexcept + cpdef circuits(self) noexcept + + cpdef _characteristic_setsystem(self) noexcept + cpdef _weak_invariant(self) noexcept + cpdef _weak_partition(self) noexcept + cpdef _strong_invariant(self) noexcept + cpdef _strong_partition(self) noexcept + cpdef _heuristic_invariant(self) noexcept + cpdef _heuristic_partition(self) noexcept + cdef _flush(self) noexcept + + cpdef _equitable_partition(self, P=*) noexcept + cpdef _is_isomorphic(self, other, certificate=*) noexcept + cpdef _isomorphism(self, other) noexcept + cpdef _is_isomorphism(self, other, morphism) noexcept + cdef bint __is_isomorphism(self, BasisExchangeMatroid other, morphism) noexcept + + cpdef is_valid(self) noexcept + +cdef bint nxksrd(bitset_s *b, long n, long k, bint succ) noexcept diff --git a/src/sage/matroids/basis_exchange_matroid.pyx b/src/sage/matroids/basis_exchange_matroid.pyx index fc902bc19c0..c27a8cba33d 100644 --- a/src/sage/matroids/basis_exchange_matroid.pyx +++ b/src/sage/matroids/basis_exchange_matroid.pyx @@ -191,7 +191,7 @@ cdef class BasisExchangeMatroid(Matroid): bitset_free(self._output) bitset_free(self._temp) - cdef _relabel(self, l): + cdef _relabel(self, l) noexcept: """ Relabel each element `e` as `l[e]`, where `l` is a given injective map. @@ -231,7 +231,7 @@ cdef class BasisExchangeMatroid(Matroid): self._heuristic_partition_var._relabel(l) # the engine - cdef _pack(self, bitset_t I, F): + cdef _pack(self, bitset_t I, F) noexcept: """ Encode a subset F of the groundset into a bitpacked set of integers """ @@ -239,7 +239,7 @@ cdef class BasisExchangeMatroid(Matroid): for f in F: bitset_add(I, self._idx[f]) - cdef __unpack(self, bitset_t I): + cdef __unpack(self, bitset_t I) noexcept: """ Unencode a bitpacked set of integers to a subset of the groundset. """ @@ -286,7 +286,7 @@ cdef class BasisExchangeMatroid(Matroid): y = bitset_next(Y, y + 1) x = bitset_next(X, x + 1) - cdef __fundamental_cocircuit(self, bitset_t C, long x): + cdef __fundamental_cocircuit(self, bitset_t C, long x) noexcept: """ Return the unique cocircuit that meets ``self._current_basis`` in exactly element ``x``. """ @@ -300,7 +300,7 @@ cdef class BasisExchangeMatroid(Matroid): y = bitset_next(self._temp, y + 1) bitset_add(C, x) - cdef __fundamental_circuit(self, bitset_t C, long y): + cdef __fundamental_circuit(self, bitset_t C, long y) noexcept: """ Return the unique circuit contained in ``self._current_basis`` union ``y``. """ @@ -313,7 +313,7 @@ cdef class BasisExchangeMatroid(Matroid): x = bitset_next(self._current_basis, x + 1) bitset_add(C, y) - cdef __max_independent(self, bitset_t R, bitset_t F): + cdef __max_independent(self, bitset_t R, bitset_t F) noexcept: """ Bitpacked version of ``max_independent``. """ @@ -322,7 +322,7 @@ cdef class BasisExchangeMatroid(Matroid): self._move(self._inside, self._outside) bitset_intersection(R, self._current_basis, F) - cdef __circuit(self, bitset_t R, bitset_t F): + cdef __circuit(self, bitset_t R, bitset_t F) noexcept: """ Bitpacked version of ``circuit``. """ @@ -349,7 +349,7 @@ cdef class BasisExchangeMatroid(Matroid): return y = bitset_next(self._outside, y + 1) - cdef __closure(self, bitset_t R, bitset_t F): + cdef __closure(self, bitset_t R, bitset_t F) noexcept: """ Bitpacked version of ``closure``. """ @@ -363,7 +363,7 @@ cdef class BasisExchangeMatroid(Matroid): bitset_difference(R, R, F) x = bitset_next(self._inside, x + 1) - cdef __max_coindependent(self, bitset_t R, bitset_t F): + cdef __max_coindependent(self, bitset_t R, bitset_t F) noexcept: """ Bitpacked version of ``max_coindependent``. """ @@ -373,7 +373,7 @@ cdef class BasisExchangeMatroid(Matroid): self._move(self._inside, self._outside) bitset_difference(R, F, self._current_basis) - cdef __cocircuit(self, bitset_t R, bitset_t F): + cdef __cocircuit(self, bitset_t R, bitset_t F) noexcept: """ Bitpacked version of ``cocircuit``. """ @@ -401,7 +401,7 @@ cdef class BasisExchangeMatroid(Matroid): return x = bitset_next(self._inside, x + 1) - cdef _coclosure_internal(self, bitset_t R, bitset_t F): + cdef _coclosure_internal(self, bitset_t R, bitset_t F) noexcept: """ Bitpacked version of ``closure``. """ @@ -416,7 +416,7 @@ cdef class BasisExchangeMatroid(Matroid): bitset_difference(R, R, F) y = bitset_next(self._outside, y + 1) - cdef __augment(self, bitset_t R, bitset_t X, bitset_t Y): + cdef __augment(self, bitset_t R, bitset_t X, bitset_t Y) noexcept: """ Bitpacked version of ``augment``. """ @@ -437,7 +437,7 @@ cdef class BasisExchangeMatroid(Matroid): self._move(self._inside, self._outside) return bitset_isempty(self._outside) - cdef __move_current_basis(self, bitset_t X, bitset_t Y): + cdef __move_current_basis(self, bitset_t X, bitset_t Y) noexcept: """ Bitpacked version of ``_move_current_basis``. """ @@ -450,7 +450,7 @@ cdef class BasisExchangeMatroid(Matroid): self._move(self._inside, self._outside) # functions for derived classes and for parent class - cdef bint _set_current_basis(self, F): + cdef bint _set_current_basis(self, F) noexcept: """ Set _current_basis to subset of the groundset ``F``. """ @@ -461,7 +461,7 @@ cdef class BasisExchangeMatroid(Matroid): return bitset_isempty(self._outside) and bitset_isempty(self._inside) # groundset and full_rank - cpdef groundset(self): + cpdef groundset(self) noexcept: """ Return the groundset of the matroid. @@ -479,7 +479,7 @@ cdef class BasisExchangeMatroid(Matroid): """ return self._groundset - cpdef groundset_list(self): + cpdef groundset_list(self) noexcept: """ Return a list of elements of the groundset of the matroid. @@ -525,7 +525,7 @@ cdef class BasisExchangeMatroid(Matroid): """ return self._groundset_size - cpdef full_rank(self): + cpdef full_rank(self) noexcept: r""" Return the rank of the matroid. @@ -546,7 +546,7 @@ cdef class BasisExchangeMatroid(Matroid): """ return self._matroid_rank - cpdef full_corank(self): + cpdef full_corank(self) noexcept: r""" Return the corank of the matroid. @@ -574,7 +574,7 @@ cdef class BasisExchangeMatroid(Matroid): # matroid oracles - cpdef basis(self): + cpdef basis(self) noexcept: r""" Return an arbitrary basis of the matroid. @@ -603,7 +603,7 @@ cdef class BasisExchangeMatroid(Matroid): """ return self.__unpack(self._current_basis) - cpdef _move_current_basis(self, X, Y): + cpdef _move_current_basis(self, X, Y) noexcept: """ Change current basis so that intersection with X is maximized, intersection with Y is minimized. @@ -634,7 +634,7 @@ cdef class BasisExchangeMatroid(Matroid): self._pack(self._input2, Y) self.__move_current_basis(self._input, self._input2) - cpdef _max_independent(self, F): + cpdef _max_independent(self, F) noexcept: """ Compute a maximal independent subset. @@ -665,7 +665,7 @@ cdef class BasisExchangeMatroid(Matroid): self.__max_independent(self._output, self._input) return self.__unpack(self._output) - cpdef _rank(self, F): + cpdef _rank(self, F) noexcept: """ Compute the rank of a subset of the ground set. @@ -696,7 +696,7 @@ cdef class BasisExchangeMatroid(Matroid): self.__max_independent(self._output, self._input) return bitset_len(self._output) - cpdef _circuit(self, F): + cpdef _circuit(self, F) noexcept: """ Return a minimal dependent subset. @@ -733,7 +733,7 @@ cdef class BasisExchangeMatroid(Matroid): self.__circuit(self._output, self._input) return self.__unpack(self._output) - cpdef _fundamental_circuit(self, B, e): + cpdef _fundamental_circuit(self, B, e) noexcept: r""" Return the `B`-fundamental circuit using `e`. @@ -760,7 +760,7 @@ cdef class BasisExchangeMatroid(Matroid): self.__fundamental_circuit(self._output, self._idx[e]) return self.__unpack(self._output) - cpdef _closure(self, F): + cpdef _closure(self, F) noexcept: """ Return the closure of a set. @@ -791,7 +791,7 @@ cdef class BasisExchangeMatroid(Matroid): self.__closure(self._output, self._input) return self.__unpack(self._output) - cpdef _max_coindependent(self, F): + cpdef _max_coindependent(self, F) noexcept: """ Compute a maximal coindependent subset. @@ -822,7 +822,7 @@ cdef class BasisExchangeMatroid(Matroid): self.__max_coindependent(self._output, self._input) return self.__unpack(self._output) - cpdef _corank(self, F): + cpdef _corank(self, F) noexcept: """ Return the corank of a set. @@ -852,7 +852,7 @@ cdef class BasisExchangeMatroid(Matroid): self.__max_coindependent(self._output, self._input) return bitset_len(self._output) - cpdef _cocircuit(self, F): + cpdef _cocircuit(self, F) noexcept: """ Return a minimal codependent subset. @@ -889,7 +889,7 @@ cdef class BasisExchangeMatroid(Matroid): self.__cocircuit(self._output, self._input) return self.__unpack(self._output) - cpdef _fundamental_cocircuit(self, B, e): + cpdef _fundamental_cocircuit(self, B, e) noexcept: r""" Return the `B`-fundamental circuit using `e`. @@ -916,7 +916,7 @@ cdef class BasisExchangeMatroid(Matroid): self.__fundamental_cocircuit(self._output, self._idx[e]) return self.__unpack(self._output) - cpdef _coclosure(self, F): + cpdef _coclosure(self, F) noexcept: """ Return the coclosure of a set. @@ -947,7 +947,7 @@ cdef class BasisExchangeMatroid(Matroid): self._coclosure_internal(self._output, self._input) return self.__unpack(self._output) - cpdef _augment(self, X, Y): + cpdef _augment(self, X, Y) noexcept: r""" Return a maximal subset `I` of `Y` such that `r(X + I)=r(X) + r(I)`. @@ -978,7 +978,7 @@ cdef class BasisExchangeMatroid(Matroid): self.__augment(self._output, self._input, self._input2) return self.__unpack(self._output) - cpdef _is_independent(self, F): + cpdef _is_independent(self, F) noexcept: """ Test if input is independent. @@ -1011,7 +1011,7 @@ cdef class BasisExchangeMatroid(Matroid): # connectivity - cpdef components(self): + cpdef components(self) noexcept: """ Return an iterable containing the components of the matroid. @@ -1095,7 +1095,7 @@ cdef class BasisExchangeMatroid(Matroid): sig_free(comp) return res - cpdef _link(self, S, T): + cpdef _link(self, S, T) noexcept: r""" Given disjoint subsets `S` and `T`, return a connector `I` and a separation `X`, which are optimal dual solutions in Tutte's Linking Theorem: @@ -1242,7 +1242,7 @@ cdef class BasisExchangeMatroid(Matroid): # enumeration - cpdef f_vector(self): + cpdef f_vector(self) noexcept: r""" Return the `f`-vector of the matroid. @@ -1283,7 +1283,7 @@ cdef class BasisExchangeMatroid(Matroid): sig_free(todo) return f_vec - cdef _f_vector_rec(self, object f_vec, bitset_t* flats, bitset_t* todo, long elt, long i): + cdef _f_vector_rec(self, object f_vec, bitset_t* flats, bitset_t* todo, long elt, long i) noexcept: """ Recursion for the f_vector method. """ @@ -1301,7 +1301,7 @@ cdef class BasisExchangeMatroid(Matroid): self._f_vector_rec(f_vec, flats, todo, e + 1, i + 1) e = bitset_next(todo[i], e) - cpdef flats(self, r): + cpdef flats(self, r) noexcept: """ Return the collection of flats of the matroid of specified rank. @@ -1356,7 +1356,7 @@ cdef class BasisExchangeMatroid(Matroid): sig_free(todo) return Rflats - cdef _flats_rec(self, SetSystem Rflats, long R, bitset_t* flats, bitset_t* todo, long elt, long i): + cdef _flats_rec(self, SetSystem Rflats, long R, bitset_t* flats, bitset_t* todo, long elt, long i) noexcept: """ Recursion for the ``flats`` method. """ @@ -1376,7 +1376,7 @@ cdef class BasisExchangeMatroid(Matroid): self._flats_rec(Rflats, R, flats, todo, e + 1, i + 1) e = bitset_next(todo[i], e) - cpdef coflats(self, r): + cpdef coflats(self, r) noexcept: """ Return the collection of coflats of the matroid of specified corank. @@ -1431,7 +1431,7 @@ cdef class BasisExchangeMatroid(Matroid): sig_free(todo) return Rcoflats - cdef _coflats_rec(self, SetSystem Rcoflats, long R, bitset_t* coflats, bitset_t* todo, long elt, long i): + cdef _coflats_rec(self, SetSystem Rcoflats, long R, bitset_t* coflats, bitset_t* todo, long elt, long i) noexcept: """ Recursion for the ``coflats`` method. """ @@ -1451,7 +1451,7 @@ cdef class BasisExchangeMatroid(Matroid): self._coflats_rec(Rcoflats, R, coflats, todo, e + 1, i + 1) e = bitset_next(todo[i], e) - cdef _flat_element_inv(self, long k): + cdef _flat_element_inv(self, long k) noexcept: """ Compute a flat-element invariant of the matroid. """ @@ -1486,7 +1486,7 @@ cdef class BasisExchangeMatroid(Matroid): f_vec = tuple([f_inc[i][self._groundset_size] for i in range(k + 1)]) return fie, f_vec - cdef _flat_element_inv_rec(self, object f_inc, long R, bitset_t* flats, bitset_t* todo, long elt, long i): + cdef _flat_element_inv_rec(self, object f_inc, long R, bitset_t* flats, bitset_t* todo, long elt, long i) noexcept: """ Recursion for ``_flat_element_inv``. """ @@ -1513,7 +1513,7 @@ cdef class BasisExchangeMatroid(Matroid): self._flat_element_inv_rec(f_inc, R, flats, todo, e + 1, i + 1) e = bitset_next(todo[i], e) - cpdef bases_count(self): + cpdef bases_count(self) noexcept: """ Return the number of bases of the matroid. @@ -1546,7 +1546,7 @@ cdef class BasisExchangeMatroid(Matroid): self._bcount = res return self._bcount - cpdef independent_sets(self): + cpdef independent_sets(self) noexcept: r""" Return the list of independent subsets of the matroid. @@ -1602,7 +1602,7 @@ cdef class BasisExchangeMatroid(Matroid): sig_free(T) return res - cpdef independent_r_sets(self, long r): + cpdef independent_r_sets(self, long r) noexcept: """ Return the list of size-``r`` independent subsets of the matroid. @@ -1637,7 +1637,7 @@ cdef class BasisExchangeMatroid(Matroid): repeat = nxksrd(self._input, self._groundset_size, r, True) return BB - cpdef bases(self): + cpdef bases(self) noexcept: """ Return the list of bases of the matroid. @@ -1657,7 +1657,7 @@ cdef class BasisExchangeMatroid(Matroid): """ return self.independent_r_sets(self.full_rank()) - cpdef dependent_r_sets(self, long r): + cpdef dependent_r_sets(self, long r) noexcept: """ Return the list of dependent subsets of fixed size. @@ -1697,7 +1697,7 @@ cdef class BasisExchangeMatroid(Matroid): NB.resize() return NB - cpdef nonbases(self): + cpdef nonbases(self) noexcept: """ Return the list of nonbases of the matroid. @@ -1722,7 +1722,7 @@ cdef class BasisExchangeMatroid(Matroid): """ return self.dependent_r_sets(self.full_rank()) - cpdef nonspanning_circuits(self): + cpdef nonspanning_circuits(self) noexcept: """ Return the list of nonspanning circuits of the matroid. @@ -1771,7 +1771,7 @@ cdef class BasisExchangeMatroid(Matroid): NSC.resize() return NSC - cpdef noncospanning_cocircuits(self): + cpdef noncospanning_cocircuits(self) noexcept: """ Return the list of noncospanning cocircuits of the matroid. @@ -1821,7 +1821,7 @@ cdef class BasisExchangeMatroid(Matroid): NSC.resize() return NSC - cpdef cocircuits(self): + cpdef cocircuits(self) noexcept: """ Return the list of cocircuits of the matroid. @@ -1869,7 +1869,7 @@ cdef class BasisExchangeMatroid(Matroid): NSC.resize() return NSC - cpdef circuits(self): + cpdef circuits(self) noexcept: """ Return the list of circuits of the matroid. @@ -1921,7 +1921,7 @@ cdef class BasisExchangeMatroid(Matroid): # isomorphism - cpdef _characteristic_setsystem(self): + cpdef _characteristic_setsystem(self) noexcept: r""" Return a characteristic set-system for this matroid, on the same ground set. @@ -1943,7 +1943,7 @@ cdef class BasisExchangeMatroid(Matroid): else: return self.noncospanning_cocircuits() - cpdef _weak_invariant(self): + cpdef _weak_invariant(self) noexcept: """ Return an isomorphism invariant of the matroid. @@ -1974,7 +1974,7 @@ cdef class BasisExchangeMatroid(Matroid): self._weak_partition_var = SetSystem(self._E, [fie[f] for f in sorted(fie)]) return self._weak_invariant_var - cpdef _weak_partition(self): + cpdef _weak_partition(self) noexcept: """ Return an ordered partition based on the incidences of elements with low-dimensional flats. @@ -1988,7 +1988,7 @@ cdef class BasisExchangeMatroid(Matroid): self._weak_invariant() return self._weak_partition_var - cpdef _strong_invariant(self): + cpdef _strong_invariant(self) noexcept: """ Return an isomorphism invariant of the matroid. @@ -2014,7 +2014,7 @@ cdef class BasisExchangeMatroid(Matroid): self._strong_invariant_var = CP[2] return self._strong_invariant_var - cpdef _strong_partition(self): + cpdef _strong_partition(self) noexcept: """ Return an equitable partition which refines _weak_partition(). @@ -2028,7 +2028,7 @@ cdef class BasisExchangeMatroid(Matroid): self._strong_invariant() return self._strong_partition_var - cpdef _heuristic_invariant(self): + cpdef _heuristic_invariant(self) noexcept: """ Return a number characteristic for the construction of _heuristic_partition(). @@ -2047,7 +2047,7 @@ cdef class BasisExchangeMatroid(Matroid): self._heuristic_invariant_var = CP[2] return self._heuristic_invariant_var - cpdef _heuristic_partition(self): + cpdef _heuristic_partition(self) noexcept: """ Return an ordered partition into singletons which refines an equitable partition of the matroid. @@ -2071,7 +2071,7 @@ cdef class BasisExchangeMatroid(Matroid): self._heuristic_invariant() return self._heuristic_partition_var - cdef _flush(self): + cdef _flush(self) noexcept: """ Delete all invariants. """ @@ -2079,7 +2079,7 @@ cdef class BasisExchangeMatroid(Matroid): self._strong_invariant_var = None self._heuristic_invariant_var = None - cpdef _equitable_partition(self, P=None): + cpdef _equitable_partition(self, P=None) noexcept: """ Return the equitable refinement of a given ordered partition. @@ -2110,7 +2110,7 @@ cdef class BasisExchangeMatroid(Matroid): EQ = self._characteristic_setsystem()._equitable_partition() return EQ[0] - cpdef _is_isomorphism(self, other, morphism): + cpdef _is_isomorphism(self, other, morphism) noexcept: r""" Version of is_isomorphism() that does no type checking. @@ -2157,7 +2157,7 @@ cdef class BasisExchangeMatroid(Matroid): ot = other return self.__is_isomorphism(ot, morphism) - cdef bint __is_isomorphism(self, BasisExchangeMatroid other, morphism): + cdef bint __is_isomorphism(self, BasisExchangeMatroid other, morphism) noexcept: """ Bitpacked version of ``is_isomorphism``. """ @@ -2177,7 +2177,7 @@ cdef class BasisExchangeMatroid(Matroid): repeat = nxksrd(self._input, self._groundset_size, self._matroid_rank, True) return True - cpdef _isomorphism(self, other): + cpdef _isomorphism(self, other) noexcept: """ Return an isomorphism form ``self`` to ``other``, if one exists. @@ -2265,7 +2265,7 @@ cdef class BasisExchangeMatroid(Matroid): return self._characteristic_setsystem()._isomorphism(other._characteristic_setsystem(), PS, PO) - cpdef _is_isomorphic(self, other, certificate=False): + cpdef _is_isomorphic(self, other, certificate=False) noexcept: """ Test if ``self`` is isomorphic to ``other``. @@ -2352,7 +2352,7 @@ cdef class BasisExchangeMatroid(Matroid): return self._characteristic_setsystem()._isomorphism(other._characteristic_setsystem(), PS, PO) is not None - cpdef is_valid(self): + cpdef is_valid(self) noexcept: r""" Test if the data obey the matroid axioms. @@ -2422,7 +2422,7 @@ cdef class BasisExchangeMatroid(Matroid): return True -cdef bint nxksrd(bitset_s* b, long n, long k, bint succ): +cdef bint nxksrd(bitset_s* b, long n, long k, bint succ) noexcept: """ Next size-k subset of a size-n set in a revolving-door sequence. diff --git a/src/sage/matroids/basis_matroid.pxd b/src/sage/matroids/basis_matroid.pxd index 6b3c0d27c9a..a4202bfedac 100644 --- a/src/sage/matroids/basis_matroid.pxd +++ b/src/sage/matroids/basis_matroid.pxd @@ -14,33 +14,33 @@ cdef class BasisMatroid(BasisExchangeMatroid): cdef _bases_invariant3_var cdef SetSystem _bases_partition3_var - cdef reset_current_basis(self) - - cpdef _is_basis(self, X) - - cpdef bases_count(self) - cpdef bases(self) - cpdef nonbases(self) - - cpdef truncation(self) - cpdef _extension(self, e, H) - cpdef _with_coloop(self, e) - cpdef relabel(self, l) - - cpdef _bases_invariant(self) - cpdef _bases_partition(self) - cpdef _bases_invariant2(self) - cpdef _bases_partition2(self) - cpdef _bases_invariant3(self) - cpdef _bases_partition3(self) - cdef _reset_invariants(self) - cpdef bint is_distinguished(self, e) - cpdef _is_relaxation(self, M, morphism) - cpdef _is_isomorphism(self, M, morphism) - cpdef _isomorphism(self, other) - cpdef _is_isomorphic(self, other, certificate=*) - - -cdef binom_init(long n, long k) -cdef long set_to_index(bitset_t S) -cdef index_to_set(bitset_t, long, long, long) + cdef reset_current_basis(self) noexcept + + cpdef _is_basis(self, X) noexcept + + cpdef bases_count(self) noexcept + cpdef bases(self) noexcept + cpdef nonbases(self) noexcept + + cpdef truncation(self) noexcept + cpdef _extension(self, e, H) noexcept + cpdef _with_coloop(self, e) noexcept + cpdef relabel(self, l) noexcept + + cpdef _bases_invariant(self) noexcept + cpdef _bases_partition(self) noexcept + cpdef _bases_invariant2(self) noexcept + cpdef _bases_partition2(self) noexcept + cpdef _bases_invariant3(self) noexcept + cpdef _bases_partition3(self) noexcept + cdef _reset_invariants(self) noexcept + cpdef bint is_distinguished(self, e) noexcept + cpdef _is_relaxation(self, M, morphism) noexcept + cpdef _is_isomorphism(self, M, morphism) noexcept + cpdef _isomorphism(self, other) noexcept + cpdef _is_isomorphic(self, other, certificate=*) noexcept + + +cdef binom_init(long n, long k) noexcept +cdef long set_to_index(bitset_t S) noexcept +cdef index_to_set(bitset_t, long, long, long) noexcept diff --git a/src/sage/matroids/basis_matroid.pyx b/src/sage/matroids/basis_matroid.pyx index 6dff6506981..93cf56ec60c 100644 --- a/src/sage/matroids/basis_matroid.pyx +++ b/src/sage/matroids/basis_matroid.pyx @@ -290,7 +290,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): bitset_add(self._b, y) return bitset_in(self._bb, set_to_index(self._b)) - cdef reset_current_basis(self): + cdef reset_current_basis(self) noexcept: """ Set the current basis to the (lexicographically) first basis of the matroid. @@ -299,7 +299,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): # a function that is very efficient for this class - cpdef _is_basis(self, X): + cpdef _is_basis(self, X) noexcept: """ Test if input is a basis. @@ -331,7 +331,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): # dual and minors - cpdef dual(self): + cpdef dual(self) noexcept: r""" Return the dual of the matroid. @@ -372,7 +372,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): D._bcount = self._bcount return D - cpdef _minor(self, contractions, deletions): + cpdef _minor(self, contractions, deletions) noexcept: """ Return a minor. @@ -409,7 +409,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): NB = [frozenset(B) for B in combinations(E, mr) if not self._is_basis(contractions | frozenset(B))] return BasisMatroid(groundset=E, nonbases=NB, rank=mr) - cpdef truncation(self): + cpdef truncation(self) noexcept: r""" Return a rank-1 truncation of the matroid. @@ -442,7 +442,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): return None return BasisMatroid(groundset=self._E, nonbases=self.dependent_r_sets(self.full_rank() - 1), rank=self.full_rank() - 1) - cpdef _extension(self, e, H): + cpdef _extension(self, e, H) noexcept: r""" Extend the matroid by a new element. @@ -494,7 +494,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): BE += BB return BasisMatroid(groundset=self._E + (e,), bases=BE) - cpdef _with_coloop(self, e): + cpdef _with_coloop(self, e) noexcept: r""" Return the matroid that arises by adding an element `e` to the groundset, that is a coloop of the resulting matroid. @@ -521,7 +521,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): cdef frozenset se = frozenset([e]) return BasisMatroid(groundset=self._E + (e,), bases=[B | se for B in self.bases()]) - cpdef relabel(self, l): + cpdef relabel(self, l) noexcept: """ Return an isomorphic matroid with relabeled groundset. @@ -562,7 +562,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): # enumeration - cpdef bases_count(self): + cpdef bases_count(self) noexcept: r""" Return the number of bases of the matroid. @@ -582,7 +582,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): self._bcount = bitset_len(self._bb) return self._bcount - cpdef bases(self): + cpdef bases(self) noexcept: r""" Return the list of bases of the matroid. @@ -613,7 +613,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): b = bitset_next(self._bb, b + 1) return BB - cpdef nonbases(self): + cpdef nonbases(self) noexcept: r""" Return the list of nonbases of the matroid. @@ -658,7 +658,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): # isomorphism test - cpdef _bases_invariant(self): + cpdef _bases_invariant(self) noexcept: """ Return an isomorphism invariant based on the incidences of groundset elements with bases. @@ -702,7 +702,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): self._bases_partition_var = SetSystem(self._E, [[self._E[e] for e in bi[c]] for c in sorted(bi)]) return self._bases_invariant_var - cpdef _bases_partition(self): + cpdef _bases_partition(self) noexcept: """ Return an ordered partition based on the incidences of groundset elements with bases. @@ -717,7 +717,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): self._bases_invariant() return self._bases_partition_var - cpdef _bases_invariant2(self): + cpdef _bases_invariant2(self) noexcept: """ Return an isomorphism invariant of the matroid. @@ -744,7 +744,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): self._bases_invariant2_var = CP[2] return self._bases_invariant2_var - cpdef _bases_partition2(self): + cpdef _bases_partition2(self) noexcept: """ Return an equitable partition which refines :meth:``. @@ -759,7 +759,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): self._bases_invariant2() return self._bases_partition2_var - cpdef _bases_invariant3(self): + cpdef _bases_invariant3(self) noexcept: """ Return a number characteristic for the construction of :meth:``. @@ -778,7 +778,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): self._bases_invariant3_var = CP[2] return self._bases_invariant3_var - cpdef _bases_partition3(self): + cpdef _bases_partition3(self) noexcept: """ Return an ordered partition into singletons which refines an equitable partition of the matroid. @@ -802,7 +802,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): self._bases_invariant3() return self._bases_partition3_var - cdef _reset_invariants(self): + cdef _reset_invariants(self) noexcept: """ Remove all precomputed invariants. """ @@ -816,7 +816,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): self._bases_partition3_var = None self._flush() - cpdef bint is_distinguished(self, e): + cpdef bint is_distinguished(self, e) noexcept: """ Return whether ``e`` is a 'distinguished' element of the groundset. @@ -863,7 +863,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): q = q2 return e in q - cpdef _is_relaxation(self, other, morphism): + cpdef _is_relaxation(self, other, morphism) noexcept: """ Return if the application of a groundset morphism to this matroid yields a relaxation of the given matroid. @@ -923,7 +923,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): bitset_free(bb_comp) return True - cpdef _is_isomorphism(self, other, morphism): + cpdef _is_isomorphism(self, other, morphism) noexcept: """ Version of :meth:`is_isomorphism` that does no type checking. @@ -961,7 +961,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): ot = other return self.bases_count() == (ot).bases_count() and self._is_relaxation(ot, morphism) - cpdef _isomorphism(self, other): + cpdef _isomorphism(self, other) noexcept: """ Return isomorphism from ``self`` to ``other``, if one exists. @@ -1040,7 +1040,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): return self.nonbases()._isomorphism(other.nonbases(), PS, PO) - cpdef _is_isomorphic(self, other, certificate=False): + cpdef _is_isomorphic(self, other, certificate=False) noexcept: """ Return if this matroid is isomorphic to the given matroid. @@ -1244,7 +1244,7 @@ cdef class BasisMatroid(BasisExchangeMatroid): cdef long binom[2956][33] # Cached binomial table -cdef binom_init(long N, long K): +cdef binom_init(long N, long K) noexcept: """ Fill up the cached binomial table. """ @@ -1270,7 +1270,7 @@ cdef binom_init(long N, long K): if binom[N][K] == 0: raise ValueError("BasisMatroid: number of potential bases would exceed 2^32") -cdef long set_to_index(bitset_t S): +cdef long set_to_index(bitset_t S) noexcept: """ Compute the rank of a set of integers amongst the sets of integers of the same cardinality. @@ -1286,7 +1286,7 @@ cdef long set_to_index(bitset_t S): return index -cdef index_to_set(bitset_t S, long index, long k, long n): +cdef index_to_set(bitset_t S, long index, long k, long n) noexcept: r""" Compute the k-subset of `\{0, ..., n-1\}` of rank index """ diff --git a/src/sage/matroids/circuit_closures_matroid.pxd b/src/sage/matroids/circuit_closures_matroid.pxd index e2c4afdaff9..1ec965db0fe 100644 --- a/src/sage/matroids/circuit_closures_matroid.pxd +++ b/src/sage/matroids/circuit_closures_matroid.pxd @@ -4,11 +4,11 @@ cdef class CircuitClosuresMatroid(Matroid): cdef frozenset _groundset # _E cdef dict _circuit_closures # _CC cdef int _matroid_rank # _R - cpdef groundset(self) - cpdef _rank(self, X) - cpdef full_rank(self) - cpdef _is_independent(self, F) - cpdef _max_independent(self, F) - cpdef _circuit(self, F) - cpdef circuit_closures(self) - cpdef _is_isomorphic(self, other, certificate=*) + cpdef groundset(self) noexcept + cpdef _rank(self, X) noexcept + cpdef full_rank(self) noexcept + cpdef _is_independent(self, F) noexcept + cpdef _max_independent(self, F) noexcept + cpdef _circuit(self, F) noexcept + cpdef circuit_closures(self) noexcept + cpdef _is_isomorphic(self, other, certificate=*) noexcept diff --git a/src/sage/matroids/circuit_closures_matroid.pyx b/src/sage/matroids/circuit_closures_matroid.pyx index 4e79b0575e2..1fc11f0c344 100644 --- a/src/sage/matroids/circuit_closures_matroid.pyx +++ b/src/sage/matroids/circuit_closures_matroid.pyx @@ -165,7 +165,7 @@ cdef class CircuitClosuresMatroid(Matroid): self._circuit_closures[k] = frozenset([frozenset(X) for X in circuit_closures[k]]) self._matroid_rank = self.rank(self._groundset) - cpdef groundset(self): + cpdef groundset(self) noexcept: """ Return the groundset of the matroid. @@ -183,7 +183,7 @@ cdef class CircuitClosuresMatroid(Matroid): """ return frozenset(self._groundset) - cpdef _rank(self, X): + cpdef _rank(self, X) noexcept: """ Return the rank of a set ``X``. @@ -207,7 +207,7 @@ cdef class CircuitClosuresMatroid(Matroid): return len(self._max_independent(X)) # OPTIONAL, OPTIMIZED FOR THIS CLASS - cpdef full_rank(self): + cpdef full_rank(self) noexcept: r""" Return the rank of the matroid. @@ -228,7 +228,7 @@ cdef class CircuitClosuresMatroid(Matroid): """ return self._matroid_rank - cpdef _is_independent(self, F): + cpdef _is_independent(self, F) noexcept: """ Test if input is independent. @@ -259,7 +259,7 @@ cdef class CircuitClosuresMatroid(Matroid): return False return True - cpdef _max_independent(self, F): + cpdef _max_independent(self, F) noexcept: """ Compute a maximal independent subset. @@ -296,7 +296,7 @@ cdef class CircuitClosuresMatroid(Matroid): return frozenset(I) - cpdef _circuit(self, F): + cpdef _circuit(self, F) noexcept: """ Return a minimal dependent subset. @@ -329,7 +329,7 @@ cdef class CircuitClosuresMatroid(Matroid): return frozenset(S) raise ValueError("no circuit in independent set") - cpdef circuit_closures(self): + cpdef circuit_closures(self) noexcept: """ Return the list of closures of circuits of the matroid. @@ -363,7 +363,7 @@ cdef class CircuitClosuresMatroid(Matroid): """ return self._circuit_closures - cpdef _is_isomorphic(self, other, certificate=False): + cpdef _is_isomorphic(self, other, certificate=False) noexcept: """ Test if ``self`` is isomorphic to ``other``. diff --git a/src/sage/matroids/extension.pxd b/src/sage/matroids/extension.pxd index 1d44f460c52..34d813eeb7c 100644 --- a/src/sage/matroids/extension.pxd +++ b/src/sage/matroids/extension.pxd @@ -6,12 +6,12 @@ cdef class CutNode: cdef bitset_t _p_free, _p_in, _l0, _l1 cdef long _ml - cdef CutNode copy(self) - cdef bint insert_plane(self, long p0) - cdef bint remove_plane(self, long p0) - cdef select_plane(self) + cdef CutNode copy(self) noexcept + cdef bint insert_plane(self, long p0) noexcept + cdef bint remove_plane(self, long p0) noexcept + cdef select_plane(self) noexcept - cdef list planes(self) + cdef list planes(self) noexcept cdef class LinearSubclassesIter: cdef LinearSubclasses _MC diff --git a/src/sage/matroids/extension.pyx b/src/sage/matroids/extension.pyx index 1f2cb38a65c..061ba37089e 100644 --- a/src/sage/matroids/extension.pyx +++ b/src/sage/matroids/extension.pyx @@ -87,10 +87,10 @@ cdef class CutNode: bitset_free(self._l0) bitset_free(self._l1) - cdef CutNode copy(self): + cdef CutNode copy(self) noexcept: return CutNode(self._MC, self) - cdef bint insert_plane(self, long p0): + cdef bint insert_plane(self, long p0) noexcept: """ Add a hyperplane to the linear subclass. """ @@ -128,7 +128,7 @@ cdef class CutNode: return False return True - cdef bint remove_plane(self, long p0): + cdef bint remove_plane(self, long p0) noexcept: """ Remove a hyperplane from the linear subclass. """ @@ -153,7 +153,7 @@ cdef class CutNode: return False return True - cdef select_plane(self): + cdef select_plane(self) noexcept: """ Choose a hyperplane from the linear subclass. """ @@ -169,7 +169,7 @@ cdef class CutNode: return bitset_first(self._p_free) - cdef list planes(self): + cdef list planes(self) noexcept: """ Return all hyperplanes from the linear subclass. """ diff --git a/src/sage/matroids/lean_matrix.pxd b/src/sage/matroids/lean_matrix.pxd index 3512bcfce31..f71e22f63ee 100644 --- a/src/sage/matroids/lean_matrix.pxd +++ b/src/sage/matroids/lean_matrix.pxd @@ -5,18 +5,18 @@ cdef class LeanMatrix: cdef long _nrows cdef long _ncols - cdef LeanMatrix copy(self) # Deprecated Sage matrix operation + cdef LeanMatrix copy(self) noexcept # Deprecated Sage matrix operation cdef int resize(self, long k) except -1 # Not a Sage matrix operation - cdef LeanMatrix stack(self, LeanMatrix M) - cdef LeanMatrix augment(self, LeanMatrix M) - cdef LeanMatrix prepend_identity(self) # Not a Sage matrix operation + cdef LeanMatrix stack(self, LeanMatrix M) noexcept + cdef LeanMatrix augment(self, LeanMatrix M) noexcept + cdef LeanMatrix prepend_identity(self) noexcept # Not a Sage matrix operation cpdef long ncols(self) except -1 cpdef long nrows(self) except -1 - cpdef base_ring(self) - cpdef characteristic(self) # Not a Sage matrix operation + cpdef base_ring(self) noexcept + cpdef characteristic(self) noexcept # Not a Sage matrix operation - cdef get_unsafe(self, long r, long c) + cdef get_unsafe(self, long r, long c) noexcept cdef int set_unsafe(self, long r, long c, x) except -1 cdef bint is_nonzero(self, long r, long c) except -2 # Not a Sage matrix operation @@ -25,16 +25,16 @@ cdef class LeanMatrix: cdef int rescale_row_c(self, long x, s, bint col_start) except -1 cdef int rescale_column_c(self, long y, s, bint start_row) except -1 cdef int pivot(self, long x, long y) except -1 # Not a Sage matrix operation - cdef list gauss_jordan_reduce(self, columns) # Not a Sage matrix operation + cdef list gauss_jordan_reduce(self, columns) noexcept # Not a Sage matrix operation - cdef list nonzero_positions_in_row(self, long r) + cdef list nonzero_positions_in_row(self, long r) noexcept - cdef LeanMatrix transpose(self) - cdef LeanMatrix _matrix_times_matrix_(self, LeanMatrix other) - cdef LeanMatrix matrix_from_rows_and_columns(self, rows, columns) + cdef LeanMatrix transpose(self) noexcept + cdef LeanMatrix _matrix_times_matrix_(self, LeanMatrix other) noexcept + cdef LeanMatrix matrix_from_rows_and_columns(self, rows, columns) noexcept - cdef shifting_all(self, P_rows, P_cols, Q_rows, Q_cols, int m) - cdef shifting(self, U_1, V_2, U_2, V_1, z2, z1, int m) + cdef shifting_all(self, P_rows, P_cols, Q_rows, Q_cols, int m) noexcept + cdef shifting(self, U_1, V_2, U_2, V_1, z2, z1, int m) noexcept cdef class GenericMatrix(LeanMatrix): cdef _base_ring, _characteristic @@ -42,29 +42,29 @@ cdef class GenericMatrix(LeanMatrix): cdef _zero cdef _one - cdef inline row_inner_product(self, long i, long j) # Not a Sage matrix operation + cdef inline row_inner_product(self, long i, long j) noexcept # Not a Sage matrix operation cdef class BinaryMatrix(LeanMatrix): cdef bitset_t* _M cdef bitset_t _temp cdef inline long row_len(self, long i) except -1 # Not a Sage matrix operation - cdef inline bint row_inner_product(self, long i, long j) # Not a Sage matrix operation + cdef inline bint row_inner_product(self, long i, long j) noexcept # Not a Sage matrix operation - cdef inline bint get(self, long x, long y) # Not a Sage matrix operation - cdef inline void set(self, long x, long y) # Not a Sage matrix operation + cdef inline bint get(self, long x, long y) noexcept # Not a Sage matrix operation + cdef inline void set(self, long x, long y) noexcept # Not a Sage matrix operation - cdef inline list row_sum(self, object L) # Not a Sage matrix operation - cdef inline list row_union(self, object L) # Not a Sage matrix operation + cdef inline list row_sum(self, object L) noexcept # Not a Sage matrix operation + cdef inline list row_union(self, object L) noexcept # Not a Sage matrix operation - cdef LeanMatrix matrix_from_rows_and_columns(self, rows, columns) - cdef matrix_from_rows_and_columns_reordered(self, rows, columns) + cdef LeanMatrix matrix_from_rows_and_columns(self, rows, columns) noexcept + cdef matrix_from_rows_and_columns_reordered(self, rows, columns) noexcept - cdef list _character(self, bitset_t x) - cdef BinaryMatrix _distinguish_by(self, BinaryMatrix P) - cdef BinaryMatrix _splice_by(self, BinaryMatrix P) - cdef BinaryMatrix _isolate(self, long r) - cdef BinaryMatrix equitable_partition(self, BinaryMatrix P=*) # Not a Sage matrix operation + cdef list _character(self, bitset_t x) noexcept + cdef BinaryMatrix _distinguish_by(self, BinaryMatrix P) noexcept + cdef BinaryMatrix _splice_by(self, BinaryMatrix P) noexcept + cdef BinaryMatrix _isolate(self, long r) noexcept + cdef BinaryMatrix equitable_partition(self, BinaryMatrix P=*) noexcept # Not a Sage matrix operation cdef bint is_isomorphic(self, BinaryMatrix other, BinaryMatrix s_eq=*, BinaryMatrix o_eq=*) except -2 # Not a Sage matrix operation @@ -73,16 +73,16 @@ cdef class TernaryMatrix(LeanMatrix): cdef bitset_t *_M1 # _M1[i] = negative support of row i cdef bitset_t _s, _t, _u # registers - cdef inline long get(self, long r, long c) # Not a Sage matrix operation + cdef inline long get(self, long r, long c) noexcept # Not a Sage matrix operation cdef inline int set(self, long r, long c, x) except -1 # Not a Sage matrix operation - cdef bint _is_negative(self, long r, long c) + cdef bint _is_negative(self, long r, long c) noexcept - cdef inline long row_len(self, long i) # Not a Sage matrix operation - cdef inline long row_inner_product(self, long i, long j) # Not a Sage matrix operation - cdef void row_subs(self, long x, long y) # Not a Sage matrix operation - cdef void _row_negate(self, long x) - cdef matrix_from_rows_and_columns_reordered(self, rows, columns) + cdef inline long row_len(self, long i) noexcept # Not a Sage matrix operation + cdef inline long row_inner_product(self, long i, long j) noexcept # Not a Sage matrix operation + cdef void row_subs(self, long x, long y) noexcept # Not a Sage matrix operation + cdef void _row_negate(self, long x) noexcept + cdef matrix_from_rows_and_columns_reordered(self, rows, columns) noexcept cdef class QuaternaryMatrix(LeanMatrix): cdef bitset_t *_M0 # _M0[i] = 1-support of row i @@ -90,36 +90,36 @@ cdef class QuaternaryMatrix(LeanMatrix): cdef bitset_t _s, _t, _u # registers cdef object _gf4, _zero, _one, _x_zero, _x_one - cdef inline get(self, long r, long c) # Not a Sage matrix operation + cdef inline get(self, long r, long c) noexcept # Not a Sage matrix operation cdef inline int set(self, long r, long c, x) except -1 # Not a Sage matrix operation cdef inline long row_len(self, long i) except -1 # Not a Sage matrix operation - cdef inline row_inner_product(self, long i, long j) # Not a Sage matrix operation + cdef inline row_inner_product(self, long i, long j) noexcept # Not a Sage matrix operation cdef inline int _row_div(self, long x, object s) except -1 - cdef matrix_from_rows_and_columns_reordered(self, rows, columns) - cdef void conjugate(self) # Not a Sage matrix operation + cdef matrix_from_rows_and_columns_reordered(self, rows, columns) noexcept + cdef void conjugate(self) noexcept # Not a Sage matrix operation cdef class PlusMinusOneMatrix(LeanMatrix): cdef int* _entries - cdef inline int get(self, long r, long c) # Not a Sage matrix operation - cdef inline void set(self, long r, long c, int x) # Not a Sage matrix operation + cdef inline int get(self, long r, long c) noexcept # Not a Sage matrix operation + cdef inline void set(self, long r, long c, int x) noexcept # Not a Sage matrix operation cdef inline long row_len(self, long i) except -1 # Not a Sage matrix operation - cdef inline row_inner_product(self, long i, long j) # Not a Sage matrix operation + cdef inline row_inner_product(self, long i, long j) noexcept # Not a Sage matrix operation cdef class RationalMatrix(LeanMatrix): cdef mpq_t* _entries - cdef inline long index(self, long r, long c) # Not a Sage matrix operation - cdef inline void set(self, long r, long c, mpq_t x) # Not a Sage matrix operation + cdef inline long index(self, long r, long c) noexcept # Not a Sage matrix operation + cdef inline void set(self, long r, long c, mpq_t x) noexcept # Not a Sage matrix operation cdef inline long row_len(self, long i) except -1 # Not a Sage matrix operation - cdef inline row_inner_product(self, long i, long j) # Not a Sage matrix operation + cdef inline row_inner_product(self, long i, long j) noexcept # Not a Sage matrix operation cdef int add_multiple_of_row_mpq(self, long x, long y, mpq_t s, bint col_start) except -1 cdef int rescale_row_mpq(self, long x, mpq_t s, bint col_start) except -1 cdef int rescale_column_mpq(self, long y, mpq_t s, bint start_row) except -1 -cpdef GenericMatrix generic_identity(n, ring) +cpdef GenericMatrix generic_identity(n, ring) noexcept diff --git a/src/sage/matroids/lean_matrix.pyx b/src/sage/matroids/lean_matrix.pyx index a137cbf70e5..740864af9ce 100644 --- a/src/sage/matroids/lean_matrix.pyx +++ b/src/sage/matroids/lean_matrix.pyx @@ -112,7 +112,7 @@ cdef class LeanMatrix: M[r, c] = self.get_unsafe(r, c) return M - cdef LeanMatrix copy(self): # Deprecated Sage matrix operation + cdef LeanMatrix copy(self) noexcept: # Deprecated Sage matrix operation """ Make a copy of ``self``. """ @@ -125,7 +125,7 @@ cdef class LeanMatrix: """ raise NotImplementedError - cdef LeanMatrix stack(self, LeanMatrix M): + cdef LeanMatrix stack(self, LeanMatrix M) noexcept: """ Stack ``self`` on top of ``M``. Assumes ``self`` and ``M`` are of same type, and compatible dimensions. @@ -142,7 +142,7 @@ cdef class LeanMatrix: A.set_unsafe(i + sr, j, M.get_unsafe(i, j)) return A - cdef LeanMatrix augment(self, LeanMatrix M): + cdef LeanMatrix augment(self, LeanMatrix M) noexcept: """ Concatenates ``self`` with ``M``, placing ``M`` to the right of ``self``. Assumes ``self`` and ``M`` are of same type, and compatible @@ -159,7 +159,7 @@ cdef class LeanMatrix: A.set_unsafe(i, j + sc, M.get_unsafe(i, j)) return A - cdef LeanMatrix prepend_identity(self): # Not a Sage matrix operation + cdef LeanMatrix prepend_identity(self) noexcept: # Not a Sage matrix operation """ Return the matrix obtained by prepending an identity matrix. Special case of ``augment``. @@ -198,7 +198,7 @@ cdef class LeanMatrix: """ return self._nrows - cpdef base_ring(self): + cpdef base_ring(self) noexcept: """ Return the base ring. @@ -213,7 +213,7 @@ cdef class LeanMatrix: """ raise NotImplementedError("subclasses need to implement this.") - cpdef characteristic(self): + cpdef characteristic(self) noexcept: """ Return the characteristic of ``self.base_ring()``. @@ -226,7 +226,7 @@ cdef class LeanMatrix: """ return self.base_ring().characteristic() - cdef get_unsafe(self, long r, long c): + cdef get_unsafe(self, long r, long c) noexcept: """ Return the value in row ``r``, column ``c``. """ @@ -310,7 +310,7 @@ cdef class LeanMatrix: self.add_multiple_of_row_c(i, x, -s, 0) return 0 - cdef list gauss_jordan_reduce(self, columns): # Not a Sage matrix operation + cdef list gauss_jordan_reduce(self, columns) noexcept: # Not a Sage matrix operation """ Row-reduce so the lexicographically first basis indexes an identity submatrix. @@ -335,13 +335,13 @@ cdef class LeanMatrix: break return P - cdef list nonzero_positions_in_row(self, long r): + cdef list nonzero_positions_in_row(self, long r) noexcept: """ Get coordinates of nonzero entries of row ``r``. """ return [i for i in range(self._ncols) if self.is_nonzero(r, i)] - cdef LeanMatrix transpose(self): + cdef LeanMatrix transpose(self) noexcept: """ Return the transpose of the matrix. """ @@ -352,7 +352,7 @@ cdef class LeanMatrix: A.set_unsafe(j, i, self.get_unsafe(i, j)) return A - cdef LeanMatrix _matrix_times_matrix_(self, LeanMatrix other): + cdef LeanMatrix _matrix_times_matrix_(self, LeanMatrix other) noexcept: """ Multiply two matrices. Assumes ``self`` and ``M`` are of same type, and compatible dimensions. @@ -365,7 +365,7 @@ cdef class LeanMatrix: A.set_unsafe(i, j, self.get_unsafe(i, k) * other.get_unsafe(k, j)) return A - cdef LeanMatrix matrix_from_rows_and_columns(self, rows, columns): + cdef LeanMatrix matrix_from_rows_and_columns(self, rows, columns) noexcept: """ Return submatrix indexed by indicated rows and columns. """ @@ -518,7 +518,7 @@ cdef class LeanMatrix: """ raise NotImplementedError("subclasses need to implement this.") - cdef shifting_all(self, P_rows, P_cols, Q_rows, Q_cols, int m): + cdef shifting_all(self, P_rows, P_cols, Q_rows, Q_cols, int m) noexcept: r""" Given a partial matrix `M`. If the submatrix `M` using rows `P_rows` columns `P_cols` and submatrix using rows `Q_rows` columns @@ -562,7 +562,7 @@ cdef class LeanMatrix: return True, cert return False, None - cdef shifting(self, U_1, V_2, U_2, V_1, z2, z1, int m): + cdef shifting(self, U_1, V_2, U_2, V_1, z2, z1, int m) noexcept: r""" Let `E_1` be the submatrix using rows `U_1` and columns `V_2` with optional column `z2` attached. @@ -760,7 +760,7 @@ cdef class GenericMatrix(LeanMatrix): """ return "LeanMatrix instance with " + str(self._nrows) + " rows and " + str(self._ncols) + " columns over " + repr(self._base_ring) - cdef LeanMatrix copy(self): # Deprecated Sage matrix operation + cdef LeanMatrix copy(self) noexcept: # Deprecated Sage matrix operation cdef GenericMatrix M = GenericMatrix(self._nrows, self._ncols, M=self) return M @@ -776,7 +776,7 @@ cdef class GenericMatrix(LeanMatrix): self._nrows = k return 0 - cdef LeanMatrix stack(self, LeanMatrix M): + cdef LeanMatrix stack(self, LeanMatrix M) noexcept: """ Warning: assumes ``M`` is a GenericMatrix instance! """ @@ -787,7 +787,7 @@ cdef class GenericMatrix(LeanMatrix): A._ncols = self._ncols return A - cdef LeanMatrix augment(self, LeanMatrix M): + cdef LeanMatrix augment(self, LeanMatrix M) noexcept: """ Warning: assumes ``M`` is a GenericMatrix instance! """ @@ -800,14 +800,14 @@ cdef class GenericMatrix(LeanMatrix): A._entries[i * A._ncols + self._ncols:(i + 1) * A._ncols]=(M)._entries[i * Mn:(i + 1) * Mn] return A - cdef LeanMatrix prepend_identity(self): # Not a Sage matrix operation + cdef LeanMatrix prepend_identity(self) noexcept: # Not a Sage matrix operation cdef GenericMatrix A = GenericMatrix(self._nrows, self._ncols + self._nrows, ring=self._base_ring) for i in range(self._nrows): A._entries[i * A._ncols + i] = self._one A._entries[i * A._ncols + self._nrows:(i + 1) * A._ncols]=self._entries[i * self._ncols:(i + 1) * self._ncols] return A - cpdef base_ring(self): + cpdef base_ring(self) noexcept: """ Return the base ring of ``self``. @@ -820,7 +820,7 @@ cdef class GenericMatrix(LeanMatrix): """ return self._base_ring - cpdef characteristic(self): + cpdef characteristic(self) noexcept: """ Return the characteristic of ``self.base_ring()``. @@ -835,7 +835,7 @@ cdef class GenericMatrix(LeanMatrix): self._characteristic = self._base_ring.characteristic() return self._characteristic - cdef get_unsafe(self, long r, long c): + cdef get_unsafe(self, long r, long c) noexcept: return self._entries[r * self._ncols + c] cdef int set_unsafe(self, long r, long c, x) except -1: @@ -851,7 +851,7 @@ cdef class GenericMatrix(LeanMatrix): self._entries[y * self._ncols:(y + 1) * self._ncols] = tmp return 0 - cdef LeanMatrix transpose(self): + cdef LeanMatrix transpose(self) noexcept: """ Return the transpose of the matrix. """ @@ -863,7 +863,7 @@ cdef class GenericMatrix(LeanMatrix): A.set_unsafe(j, i, self.get_unsafe(i, j)) return A - cdef inline row_inner_product(self, long i, long j): # Not a Sage matrix operation + cdef inline row_inner_product(self, long i, long j) noexcept: # Not a Sage matrix operation """ Return the inner product between rows ``i`` and ``j``. """ @@ -877,7 +877,7 @@ cdef class GenericMatrix(LeanMatrix): res += x * y return res - cdef LeanMatrix _matrix_times_matrix_(self, LeanMatrix other): + cdef LeanMatrix _matrix_times_matrix_(self, LeanMatrix other) noexcept: """ Return the product ``self * other``. """ @@ -1084,7 +1084,7 @@ cdef class BinaryMatrix(LeanMatrix): M[i, j] = 1 return M - cdef LeanMatrix copy(self): # Deprecated Sage matrix operation + cdef LeanMatrix copy(self) noexcept: # Deprecated Sage matrix operation cdef BinaryMatrix B cdef long i B = BinaryMatrix(self.nrows(), self.ncols()) @@ -1111,7 +1111,7 @@ cdef class BinaryMatrix(LeanMatrix): self._nrows = k return 0 - cdef LeanMatrix stack(self, LeanMatrix MM): + cdef LeanMatrix stack(self, LeanMatrix MM) noexcept: """ Given ``A`` and ``B``, return [A] @@ -1125,7 +1125,7 @@ cdef class BinaryMatrix(LeanMatrix): bitset_copy(R._M[i + self.nrows()], M._M[i]) return R - cdef LeanMatrix augment(self, LeanMatrix MM): + cdef LeanMatrix augment(self, LeanMatrix MM) noexcept: """ Given ``A`` and ``B``, return [A B] @@ -1139,7 +1139,7 @@ cdef class BinaryMatrix(LeanMatrix): bitset_set_to(R._M[i], self.ncols() + j, bitset_in(M._M[i], j)) return R - cdef LeanMatrix prepend_identity(self): # Not a Sage matrix operation + cdef LeanMatrix prepend_identity(self) noexcept: # Not a Sage matrix operation """ Return the matrix obtained by prepending an identity matrix. Special case of ``augment``. """ @@ -1150,7 +1150,7 @@ cdef class BinaryMatrix(LeanMatrix): A.set(i, i) return A - cpdef base_ring(self): + cpdef base_ring(self) noexcept: """ Return `GF(2)`. @@ -1164,7 +1164,7 @@ cdef class BinaryMatrix(LeanMatrix): global GF2 return GF2 - cpdef characteristic(self): + cpdef characteristic(self) noexcept: """ Return the characteristic of ``self.base_ring()``. @@ -1177,7 +1177,7 @@ cdef class BinaryMatrix(LeanMatrix): """ return 2 - cdef get_unsafe(self, long r, long c): + cdef get_unsafe(self, long r, long c) noexcept: global GF2_one, GF2_zero if bitset_in(self._M[r], c): return GF2_one @@ -1193,10 +1193,10 @@ cdef class BinaryMatrix(LeanMatrix): cdef inline bint is_nonzero(self, long r, long c) except -2: # Not a Sage matrix operation return bitset_in(self._M[r], c) - cdef inline bint get(self, long r, long c): # Not a Sage matrix operation + cdef inline bint get(self, long r, long c) noexcept: # Not a Sage matrix operation return bitset_in(self._M[r], c) - cdef inline void set(self, long x, long y): # Not a Sage matrix operation + cdef inline void set(self, long x, long y) noexcept: # Not a Sage matrix operation bitset_add(self._M[x], y) cdef int pivot(self, long x, long y) except -1: # Not a Sage matrix operation @@ -1224,7 +1224,7 @@ cdef class BinaryMatrix(LeanMatrix): """ return bitset_len(self._M[i]) - cdef inline bint row_inner_product(self, long i, long j): # Not a Sage matrix operation + cdef inline bint row_inner_product(self, long i, long j) noexcept: # Not a Sage matrix operation """ Return the inner product between rows ``i`` and ``j``. """ @@ -1245,13 +1245,13 @@ cdef class BinaryMatrix(LeanMatrix): bitset_copy(self._M[j], self._temp) return 0 - cdef inline list nonzero_positions_in_row(self, long i): + cdef inline list nonzero_positions_in_row(self, long i) noexcept: """ Get coordinates of nonzero entries of row ``r``. """ return bitset_list(self._M[i]) - cdef inline list row_sum(self, object L): # Not a Sage matrix operation + cdef inline list row_sum(self, object L) noexcept: # Not a Sage matrix operation """ Return the mod-2 sum of the rows indexed by ``L``. """ @@ -1260,7 +1260,7 @@ cdef class BinaryMatrix(LeanMatrix): bitset_symmetric_difference(self._temp, self._temp, self._M[l]) return bitset_list(self._temp) - cdef inline list row_union(self, object L): # Not a Sage matrix operation + cdef inline list row_union(self, object L) noexcept: # Not a Sage matrix operation """ Return the ``or`` of the rows indexed by ``L``. """ @@ -1269,7 +1269,7 @@ cdef class BinaryMatrix(LeanMatrix): bitset_union(self._temp, self._temp, self._M[l]) return bitset_list(self._temp) - cdef LeanMatrix transpose(self): + cdef LeanMatrix transpose(self) noexcept: """ Return the transpose of the matrix. """ @@ -1283,7 +1283,7 @@ cdef class BinaryMatrix(LeanMatrix): j = bitset_next(self._M[i], j + 1) return T - cdef LeanMatrix _matrix_times_matrix_(self, LeanMatrix other): + cdef LeanMatrix _matrix_times_matrix_(self, LeanMatrix other) noexcept: """ Return the product ``self * other``. """ @@ -1298,7 +1298,7 @@ cdef class BinaryMatrix(LeanMatrix): j = bitset_next(self._M[i], j + 1) return M - cdef LeanMatrix matrix_from_rows_and_columns(self, rows, columns): + cdef LeanMatrix matrix_from_rows_and_columns(self, rows, columns) noexcept: """ Return submatrix indexed by indicated rows and columns. """ @@ -1310,7 +1310,7 @@ cdef class BinaryMatrix(LeanMatrix): bitset_add(A._M[r], c) return A - cdef matrix_from_rows_and_columns_reordered(self, rows, columns): + cdef matrix_from_rows_and_columns_reordered(self, rows, columns) noexcept: """ Return a submatrix indexed by indicated rows and columns, as well as the column order of the resulting submatrix. @@ -1367,7 +1367,7 @@ cdef class BinaryMatrix(LeanMatrix): bitset_free(mask) return A, order - cdef list _character(self, bitset_t x): # Not a Sage matrix operation + cdef list _character(self, bitset_t x) noexcept: # Not a Sage matrix operation """ Return the vector of intersection lengths of the rows with ``x``. """ @@ -1378,7 +1378,7 @@ cdef class BinaryMatrix(LeanMatrix): I.append(bitset_len(self._temp)) return I - cdef BinaryMatrix _distinguish_by(self, BinaryMatrix P): + cdef BinaryMatrix _distinguish_by(self, BinaryMatrix P) noexcept: """ Helper method for equitable partition. """ @@ -1399,7 +1399,7 @@ cdef class BinaryMatrix(LeanMatrix): i += 1 return Q - cdef BinaryMatrix _splice_by(self, BinaryMatrix P): + cdef BinaryMatrix _splice_by(self, BinaryMatrix P) noexcept: """ Helper method for equitable partition. """ @@ -1416,7 +1416,7 @@ cdef class BinaryMatrix(LeanMatrix): Q.resize(r) return Q - cdef BinaryMatrix _isolate(self, long j): + cdef BinaryMatrix _isolate(self, long j) noexcept: """ Helper method for isomorphism test. """ @@ -1429,7 +1429,7 @@ cdef class BinaryMatrix(LeanMatrix): bitset_add(Q._M[self._nrows], j) return Q - cdef BinaryMatrix equitable_partition(self, BinaryMatrix P=None): + cdef BinaryMatrix equitable_partition(self, BinaryMatrix P=None) noexcept: """ Compute an equitable partition of the columns. """ @@ -1720,7 +1720,7 @@ cdef class TernaryMatrix(LeanMatrix): M[i, j] = self.get(i, j) return M - cdef get_unsafe(self, long r, long c): + cdef get_unsafe(self, long r, long c) noexcept: global GF3_zero, GF3_one, GF3_minus_one if not bitset_in(self._M0[r], c): return GF3_zero @@ -1732,7 +1732,7 @@ cdef class TernaryMatrix(LeanMatrix): self.set(r, c, x) return 0 - cdef LeanMatrix copy(self): # Deprecated Sage matrix operation + cdef LeanMatrix copy(self) noexcept: # Deprecated Sage matrix operation cdef TernaryMatrix T cdef long i T = TernaryMatrix(self._nrows, self._ncols) @@ -1766,7 +1766,7 @@ cdef class TernaryMatrix(LeanMatrix): self._nrows = k return 0 - cdef LeanMatrix stack(self, LeanMatrix MM): + cdef LeanMatrix stack(self, LeanMatrix MM) noexcept: cdef TernaryMatrix R cdef TernaryMatrix M = MM cdef long i @@ -1776,7 +1776,7 @@ cdef class TernaryMatrix(LeanMatrix): bitset_copy(R._M1[i + self.nrows()], M._M1[i]) return R - cdef LeanMatrix augment(self, LeanMatrix MM): + cdef LeanMatrix augment(self, LeanMatrix MM) noexcept: cdef TernaryMatrix R cdef TernaryMatrix M = MM cdef long i, j @@ -1787,7 +1787,7 @@ cdef class TernaryMatrix(LeanMatrix): bitset_set_to(R._M1[i], self.ncols() + j, bitset_in(M._M1[i], j)) return R - cdef LeanMatrix prepend_identity(self): # Not a Sage matrix operation + cdef LeanMatrix prepend_identity(self) noexcept: # Not a Sage matrix operation """ Return the matrix obtained by prepending an identity matrix. @@ -1801,7 +1801,7 @@ cdef class TernaryMatrix(LeanMatrix): A.set(i, i, 1) return A - cpdef base_ring(self): + cpdef base_ring(self) noexcept: """ Return GF(3). @@ -1815,7 +1815,7 @@ cdef class TernaryMatrix(LeanMatrix): global GF3 return GF3 - cpdef characteristic(self): + cpdef characteristic(self) noexcept: """ Return the characteristic of ``self.base_ring()``. @@ -1828,7 +1828,7 @@ cdef class TernaryMatrix(LeanMatrix): """ return 3 - cdef inline long get(self, long r, long c): # Not a Sage matrix operation + cdef inline long get(self, long r, long c) noexcept: # Not a Sage matrix operation if not bitset_in(self._M0[r], c): return 0 if not bitset_in(self._M1[r], c): @@ -1850,16 +1850,16 @@ cdef class TernaryMatrix(LeanMatrix): cdef inline bint is_nonzero(self, long r, long c) except -2: # Not a Sage matrix operation return bitset_in(self._M0[r], c) - cdef inline bint _is_negative(self, long r, long c): + cdef inline bint _is_negative(self, long r, long c) noexcept: return bitset_in(self._M1[r], c) - cdef inline long row_len(self, long i): # Not a Sage matrix operation + cdef inline long row_len(self, long i) noexcept: # Not a Sage matrix operation """ Return number of nonzero entries in row ``i``. """ return bitset_len(self._M0[i]) - cdef inline long row_inner_product(self, long i, long j): # Not a Sage matrix operation + cdef inline long row_inner_product(self, long i, long j) noexcept: # Not a Sage matrix operation """ Return the inner product between rows ``i`` and ``j``. """ @@ -1897,7 +1897,7 @@ cdef class TernaryMatrix(LeanMatrix): self.row_subs(x, y) return 0 - cdef void row_subs(self, long x, long y): # Not a Sage matrix operation + cdef void row_subs(self, long x, long y) noexcept: # Not a Sage matrix operation """ Subtract row ``y`` from row ``x``. """ @@ -1908,7 +1908,7 @@ cdef class TernaryMatrix(LeanMatrix): bitset_symmetric_difference(self._s, self._M0[y], self._M1[x]) bitset_intersection(self._M1[x], self._s, self._t) - cdef void _row_negate(self, long x): + cdef void _row_negate(self, long x) noexcept: bitset_symmetric_difference(self._M1[x], self._M1[x], self._M0[x]) cdef int swap_rows_c(self, long x, long y) except -1: @@ -1944,13 +1944,13 @@ cdef class TernaryMatrix(LeanMatrix): self.row_subs(i, x) return 0 - cdef list nonzero_positions_in_row(self, long r): + cdef list nonzero_positions_in_row(self, long r) noexcept: """ Get coordinates of nonzero entries of row ``r``. """ return bitset_list(self._M0[r]) - cdef LeanMatrix transpose(self): + cdef LeanMatrix transpose(self) noexcept: """ Return the transpose of the matrix. """ @@ -1966,7 +1966,7 @@ cdef class TernaryMatrix(LeanMatrix): j = bitset_next(self._M0[i], j + 1) return T - cdef LeanMatrix _matrix_times_matrix_(self, LeanMatrix other): + cdef LeanMatrix _matrix_times_matrix_(self, LeanMatrix other) noexcept: """ Return the product ``self * other``. """ @@ -1986,7 +1986,7 @@ cdef class TernaryMatrix(LeanMatrix): M.resize(self._nrows) return M - cdef matrix_from_rows_and_columns_reordered(self, rows, columns): + cdef matrix_from_rows_and_columns_reordered(self, rows, columns) noexcept: """ Return a submatrix indexed by indicated rows and columns, as well as the column order of the resulting submatrix. @@ -2298,7 +2298,7 @@ cdef class QuaternaryMatrix(LeanMatrix): M[i, j] = self.get(i, j) return M - cdef inline get(self, long r, long c): # Not a Sage matrix operation + cdef inline get(self, long r, long c) noexcept: # Not a Sage matrix operation if bitset_in(self._M0[r], c): if bitset_in(self._M1[r], c): return self._x_one @@ -2325,7 +2325,7 @@ cdef class QuaternaryMatrix(LeanMatrix): bitset_add(self._M1[r], c) return 0 - cdef get_unsafe(self, long r, long c): + cdef get_unsafe(self, long r, long c) noexcept: return self.get(r, c) cdef int set_unsafe(self, long r, long c, x) except -1: @@ -2335,7 +2335,7 @@ cdef class QuaternaryMatrix(LeanMatrix): cdef inline bint is_nonzero(self, long r, long c) except -2: # Not a Sage matrix operation return bitset_in(self._M0[r], c) or bitset_in(self._M1[r], c) - cdef LeanMatrix copy(self): # Deprecated Sage matrix operation + cdef LeanMatrix copy(self) noexcept: # Deprecated Sage matrix operation cdef QuaternaryMatrix T cdef long i T = QuaternaryMatrix(self._nrows, self._ncols, ring=self._gf4) @@ -2368,7 +2368,7 @@ cdef class QuaternaryMatrix(LeanMatrix): self._nrows = k return 0 - cdef LeanMatrix stack(self, LeanMatrix MM): + cdef LeanMatrix stack(self, LeanMatrix MM) noexcept: cdef QuaternaryMatrix R cdef QuaternaryMatrix M = MM cdef long i @@ -2378,7 +2378,7 @@ cdef class QuaternaryMatrix(LeanMatrix): bitset_copy(R._M1[i + self.nrows()], M._M1[i]) return R - cdef LeanMatrix augment(self, LeanMatrix MM): + cdef LeanMatrix augment(self, LeanMatrix MM) noexcept: cdef QuaternaryMatrix R cdef QuaternaryMatrix M = MM cdef long i, j @@ -2389,7 +2389,7 @@ cdef class QuaternaryMatrix(LeanMatrix): bitset_set_to(R._M1[i], self.ncols() + j, bitset_in(M._M1[i], j)) return R - cdef LeanMatrix prepend_identity(self): # Not a Sage matrix operation + cdef LeanMatrix prepend_identity(self) noexcept: # Not a Sage matrix operation """ Return the matrix obtained by prepending an identity matrix. Special case of ``augment``. @@ -2402,7 +2402,7 @@ cdef class QuaternaryMatrix(LeanMatrix): A.set(i, i, 1) return A - cpdef base_ring(self): + cpdef base_ring(self) noexcept: """ Return copy of `GF(4)` with appropriate generator. @@ -2415,7 +2415,7 @@ cdef class QuaternaryMatrix(LeanMatrix): """ return self._gf4 - cpdef characteristic(self): + cpdef characteristic(self) noexcept: """ Return the characteristic of ``self.base_ring()``. @@ -2435,7 +2435,7 @@ cdef class QuaternaryMatrix(LeanMatrix): bitset_union(self._t, self._M0[i], self._M1[i]) return bitset_len(self._t) - cdef inline row_inner_product(self, long i, long j): # Not a Sage matrix operation + cdef inline row_inner_product(self, long i, long j) noexcept: # Not a Sage matrix operation """ Return the inner product between rows ``i`` and ``j``. """ @@ -2527,14 +2527,14 @@ cdef class QuaternaryMatrix(LeanMatrix): self.add_multiple_of_row_c(i, x, self.get(i, y), 0) return 0 - cdef list nonzero_positions_in_row(self, long r): + cdef list nonzero_positions_in_row(self, long r) noexcept: """ Get coordinates of nonzero entries of row ``r``. """ bitset_union(self._t, self._M0[r], self._M1[r]) return bitset_list(self._t) - cdef LeanMatrix transpose(self): + cdef LeanMatrix transpose(self) noexcept: """ Return the transpose of the matrix. """ @@ -2546,7 +2546,7 @@ cdef class QuaternaryMatrix(LeanMatrix): T.set(i, j, self.get(j, i)) return T - cdef void conjugate(self): # Not a Sage matrix operation + cdef void conjugate(self) noexcept: # Not a Sage matrix operation """ Apply the nontrivial GF(4)-automorphism to the entries. """ @@ -2554,7 +2554,7 @@ cdef class QuaternaryMatrix(LeanMatrix): for i in range(self._nrows): bitset_symmetric_difference(self._M0[i], self._M0[i], self._M1[i]) - cdef LeanMatrix _matrix_times_matrix_(self, LeanMatrix other): + cdef LeanMatrix _matrix_times_matrix_(self, LeanMatrix other) noexcept: """ Return the product ``self * other``. """ @@ -2570,7 +2570,7 @@ cdef class QuaternaryMatrix(LeanMatrix): M.resize(self._nrows) return M - cdef matrix_from_rows_and_columns_reordered(self, rows, columns): + cdef matrix_from_rows_and_columns_reordered(self, rows, columns) noexcept: """ Return a submatrix indexed by indicated rows and columns, as well as the column order of the resulting submatrix. @@ -2726,7 +2726,7 @@ cdef class QuaternaryMatrix(LeanMatrix): data = (self.nrows(), self.ncols(), ring, versionB, size, limbs, longsize, M0, M1) return sage.matroids.unpickling.unpickle_quaternary_matrix, (version, data) -cpdef GenericMatrix generic_identity(n, ring): +cpdef GenericMatrix generic_identity(n, ring) noexcept: """ Return a GenericMatrix instance containing the `n \times n` identity matrix over ``ring``. @@ -2848,13 +2848,13 @@ cdef class PlusMinusOneMatrix(LeanMatrix): """ return "PlusMinusOneMatrix instance with {} rows and {} columns".format(self._nrows, self._ncols) - cdef inline int get(self, long r, long c): # Not a Sage matrix operation + cdef inline int get(self, long r, long c) noexcept: # Not a Sage matrix operation return self._entries[r * self._ncols + c] - cdef inline void set(self, long r, long c, int x): # Not a Sage matrix operation + cdef inline void set(self, long r, long c, int x) noexcept: # Not a Sage matrix operation self._entries[r * self._ncols + c] = x - cdef get_unsafe(self, long r, long c): + cdef get_unsafe(self, long r, long c) noexcept: """ Return a Sage Integer, for safety down the line when dividing. @@ -2883,7 +2883,7 @@ cdef class PlusMinusOneMatrix(LeanMatrix): cdef bint is_nonzero(self, long r, long c) except -2: # Not a Sage matrix operation return self.get(r, c) != 0 - cdef LeanMatrix copy(self): # Deprecated Sage matrix operation + cdef LeanMatrix copy(self) noexcept: # Deprecated Sage matrix operation cdef PlusMinusOneMatrix M = PlusMinusOneMatrix(self._nrows, self._ncols) memcpy(M._entries, self._entries, self._nrows * self._ncols * sizeof(int)) return M @@ -2901,7 +2901,7 @@ cdef class PlusMinusOneMatrix(LeanMatrix): self._nrows = k return 0 - cdef LeanMatrix stack(self, LeanMatrix M): + cdef LeanMatrix stack(self, LeanMatrix M) noexcept: """ Warning: assumes ``M`` is an PlusMinusOneMatrix instance of right dimensions! @@ -2912,7 +2912,7 @@ cdef class PlusMinusOneMatrix(LeanMatrix): memcpy(A._entries + self._nrows * self._ncols, (M)._entries, M.nrows() * M.ncols() * sizeof(int)) return A - cdef LeanMatrix augment(self, LeanMatrix M): + cdef LeanMatrix augment(self, LeanMatrix M) noexcept: """ Warning: assumes ``M`` is a PlusMinusOneMatrix instance! """ @@ -2925,7 +2925,7 @@ cdef class PlusMinusOneMatrix(LeanMatrix): memcpy(A._entries + (i * A._ncols + self._ncols), (M)._entries + i * Mn, Mn * sizeof(int)) return A - cdef LeanMatrix prepend_identity(self): # Not a Sage matrix operation + cdef LeanMatrix prepend_identity(self) noexcept: # Not a Sage matrix operation cdef PlusMinusOneMatrix A = PlusMinusOneMatrix(self._nrows, self._ncols + self._nrows, ring=self._base_ring) cdef long i for i in range(self._nrows): @@ -2933,7 +2933,7 @@ cdef class PlusMinusOneMatrix(LeanMatrix): memcpy(A._entries + (i * A._ncols + self._nrows), self._entries + i * self._ncols, self._ncols * sizeof(int)) return A - cpdef base_ring(self): + cpdef base_ring(self) noexcept: """ Return the base ring of ``self``. @@ -2946,7 +2946,7 @@ cdef class PlusMinusOneMatrix(LeanMatrix): """ return ZZ - cpdef characteristic(self): + cpdef characteristic(self) noexcept: """ Return the characteristic of ``self.base_ring()``. @@ -2970,7 +2970,7 @@ cdef class PlusMinusOneMatrix(LeanMatrix): res += 1 return res - cdef inline row_inner_product(self, long i, long j): # Not a Sage matrix operation + cdef inline row_inner_product(self, long i, long j) noexcept: # Not a Sage matrix operation """ Return the inner product between rows ``i`` and ``j``. """ @@ -3055,7 +3055,7 @@ cdef class PlusMinusOneMatrix(LeanMatrix): self.add_multiple_of_row_c(i, x, -s, 0) return 0 - cdef list nonzero_positions_in_row(self, long r): + cdef list nonzero_positions_in_row(self, long r) noexcept: """ Get coordinates of nonzero entries of row ``r``. """ @@ -3066,7 +3066,7 @@ cdef class PlusMinusOneMatrix(LeanMatrix): res.append(j - r * self._ncols) return res - cdef LeanMatrix transpose(self): + cdef LeanMatrix transpose(self) noexcept: """ Return the transpose of the matrix. """ @@ -3078,7 +3078,7 @@ cdef class PlusMinusOneMatrix(LeanMatrix): A.set(j, i, self.get(i, j)) return A - cdef LeanMatrix _matrix_times_matrix_(self, LeanMatrix other): + cdef LeanMatrix _matrix_times_matrix_(self, LeanMatrix other) noexcept: """ Return the product ``self * other``. """ @@ -3095,7 +3095,7 @@ cdef class PlusMinusOneMatrix(LeanMatrix): A.set(i, j, s) return A - cdef list gauss_jordan_reduce(self, columns): # Not a Sage matrix operation + cdef list gauss_jordan_reduce(self, columns) noexcept: # Not a Sage matrix operation """ Row-reduce so the lexicographically first basis indexes an identity submatrix. @@ -3295,13 +3295,13 @@ cdef class RationalMatrix(LeanMatrix): """ return "RationalMatrix instance with {} rows and {} columns".format(self._nrows, self._ncols) - cdef inline long index(self, long r, long c): # Not a Sage matrix operation + cdef inline long index(self, long r, long c) noexcept: # Not a Sage matrix operation return r * self._ncols + c - cdef inline void set(self, long r, long c, mpq_t x): # Not a Sage matrix operation + cdef inline void set(self, long r, long c, mpq_t x) noexcept: # Not a Sage matrix operation mpq_set(self._entries[r * self._ncols + c], x) - cdef get_unsafe(self, long r, long c): + cdef get_unsafe(self, long r, long c) noexcept: """ Return a Sage Integer, for safety down the line when dividing. @@ -3332,7 +3332,7 @@ cdef class RationalMatrix(LeanMatrix): cdef bint is_nonzero(self, long r, long c) except -2: # Not a Sage matrix operation return mpq_sgn(self._entries[self.index(r, c)]) != 0 - cdef LeanMatrix copy(self): # Deprecated Sage matrix operation + cdef LeanMatrix copy(self) noexcept: # Deprecated Sage matrix operation cdef RationalMatrix M = RationalMatrix(self._nrows, self._ncols) cdef long i for i in range(self._nrows * self._ncols): @@ -3358,7 +3358,7 @@ cdef class RationalMatrix(LeanMatrix): self._nrows = k return 0 - cdef LeanMatrix stack(self, LeanMatrix M): + cdef LeanMatrix stack(self, LeanMatrix M) noexcept: """ Warning: assumes ``M`` is an RationalMatrix instance of right dimensions! @@ -3373,7 +3373,7 @@ cdef class RationalMatrix(LeanMatrix): mpq_set(A._entries[l+i], (M)._entries[i]) return A - cdef LeanMatrix augment(self, LeanMatrix M): + cdef LeanMatrix augment(self, LeanMatrix M) noexcept: """ Warning: assumes ``M`` is a RationalMatrix instance! """ @@ -3387,7 +3387,7 @@ cdef class RationalMatrix(LeanMatrix): mpq_set(A._entries[i*A._ncols + self._ncols + j], (M)._entries[i*Mn + j]) return A - cdef LeanMatrix prepend_identity(self): # Not a Sage matrix operation + cdef LeanMatrix prepend_identity(self) noexcept: # Not a Sage matrix operation cdef RationalMatrix A = RationalMatrix(self._nrows, self._ncols + self._nrows) cdef long i, j for i in range(self._nrows): @@ -3396,7 +3396,7 @@ cdef class RationalMatrix(LeanMatrix): mpq_set(A._entries[A.index(i,self._nrows+j)], self._entries[self.index(i,j)]) return A - cpdef base_ring(self): + cpdef base_ring(self) noexcept: """ Return the base ring of ``self``. @@ -3409,7 +3409,7 @@ cdef class RationalMatrix(LeanMatrix): """ return QQ - cpdef characteristic(self): + cpdef characteristic(self) noexcept: """ Return the characteristic of ``self.base_ring()``. @@ -3433,7 +3433,7 @@ cdef class RationalMatrix(LeanMatrix): res += 1 return res - cdef inline row_inner_product(self, long i, long j): # Not a Sage matrix operation + cdef inline row_inner_product(self, long i, long j) noexcept: # Not a Sage matrix operation """ Return the inner product between rows ``i`` and ``j``. """ @@ -3542,7 +3542,7 @@ cdef class RationalMatrix(LeanMatrix): mpq_clear(t) return 0 - cdef list nonzero_positions_in_row(self, long r): + cdef list nonzero_positions_in_row(self, long r) noexcept: """ Get coordinates of nonzero entries of row ``r``. """ @@ -3553,7 +3553,7 @@ cdef class RationalMatrix(LeanMatrix): res.append(j - r * self._ncols) return res - cdef LeanMatrix transpose(self): + cdef LeanMatrix transpose(self) noexcept: """ Return the transpose of the matrix. """ @@ -3565,7 +3565,7 @@ cdef class RationalMatrix(LeanMatrix): A.set(j, i, self._entries[self.index(i, j)]) return A - cdef LeanMatrix _matrix_times_matrix_(self, LeanMatrix other): + cdef LeanMatrix _matrix_times_matrix_(self, LeanMatrix other) noexcept: """ Return the product ``self * other``. """ @@ -3585,7 +3585,7 @@ cdef class RationalMatrix(LeanMatrix): mpq_clear(s) return A - cdef list gauss_jordan_reduce(self, columns): # Not a Sage matrix operation + cdef list gauss_jordan_reduce(self, columns) noexcept: # Not a Sage matrix operation """ Row-reduce so the lexicographically first basis indexes an identity submatrix. diff --git a/src/sage/matroids/linear_matroid.pxd b/src/sage/matroids/linear_matroid.pxd index 9aebd446b68..663886fa58e 100644 --- a/src/sage/matroids/linear_matroid.pxd +++ b/src/sage/matroids/linear_matroid.pxd @@ -10,87 +10,87 @@ cdef class LinearMatroid(BasisExchangeMatroid): cdef long *_prow cdef object _zero, _one - cpdef _forget(self) - cpdef base_ring(self) - cpdef characteristic(self) - - cdef list _setup_internal_representation(self, matrix, reduced_matrix, ring, keep_initial_representation) - cdef _exchange_value_internal(self, long x, long y) - - cpdef representation(self, B=*, reduced=*, labels=*, order=*, lift_map=*) - cpdef _current_rows_cols(self, B=*) - cpdef representation_vectors(self) - cpdef LeanMatrix _basic_representation(self, B=*) - cpdef LeanMatrix _reduced_representation(self, B=*) - - cpdef bint _is_field_isomorphism(self, LinearMatroid other, morphism) - cpdef is_field_equivalent(self, other) - cpdef is_field_isomorphism(self, other, morphism) + cpdef _forget(self) noexcept + cpdef base_ring(self) noexcept + cpdef characteristic(self) noexcept + + cdef list _setup_internal_representation(self, matrix, reduced_matrix, ring, keep_initial_representation) noexcept + cdef _exchange_value_internal(self, long x, long y) noexcept + + cpdef representation(self, B=*, reduced=*, labels=*, order=*, lift_map=*) noexcept + cpdef _current_rows_cols(self, B=*) noexcept + cpdef representation_vectors(self) noexcept + cpdef LeanMatrix _basic_representation(self, B=*) noexcept + cpdef LeanMatrix _reduced_representation(self, B=*) noexcept + + cpdef bint _is_field_isomorphism(self, LinearMatroid other, morphism) noexcept + cpdef is_field_equivalent(self, other) noexcept + cpdef is_field_isomorphism(self, other, morphism) noexcept # cpdef is_field_isomorphic(self, other) # TODO: currently only works as ``def`` - cpdef _fast_isom_test(self, other) - - cpdef _minor(self, contractions, deletions) - cpdef dual(self) - cpdef has_line_minor(self, k, hyperlines=*, certificate=*) - cpdef has_field_minor(self, N) - - cpdef _exchange_value(self, e, f) - cpdef fundamental_cycle(self, B, e) - cpdef fundamental_cocycle(self, B, e) - - cpdef _line_ratios(self, F) - cpdef _line_length(self, F) - - cpdef _line_cross_ratios(self, F) - cpdef cross_ratios(self, hyperlines=*) - cpdef cross_ratio(self, F, a, b, c, d) - cpdef _line_cross_ratio_test(self, F, x, fundamentals) - cpdef _cross_ratio_test(self, x, fundamentals, hyperlines=*) - - cpdef linear_extension(self, element, chain=*, col=*) - cpdef linear_coextension(self, element, cochain=*, row=*) - cpdef _linear_extensions(self, element, chains) - cpdef _linear_coextensions(self, element, cochains) - cdef _extend_chains(self, C, f, fundamentals=*) - cpdef _linear_extension_chains(self, F, fundamentals=*) - cpdef linear_extension_chains(self, F=*, simple=*, fundamentals=*) - cpdef linear_coextension_cochains(self, F=*, cosimple=*, fundamentals=*) - cpdef linear_extensions(self, element=*, F=*, simple=*, fundamentals=*) - cpdef linear_coextensions(self, element=*, F=*, cosimple=*, fundamentals=*) - - cpdef _is_3connected_shifting(self, certificate=*) - cpdef _is_4connected_shifting(self, certificate=*) - - cpdef is_valid(self) + cpdef _fast_isom_test(self, other) noexcept + + cpdef _minor(self, contractions, deletions) noexcept + cpdef dual(self) noexcept + cpdef has_line_minor(self, k, hyperlines=*, certificate=*) noexcept + cpdef has_field_minor(self, N) noexcept + + cpdef _exchange_value(self, e, f) noexcept + cpdef fundamental_cycle(self, B, e) noexcept + cpdef fundamental_cocycle(self, B, e) noexcept + + cpdef _line_ratios(self, F) noexcept + cpdef _line_length(self, F) noexcept + + cpdef _line_cross_ratios(self, F) noexcept + cpdef cross_ratios(self, hyperlines=*) noexcept + cpdef cross_ratio(self, F, a, b, c, d) noexcept + cpdef _line_cross_ratio_test(self, F, x, fundamentals) noexcept + cpdef _cross_ratio_test(self, x, fundamentals, hyperlines=*) noexcept + + cpdef linear_extension(self, element, chain=*, col=*) noexcept + cpdef linear_coextension(self, element, cochain=*, row=*) noexcept + cpdef _linear_extensions(self, element, chains) noexcept + cpdef _linear_coextensions(self, element, cochains) noexcept + cdef _extend_chains(self, C, f, fundamentals=*) noexcept + cpdef _linear_extension_chains(self, F, fundamentals=*) noexcept + cpdef linear_extension_chains(self, F=*, simple=*, fundamentals=*) noexcept + cpdef linear_coextension_cochains(self, F=*, cosimple=*, fundamentals=*) noexcept + cpdef linear_extensions(self, element=*, F=*, simple=*, fundamentals=*) noexcept + cpdef linear_coextensions(self, element=*, F=*, cosimple=*, fundamentals=*) noexcept + + cpdef _is_3connected_shifting(self, certificate=*) noexcept + cpdef _is_4connected_shifting(self, certificate=*) noexcept + + cpdef is_valid(self) noexcept cdef class BinaryMatroid(LinearMatroid): cdef tuple _b_invariant, _b_partition cdef BinaryMatrix _b_projection, _eq_part - cpdef base_ring(self) - cpdef characteristic(self) + cpdef base_ring(self) noexcept + cpdef characteristic(self) noexcept - cpdef _current_rows_cols(self, B=*) - cpdef LeanMatrix _basic_representation(self, B=*) - cpdef LeanMatrix _reduced_representation(self, B=*) + cpdef _current_rows_cols(self, B=*) noexcept + cpdef LeanMatrix _basic_representation(self, B=*) noexcept + cpdef LeanMatrix _reduced_representation(self, B=*) noexcept - cdef __fundamental_cocircuit(self, bitset_t, long x) + cdef __fundamental_cocircuit(self, bitset_t, long x) noexcept - cpdef _is_isomorphic(self, other, certificate=*) + cpdef _is_isomorphic(self, other, certificate=*) noexcept - cpdef _minor(self, contractions, deletions) + cpdef _minor(self, contractions, deletions) noexcept - cpdef _make_invariant(self) - cpdef _invariant(self) - cpdef bicycle_dimension(self) - cpdef brown_invariant(self) - cpdef _principal_tripartition(self) - cpdef BinaryMatrix _projection(self) - cpdef BinaryMatrix _projection_partition(self) - cpdef _fast_isom_test(self, other) + cpdef _make_invariant(self) noexcept + cpdef _invariant(self) noexcept + cpdef bicycle_dimension(self) noexcept + cpdef brown_invariant(self) noexcept + cpdef _principal_tripartition(self) noexcept + cpdef BinaryMatrix _projection(self) noexcept + cpdef BinaryMatrix _projection_partition(self) noexcept + cpdef _fast_isom_test(self, other) noexcept - cpdef is_graphic(self) - cpdef is_valid(self) + cpdef is_graphic(self) noexcept + cpdef is_valid(self) noexcept cdef class TernaryMatroid(LinearMatroid): @@ -98,74 +98,74 @@ cdef class TernaryMatroid(LinearMatroid): cdef tuple _t_invariant, _t_partition cdef TernaryMatrix _t_projection - cpdef base_ring(self) - cpdef characteristic(self) + cpdef base_ring(self) noexcept + cpdef characteristic(self) noexcept - cpdef _current_rows_cols(self, B=*) - cpdef LeanMatrix _basic_representation(self, B=*) - cpdef LeanMatrix _reduced_representation(self, B=*) + cpdef _current_rows_cols(self, B=*) noexcept + cpdef LeanMatrix _basic_representation(self, B=*) noexcept + cpdef LeanMatrix _reduced_representation(self, B=*) noexcept - cdef __fundamental_cocircuit(self, bitset_t, long x) + cdef __fundamental_cocircuit(self, bitset_t, long x) noexcept - cpdef _is_isomorphic(self, other, certificate=*) + cpdef _is_isomorphic(self, other, certificate=*) noexcept - cpdef _minor(self, contractions, deletions) + cpdef _minor(self, contractions, deletions) noexcept - cpdef _make_invariant(self) - cpdef _invariant(self) - cpdef bicycle_dimension(self) - cpdef character(self) - cpdef _principal_quadripartition(self) - cpdef TernaryMatrix _projection(self) - cpdef _fast_isom_test(self, other) + cpdef _make_invariant(self) noexcept + cpdef _invariant(self) noexcept + cpdef bicycle_dimension(self) noexcept + cpdef character(self) noexcept + cpdef _principal_quadripartition(self) noexcept + cpdef TernaryMatrix _projection(self) noexcept + cpdef _fast_isom_test(self, other) noexcept - cpdef is_valid(self) + cpdef is_valid(self) noexcept cdef class QuaternaryMatroid(LinearMatroid): cdef object _x_zero, _x_one cdef tuple _q_invariant, _q_partition cdef QuaternaryMatrix _q_projection - cpdef base_ring(self) - cpdef characteristic(self) + cpdef base_ring(self) noexcept + cpdef characteristic(self) noexcept - cpdef _current_rows_cols(self, B=*) - cpdef LeanMatrix _basic_representation(self, B=*) - cpdef LeanMatrix _reduced_representation(self, B=*) + cpdef _current_rows_cols(self, B=*) noexcept + cpdef LeanMatrix _basic_representation(self, B=*) noexcept + cpdef LeanMatrix _reduced_representation(self, B=*) noexcept - cdef __fundamental_cocircuit(self, bitset_t, long x) + cdef __fundamental_cocircuit(self, bitset_t, long x) noexcept - cpdef _is_isomorphic(self, other, certificate=*) + cpdef _is_isomorphic(self, other, certificate=*) noexcept - cpdef _minor(self, contractions, deletions) + cpdef _minor(self, contractions, deletions) noexcept - cpdef _make_invariant(self) - cpdef _invariant(self) - cpdef bicycle_dimension(self) - cpdef _principal_tripartition(self) - cpdef _fast_isom_test(self, other) + cpdef _make_invariant(self) noexcept + cpdef _invariant(self) noexcept + cpdef bicycle_dimension(self) noexcept + cpdef _principal_tripartition(self) noexcept + cpdef _fast_isom_test(self, other) noexcept - cpdef is_valid(self) + cpdef is_valid(self) noexcept cdef class RegularMatroid(LinearMatroid): cdef _bases_count, _r_invariant cdef _r_projection, _r_hypergraph cdef _hypergraph_vertex_partition, _hypergraph_tuples - cpdef base_ring(self) - cpdef characteristic(self) + cpdef base_ring(self) noexcept + cpdef characteristic(self) noexcept - cpdef _is_isomorphic(self, other, certificate=*) + cpdef _is_isomorphic(self, other, certificate=*) noexcept - cpdef _invariant(self) - cpdef _fast_isom_test(self, other) + cpdef _invariant(self) noexcept + cpdef _fast_isom_test(self, other) noexcept - cpdef bases_count(self) - cpdef _projection(self) - cpdef _hypergraph(self) - cdef _hypertest(self, other) - cpdef has_line_minor(self, k, hyperlines=*, certificate=*) - cpdef _linear_extension_chains(self, F, fundamentals=*) + cpdef bases_count(self) noexcept + cpdef _projection(self) noexcept + cpdef _hypergraph(self) noexcept + cdef _hypertest(self, other) noexcept + cpdef has_line_minor(self, k, hyperlines=*, certificate=*) noexcept + cpdef _linear_extension_chains(self, F, fundamentals=*) noexcept - cpdef is_graphic(self) - cpdef is_valid(self) + cpdef is_graphic(self) noexcept + cpdef is_valid(self) noexcept diff --git a/src/sage/matroids/linear_matroid.pyx b/src/sage/matroids/linear_matroid.pyx index 5b434dcac98..81a9f9e5a89 100644 --- a/src/sage/matroids/linear_matroid.pyx +++ b/src/sage/matroids/linear_matroid.pyx @@ -148,10 +148,10 @@ cdef GF3, GF3_one, GF3_zero, GF3_minus_one # provide alternative implementations # Below is some code, commented out currently, to get you going. -cdef inline gauss_jordan_reduce(LeanMatrix A, columns): +cdef inline gauss_jordan_reduce(LeanMatrix A, columns) noexcept: return A.gauss_jordan_reduce(columns) # Not a Sage matrix operation -cdef inline characteristic(LeanMatrix A): +cdef inline characteristic(LeanMatrix A) noexcept: return A.characteristic() # Not a Sage matrix operation # Implementation using default Sage matrices @@ -297,7 +297,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): sig_free(self._prow) self._prow = NULL - cdef list _setup_internal_representation(self, matrix, reduced_matrix, ring, keep_initial_representation): + cdef list _setup_internal_representation(self, matrix, reduced_matrix, ring, keep_initial_representation) noexcept: """ Setup the internal representation matrix ``self._A`` and the array of row- and column indices ``self._prow``. @@ -345,7 +345,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): self._prow[self._A.nrows() + r] = r return P - cpdef _forget(self): + cpdef _forget(self) noexcept: """ Remove the internal representation matrix. @@ -364,7 +364,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): """ self._representation = None - cpdef base_ring(self): + cpdef base_ring(self) noexcept: """ Return the base ring of the matrix representing the matroid. @@ -377,7 +377,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): """ return self._A.base_ring() - cpdef characteristic(self): + cpdef characteristic(self) noexcept: """ Return the characteristic of the base ring of the matrix representing the matroid. @@ -422,7 +422,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): self._prow[x] = py BasisExchangeMatroid._exchange(self, x, y) - cdef _exchange_value_internal(self, long x, long y): + cdef _exchange_value_internal(self, long x, long y) noexcept: r""" Return the (x, y) entry of the current representation. """ @@ -471,7 +471,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): # representations - cpdef representation(self, B=None, reduced=False, labels=None, order=None, lift_map=None): + cpdef representation(self, B=None, reduced=False, labels=None, order=None, lift_map=None) noexcept: r""" Return a matrix representing the matroid. @@ -649,7 +649,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): else: return lift_cross_ratios(A._matrix_(), lift_map) - cpdef _current_rows_cols(self, B=None): + cpdef _current_rows_cols(self, B=None) noexcept: """ Return the current row and column labels of a reduced matrix. @@ -688,7 +688,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): cols[self._prow[self._idx[e]]] = e return rows, cols - cpdef LeanMatrix _basic_representation(self, B=None): + cpdef LeanMatrix _basic_representation(self, B=None) noexcept: """ Return a basic matrix representation of the matroid. @@ -737,7 +737,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): i += 1 return A - cpdef representation_vectors(self): + cpdef representation_vectors(self) noexcept: """ Return a dictionary that associates a column vector with each element of the matroid. @@ -757,7 +757,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): R = self._matrix_().columns() return {e: R[self._idx[e]] for e in self.groundset()} - cpdef LeanMatrix _reduced_representation(self, B=None): + cpdef LeanMatrix _reduced_representation(self, B=None) noexcept: r""" Return a reduced representation of the matroid, i.e. a matrix `R` such that `[I\ \ R]` represents the matroid. @@ -796,7 +796,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): # (field) isomorphism - cpdef bint _is_field_isomorphism(self, LinearMatroid other, morphism): # not safe if self == other + cpdef bint _is_field_isomorphism(self, LinearMatroid other, morphism) noexcept: # not safe if self == other r""" Version of :meth:`` that does no type checking. @@ -879,7 +879,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): normalization[N.pop()] = self._one return True - cpdef is_field_equivalent(self, other): + cpdef is_field_equivalent(self, other) noexcept: """ Test for matroid representation equality. @@ -966,7 +966,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): morphism = {e: e for e in self.groundset()} return self._is_field_isomorphism(other, morphism) - cpdef is_field_isomorphism(self, other, morphism): + cpdef is_field_isomorphism(self, other, morphism) noexcept: r""" Test if a provided morphism induces a bijection between represented matroids. @@ -1052,7 +1052,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): else: return self._is_field_isomorphism(copy(other), mf) - cpdef _fast_isom_test(self, other): + cpdef _fast_isom_test(self, other) noexcept: """ Fast (field) isomorphism test for some subclasses. @@ -1278,7 +1278,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): # minors, dual - cpdef _minor(self, contractions, deletions): + cpdef _minor(self, contractions, deletions) noexcept: r""" Return a minor. @@ -1322,7 +1322,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): M.set_unsafe(i, j, self._exchange_value(rows[i], cols[j])) return type(self)(reduced_matrix=M, groundset=rows + cols) - cpdef dual(self): + cpdef dual(self) noexcept: r""" Return the dual of the matroid. @@ -1354,7 +1354,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): rows, cols = self._current_rows_cols() return type(self)(reduced_matrix=R, groundset=cols + rows) - cpdef has_line_minor(self, k, hyperlines=None, certificate=False): + cpdef has_line_minor(self, k, hyperlines=None, certificate=False) noexcept: r""" Test if the matroid has a `U_{2, k}`-minor. @@ -1409,7 +1409,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): pass return Matroid.has_line_minor(self, k, hyperlines, certificate) - cpdef has_field_minor(self, N): + cpdef has_field_minor(self, N) noexcept: """ Check if ``self`` has a minor field isomorphic to ``N``. @@ -1467,7 +1467,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): # cycles, cocycles and cross ratios - cpdef _exchange_value(self, e, f): + cpdef _exchange_value(self, e, f) noexcept: """ Return the matrix entry indexed by row `e` and column `f`. @@ -1495,7 +1495,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): """ return self._exchange_value_internal(self._idx[e], self._idx[f]) - cpdef fundamental_cycle(self, B, e): + cpdef fundamental_cycle(self, B, e) noexcept: """ Return the fundamental cycle, relative to ``B``, containing element ``e``. @@ -1541,7 +1541,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): chain[f] = -x return chain - cpdef fundamental_cocycle(self, B, e): + cpdef fundamental_cocycle(self, B, e) noexcept: """ Return the fundamental cycle, relative to ``B``, containing element ``e``. @@ -1586,7 +1586,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): cochain[f] = x return cochain - cpdef _line_ratios(self, F): + cpdef _line_ratios(self, F) noexcept: """ Return the set of nonzero ratios of column entries after contracting a rank-`r-2` flat ``F``. @@ -1617,7 +1617,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): rat.add(s * (t ** (-1))) return rat - cpdef _line_length(self, F): + cpdef _line_length(self, F) noexcept: """ Return ``len(M.contract(F).simplify())``, where ``F`` is assumed to be a flat of rank 2 less than the matroid. @@ -1637,7 +1637,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): """ return 2 + len(self._line_ratios(F)) - cpdef _line_cross_ratios(self, F): + cpdef _line_cross_ratios(self, F) noexcept: """ Return the set of cross ratios of column entries after contracting a rank-`r-2` flat ``F``. @@ -1665,7 +1665,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): cr.add(r2 / r1) return cr - cpdef cross_ratios(self, hyperlines=None): + cpdef cross_ratios(self, hyperlines=None) noexcept: r""" Return the set of cross ratios that occur in this linear matroid. @@ -1723,7 +1723,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): CR.difference_update(asc) return CR2 - cpdef cross_ratio(self, F, a, b, c, d): + cpdef cross_ratio(self, F, a, b, c, d) noexcept: r""" Return the cross ratio of the four ordered points ``a, b, c, d`` after contracting a flat ``F`` of codimension 2. @@ -1781,7 +1781,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): raise ValueError("points a, b, c, d do not form a 4-point line in M/F") return cr1 / cr2 - cpdef _line_cross_ratio_test(self, F, x, fundamentals): + cpdef _line_cross_ratio_test(self, F, x, fundamentals) noexcept: r""" Check whether the cross ratios involving a fixed element in a fixed rank-2 minor are in a specified subset. @@ -1841,7 +1841,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): return False return True - cpdef _cross_ratio_test(self, x, fundamentals, hyperlines=None): + cpdef _cross_ratio_test(self, x, fundamentals, hyperlines=None) noexcept: r""" Test if the cross ratios using a given element of this linear matroid are contained in a given set of fundamentals. @@ -1890,7 +1890,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): return True # linear extension - cpdef linear_extension(self, element, chain=None, col=None): + cpdef linear_extension(self, element, chain=None, col=None) noexcept: r""" Return a linear extension of this matroid. @@ -1959,7 +1959,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): raise TypeError("chain argument needs to be a dictionary") return self._linear_extensions(element, [chain])[0] - cpdef linear_coextension(self, element, cochain=None, row=None): + cpdef linear_coextension(self, element, cochain=None, row=None) noexcept: r""" Return a linear coextension of this matroid. @@ -2060,7 +2060,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): raise TypeError("cochain argument needs to be a dictionary") return self._linear_coextensions(element, [cochain])[0] - cpdef _linear_extensions(self, element, chains): + cpdef _linear_extensions(self, element, chains) noexcept: r""" Return the linear extensions of this matroid representation specified by the given chains. @@ -2108,7 +2108,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): ext.append(type(self)(matrix=M, groundset=E)) return ext - cpdef _linear_coextensions(self, element, cochains): + cpdef _linear_coextensions(self, element, cochains) noexcept: r""" Return the linear coextensions of this matroid representation specified by the given cochains. @@ -2156,7 +2156,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): coext.append(type(self)(matrix=M, groundset=E)) return coext - cdef _extend_chains(self, C, f, fundamentals=None): + cdef _extend_chains(self, C, f, fundamentals=None) noexcept: r""" Extend a list of chains for ``self / f`` to a list of chains for ``self``. @@ -2218,7 +2218,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): res = [chain for chain in res if len(chain) < 2 or self._linear_extensions(ne, [chain])[0]._cross_ratio_test(ne, fundamentals, hyperlines)] return res - cpdef _linear_extension_chains(self, F, fundamentals=None): # assumes independent F + cpdef _linear_extension_chains(self, F, fundamentals=None) noexcept: # assumes independent F r""" Create a list of chains that determine single-element extensions of this linear matroid representation. @@ -2294,7 +2294,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): chains = new_chains return chains - cpdef linear_extension_chains(self, F=None, simple=False, fundamentals=None): + cpdef linear_extension_chains(self, F=None, simple=False, fundamentals=None) noexcept: r""" Create a list of chains that determine the single-element extensions of this linear matroid representation. @@ -2393,7 +2393,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): chains = simple_chains return chains - cpdef linear_coextension_cochains(self, F=None, cosimple=False, fundamentals=None): + cpdef linear_coextension_cochains(self, F=None, cosimple=False, fundamentals=None) noexcept: r""" Create a list of cochains that determine the single-element coextensions of this linear matroid representation. @@ -2451,7 +2451,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): """ return self.dual().linear_extension_chains(F=F, simple=cosimple, fundamentals=fundamentals) - cpdef linear_extensions(self, element=None, F=None, simple=False, fundamentals=None): + cpdef linear_extensions(self, element=None, F=None, simple=False, fundamentals=None) noexcept: r""" Create a list of linear matroids represented by rank-preserving single-element extensions of this linear matroid representation. @@ -2519,7 +2519,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): chains = self.linear_extension_chains(F, simple=simple, fundamentals=fundamentals) return self._linear_extensions(element, chains) - cpdef linear_coextensions(self, element=None, F=None, cosimple=False, fundamentals=None): + cpdef linear_coextensions(self, element=None, F=None, cosimple=False, fundamentals=None) noexcept: r""" Create a list of linear matroids represented by corank-preserving single-element coextensions of this linear matroid representation. @@ -2590,7 +2590,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): cochains = self.linear_coextension_cochains(F, cosimple=cosimple, fundamentals=fundamentals) return self._linear_coextensions(element, cochains) - cpdef is_valid(self): + cpdef is_valid(self) noexcept: r""" Test if the data represent an actual matroid. @@ -2641,7 +2641,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): # connectivity - cpdef _is_3connected_shifting(self, certificate=False): + cpdef _is_3connected_shifting(self, certificate=False) noexcept: r""" Return ``True`` if the matroid is 4-connected, ``False`` otherwise. It can optionally return a separator as a witness. @@ -2720,7 +2720,7 @@ cdef class LinearMatroid(BasisExchangeMatroid): return True, None return True - cpdef _is_4connected_shifting(self, certificate=False): + cpdef _is_4connected_shifting(self, certificate=False) noexcept: r""" Return ``True`` if the matroid is 4-connected, ``False`` otherwise. It can optionally return a separator as a witness. @@ -3125,7 +3125,7 @@ cdef class BinaryMatroid(LinearMatroid): self._zero = GF2_zero self._one = GF2_one - cpdef base_ring(self): + cpdef base_ring(self) noexcept: r""" Return the base ring of the matrix representing the matroid, in this case `\GF{2}`. @@ -3139,7 +3139,7 @@ cdef class BinaryMatroid(LinearMatroid): global GF2 return GF2 - cpdef characteristic(self): + cpdef characteristic(self) noexcept: """ Return the characteristic of the base ring of the matrix representing the matroid, in this case `2`. @@ -3167,13 +3167,13 @@ cdef class BinaryMatroid(LinearMatroid): self._prow[y] = p BasisExchangeMatroid._exchange(self, x, y) - cdef __fundamental_cocircuit(self, bitset_t C, long x): + cdef __fundamental_cocircuit(self, bitset_t C, long x) noexcept: r""" Fill bitset `C` with the incidence vector of the `B`-fundamental cocircuit using ``x``. Internal method using packed elements. """ bitset_copy(C, (self._A)._M[self._prow[x]]) - cdef _coclosure_internal(self, bitset_t R, bitset_t F): + cdef _coclosure_internal(self, bitset_t R, bitset_t F) noexcept: """ Bitpacked version of ``coclosure``. @@ -3196,7 +3196,7 @@ cdef class BinaryMatroid(LinearMatroid): bitset_add(R, y) y = bitset_next(self._inside, y + 1) - cdef _exchange_value_internal(self, long x, long y): + cdef _exchange_value_internal(self, long x, long y) noexcept: r""" Return the (x, y) entry of the current representation. """ @@ -3222,7 +3222,7 @@ cdef class BinaryMatroid(LinearMatroid): S = "Binary matroid of rank " + str(self.rank()) + " on " + str(self.size()) + " elements, type (" + str(self.bicycle_dimension()) + ', ' + str(self.brown_invariant()) + ')' return S - cpdef _current_rows_cols(self, B=None): + cpdef _current_rows_cols(self, B=None) noexcept: """ Return the current row and column labels of a reduced matrix. @@ -3264,7 +3264,7 @@ cdef class BinaryMatroid(LinearMatroid): c += 1 return rows, cols - cpdef LeanMatrix _basic_representation(self, B=None): + cpdef LeanMatrix _basic_representation(self, B=None) noexcept: """ Return a basic matrix representation of the matroid. @@ -3303,7 +3303,7 @@ cdef class BinaryMatroid(LinearMatroid): self._move_current_basis(B, set()) return self._A.copy() # Deprecated Sage matrix operation - cpdef LeanMatrix _reduced_representation(self, B=None): + cpdef LeanMatrix _reduced_representation(self, B=None) noexcept: r""" Return a reduced representation of the matroid, i.e. a matrix `R` such that `[I\ \ R]` represents the matroid. @@ -3345,7 +3345,7 @@ cdef class BinaryMatroid(LinearMatroid): # isomorphism - cpdef _is_isomorphic(self, other, certificate=False): + cpdef _is_isomorphic(self, other, certificate=False) noexcept: """ Test if ``self`` is isomorphic to ``other``. @@ -3394,7 +3394,7 @@ cdef class BinaryMatroid(LinearMatroid): else: return LinearMatroid._is_isomorphic(self, other) - cpdef _is_isomorphism(self, other, morphism): + cpdef _is_isomorphism(self, other, morphism) noexcept: r""" Test if a given bijection is an isomorphism. @@ -3425,7 +3425,7 @@ cdef class BinaryMatroid(LinearMatroid): return LinearMatroid._is_isomorphism(self, other, morphism) # invariants - cpdef _make_invariant(self): + cpdef _make_invariant(self) noexcept: """ Create an invariant. @@ -3515,7 +3515,7 @@ cdef class BinaryMatroid(LinearMatroid): self._b_invariant = tuple([d, b2, len(Fm), len(F0), len(Fp), p[0], p[1], p[2]]) self._b_partition = tuple([Fm, F0, Fp]) - cpdef _invariant(self): + cpdef _invariant(self) noexcept: r""" Return a matroid invariant. @@ -3544,7 +3544,7 @@ cdef class BinaryMatroid(LinearMatroid): self._make_invariant() return self._b_invariant - cpdef bicycle_dimension(self): + cpdef bicycle_dimension(self) noexcept: r""" Return the bicycle dimension of the binary matroid. @@ -3567,7 +3567,7 @@ cdef class BinaryMatroid(LinearMatroid): self._make_invariant() return self._b_invariant[0] - cpdef brown_invariant(self): + cpdef brown_invariant(self) noexcept: r""" Return the value of Brown's invariant for the binary matroid. @@ -3604,7 +3604,7 @@ cdef class BinaryMatroid(LinearMatroid): self._make_invariant() return self._b_invariant[1] - cpdef _principal_tripartition(self): + cpdef _principal_tripartition(self) noexcept: r""" Return the principal tripartition of the binary matroid. @@ -3642,7 +3642,7 @@ cdef class BinaryMatroid(LinearMatroid): P = self._b_partition return frozenset([self._E[e] for e in P[0]]), frozenset([self._E[e] for e in P[1]]), frozenset([self._E[e] for e in P[2]]) - cpdef BinaryMatrix _projection(self): + cpdef BinaryMatrix _projection(self) noexcept: """ Return the projection matrix onto the row space. @@ -3684,7 +3684,7 @@ cdef class BinaryMatroid(LinearMatroid): self._make_invariant() return self._b_projection - cpdef BinaryMatrix _projection_partition(self): + cpdef BinaryMatrix _projection_partition(self) noexcept: """ Return the equitable partition of the graph whose incidence matrix is the projection matrix of this matroid. @@ -3716,7 +3716,7 @@ cdef class BinaryMatroid(LinearMatroid): self._eq_part = self._b_projection.equitable_partition() # Not a Sage matrix operation return self._eq_part - cpdef _fast_isom_test(self, other): + cpdef _fast_isom_test(self, other) noexcept: r""" Run a quick test to see if two binary matroids are isomorphic. @@ -3750,7 +3750,7 @@ cdef class BinaryMatroid(LinearMatroid): # minors, dual - cpdef _minor(self, contractions, deletions): + cpdef _minor(self, contractions, deletions) noexcept: r""" Return a minor. @@ -3793,7 +3793,7 @@ cdef class BinaryMatroid(LinearMatroid): keep_initial_representation=False) # graphicness test - cpdef is_graphic(self): + cpdef is_graphic(self) noexcept: """ Test if the binary matroid is graphic. @@ -3864,7 +3864,7 @@ cdef class BinaryMatroid(LinearMatroid): # now self is graphic iff there is a binary vector x so that M*x = 0 and x_0 = 1, so: return BinaryMatroid(m).corank(frozenset([0])) > 0 - cpdef is_valid(self): + cpdef is_valid(self) noexcept: r""" Test if the data obey the matroid axioms. @@ -3885,7 +3885,7 @@ cdef class BinaryMatroid(LinearMatroid): # representability - cpdef binary_matroid(self, randomized_tests=1, verify = True): + cpdef binary_matroid(self, randomized_tests=1, verify = True) noexcept: r""" Return a binary matroid representing ``self``. @@ -3915,7 +3915,7 @@ cdef class BinaryMatroid(LinearMatroid): """ return self - cpdef is_binary(self, randomized_tests=1): + cpdef is_binary(self, randomized_tests=1) noexcept: r""" Decide if ``self`` is a binary matroid. @@ -4193,7 +4193,7 @@ cdef class TernaryMatroid(LinearMatroid): self._one = GF3_one self._two = GF3_minus_one - cpdef base_ring(self): + cpdef base_ring(self) noexcept: r""" Return the base ring of the matrix representing the matroid, in this case `\GF{3}`. @@ -4207,7 +4207,7 @@ cdef class TernaryMatroid(LinearMatroid): global GF3 return GF3 - cpdef characteristic(self): + cpdef characteristic(self) noexcept: """ Return the characteristic of the base ring of the matrix representing the matroid, in this case `3`. @@ -4235,13 +4235,13 @@ cdef class TernaryMatroid(LinearMatroid): self._prow[y] = p BasisExchangeMatroid._exchange(self, x, y) - cdef __fundamental_cocircuit(self, bitset_t C, long x): + cdef __fundamental_cocircuit(self, bitset_t C, long x) noexcept: r""" Fill bitset `C` with the incidence vector of the `B`-fundamental cocircuit using ``x``. Internal method using packed elements. """ bitset_copy(C, (self._A)._M0[self._prow[x]]) - cdef _coclosure_internal(self, bitset_t R, bitset_t F): + cdef _coclosure_internal(self, bitset_t R, bitset_t F) noexcept: """ Bitpacked version of ``coclosure``. @@ -4264,7 +4264,7 @@ cdef class TernaryMatroid(LinearMatroid): bitset_add(R, y) y = bitset_next(self._inside, y + 1) - cdef _exchange_value_internal(self, long x, long y): + cdef _exchange_value_internal(self, long x, long y) noexcept: r""" Return the (x, y) entry of the current representation. """ @@ -4296,7 +4296,7 @@ cdef class TernaryMatroid(LinearMatroid): S = S + '-' return S - cpdef _current_rows_cols(self, B=None): + cpdef _current_rows_cols(self, B=None) noexcept: """ Return the current row and column labels of a reduced matrix. @@ -4338,7 +4338,7 @@ cdef class TernaryMatroid(LinearMatroid): c += 1 return rows, cols - cpdef LeanMatrix _basic_representation(self, B=None): + cpdef LeanMatrix _basic_representation(self, B=None) noexcept: """ Return a basic matrix representation of the matroid. @@ -4377,7 +4377,7 @@ cdef class TernaryMatroid(LinearMatroid): self._move_current_basis(B, set()) return self._A.copy() # Deprecated Sage matrix operation - cpdef LeanMatrix _reduced_representation(self, B=None): + cpdef LeanMatrix _reduced_representation(self, B=None) noexcept: r""" Return a reduced representation of the matroid, i.e. a matrix `R` such that `[I\ \ R]` represents the matroid. @@ -4419,7 +4419,7 @@ cdef class TernaryMatroid(LinearMatroid): # isomorphism - cpdef _is_isomorphic(self, other, certificate=False): + cpdef _is_isomorphic(self, other, certificate=False) noexcept: """ Test if ``self`` is isomorphic to ``other``. Internal version that performs no checks on input. @@ -4458,7 +4458,7 @@ cdef class TernaryMatroid(LinearMatroid): # invariants - cpdef _make_invariant(self): + cpdef _make_invariant(self) noexcept: """ Create an invariant. @@ -4530,7 +4530,7 @@ cdef class TernaryMatroid(LinearMatroid): self._t_partition = tuple([F, Fa, Fb, Fc]) self._t_invariant = tuple([d, c, len(F), len(Fa), len(Fb), len(Fc), p[0], p[1], p[2], p[3], p[4], p[5]]) - cpdef _invariant(self): + cpdef _invariant(self) noexcept: r""" Return a matroid invariant. @@ -4559,7 +4559,7 @@ cdef class TernaryMatroid(LinearMatroid): self._make_invariant() return self._t_invariant - cpdef bicycle_dimension(self): + cpdef bicycle_dimension(self) noexcept: r""" Return the bicycle dimension of the ternary matroid. @@ -4582,7 +4582,7 @@ cdef class TernaryMatroid(LinearMatroid): self._make_invariant() return self._t_invariant[0] - cpdef character(self): + cpdef character(self) noexcept: r""" Return the character of the ternary matroid. @@ -4608,7 +4608,7 @@ cdef class TernaryMatroid(LinearMatroid): self._make_invariant() return self._t_invariant[1] - cpdef _principal_quadripartition(self): + cpdef _principal_quadripartition(self) noexcept: r""" Return an ordered partition of the ground set. @@ -4643,7 +4643,7 @@ cdef class TernaryMatroid(LinearMatroid): self._make_invariant() return tuple([[self._E[j] for j in self._t_partition[0]], [self._E[j] for j in self._t_partition[1]], [self._E[j] for j in self._t_partition[2]], [self._E[j] for j in self._t_partition[3]]]) - cpdef TernaryMatrix _projection(self): + cpdef TernaryMatrix _projection(self) noexcept: """ Return the projection matrix onto the row space. @@ -4685,7 +4685,7 @@ cdef class TernaryMatroid(LinearMatroid): self._make_invariant() return self._t_projection - cpdef _fast_isom_test(self, other): + cpdef _fast_isom_test(self, other) noexcept: r""" Run a quick test to see if two ternary matroids are isomorphic. @@ -4716,7 +4716,7 @@ cdef class TernaryMatroid(LinearMatroid): # minors, dual - cpdef _minor(self, contractions, deletions): + cpdef _minor(self, contractions, deletions) noexcept: r""" Return a minor. @@ -4758,7 +4758,7 @@ cdef class TernaryMatroid(LinearMatroid): basis=bas, keep_initial_representation=False) - cpdef is_valid(self): + cpdef is_valid(self) noexcept: r""" Test if the data obey the matroid axioms. @@ -4779,7 +4779,7 @@ cdef class TernaryMatroid(LinearMatroid): # representability - cpdef ternary_matroid(self, randomized_tests=1, verify = True): + cpdef ternary_matroid(self, randomized_tests=1, verify = True) noexcept: r""" Return a ternary matroid representing ``self``. @@ -4809,7 +4809,7 @@ cdef class TernaryMatroid(LinearMatroid): """ return self - cpdef is_ternary(self, randomized_tests=1): + cpdef is_ternary(self, randomized_tests=1) noexcept: r""" Decide if ``self`` is a binary matroid. @@ -5094,7 +5094,7 @@ cdef class QuaternaryMatroid(LinearMatroid): self._x_zero = (self._A)._x_zero self._x_one = (self._A)._x_one - cpdef base_ring(self): + cpdef base_ring(self) noexcept: r""" Return the base ring of the matrix representing the matroid, in this case `\GF{4}`. @@ -5108,7 +5108,7 @@ cdef class QuaternaryMatroid(LinearMatroid): """ return (self._A).base_ring() - cpdef characteristic(self): + cpdef characteristic(self) noexcept: """ Return the characteristic of the base ring of the matrix representing the matroid, in this case `2`. @@ -5137,13 +5137,13 @@ cdef class QuaternaryMatroid(LinearMatroid): self._prow[y] = p BasisExchangeMatroid._exchange(self, x, y) - cdef __fundamental_cocircuit(self, bitset_t C, long x): + cdef __fundamental_cocircuit(self, bitset_t C, long x) noexcept: r""" Fill bitset `C` with the incidence vector of the `B`-fundamental cocircuit using ``x``. Internal method using packed elements. """ bitset_union(C, (self._A)._M0[self._prow[x]], (self._A)._M1[self._prow[x]]) - cdef _coclosure_internal(self, bitset_t R, bitset_t F): + cdef _coclosure_internal(self, bitset_t R, bitset_t F) noexcept: """ Bitpacked version of ``coclosure``. @@ -5166,7 +5166,7 @@ cdef class QuaternaryMatroid(LinearMatroid): bitset_add(R, y) y = bitset_next(self._inside, y + 1) - cdef _exchange_value_internal(self, long x, long y): + cdef _exchange_value_internal(self, long x, long y) noexcept: r""" Return the (x, y) entry of the current representation. """ @@ -5186,7 +5186,7 @@ cdef class QuaternaryMatroid(LinearMatroid): S = "Quaternary matroid of rank " + str(self.rank()) + " on " + str(self.size()) + " elements" return S - cpdef _current_rows_cols(self, B=None): + cpdef _current_rows_cols(self, B=None) noexcept: """ Return the current row and column labels of a reduced matrix. @@ -5229,7 +5229,7 @@ cdef class QuaternaryMatroid(LinearMatroid): c += 1 return rows, cols - cpdef LeanMatrix _basic_representation(self, B=None): + cpdef LeanMatrix _basic_representation(self, B=None) noexcept: """ Return a basic matrix representation of the matroid. @@ -5272,7 +5272,7 @@ cdef class QuaternaryMatroid(LinearMatroid): self._move_current_basis(B, set()) return self._A.copy() # Deprecated Sage matrix operation - cpdef LeanMatrix _reduced_representation(self, B=None): + cpdef LeanMatrix _reduced_representation(self, B=None) noexcept: r""" Return a reduced representation of the matroid, i.e. a matrix `R` such that `[I\ \ R]` represents the matroid. @@ -5316,7 +5316,7 @@ cdef class QuaternaryMatroid(LinearMatroid): _, cols = self._current_rows_cols() return self._A.matrix_from_rows_and_columns(range(self.full_rank()), [self._idx[e] for e in cols]) - cpdef _make_invariant(self): + cpdef _make_invariant(self) noexcept: """ Create an invariant. @@ -5383,7 +5383,7 @@ cdef class QuaternaryMatroid(LinearMatroid): self._q_partition = tuple([F, Fa, Fb]) self._q_invariant = tuple([d, len(F), len(Fa), len(Fb), p[0], p[1], p[2]]) - cpdef _invariant(self): + cpdef _invariant(self) noexcept: r""" Return a matroid invariant. @@ -5412,7 +5412,7 @@ cdef class QuaternaryMatroid(LinearMatroid): self._make_invariant() return self._q_invariant - cpdef bicycle_dimension(self): + cpdef bicycle_dimension(self) noexcept: r""" Return the bicycle dimension of the quaternary matroid. @@ -5439,7 +5439,7 @@ cdef class QuaternaryMatroid(LinearMatroid): self._make_invariant() return self._q_invariant[0] - cpdef _principal_tripartition(self): + cpdef _principal_tripartition(self) noexcept: r""" Return the principal tripartition of the quaternary matroid. @@ -5478,7 +5478,7 @@ cdef class QuaternaryMatroid(LinearMatroid): P = self._q_partition return frozenset([self._E[e] for e in P[0]]), frozenset([self._E[e] for e in P[1]]), frozenset([self._E[e] for e in P[2]]) - cpdef _fast_isom_test(self, other): + cpdef _fast_isom_test(self, other) noexcept: r""" Run a quick test to see if two quaternary matroids are isomorphic. @@ -5507,7 +5507,7 @@ cdef class QuaternaryMatroid(LinearMatroid): # minors, dual - cpdef _minor(self, contractions, deletions): + cpdef _minor(self, contractions, deletions) noexcept: r""" Return a minor. @@ -5549,7 +5549,7 @@ cdef class QuaternaryMatroid(LinearMatroid): basis=bas, keep_initial_representation=False) - cpdef is_valid(self): + cpdef is_valid(self) noexcept: r""" Test if the data obey the matroid axioms. @@ -5769,7 +5769,7 @@ cdef class RegularMatroid(LinearMatroid): """ LinearMatroid.__init__(self, matrix, groundset, reduced_matrix, ring=ZZ, keep_initial_representation=keep_initial_representation) - cdef list _setup_internal_representation(self, matrix, reduced_matrix, ring, keep_initial_representation): + cdef list _setup_internal_representation(self, matrix, reduced_matrix, ring, keep_initial_representation) noexcept: """ Setup the internal representation matrix ``self._A`` and the array of row- and column indices ``self._prow``. @@ -5812,7 +5812,7 @@ cdef class RegularMatroid(LinearMatroid): self._prow[self._A.nrows() + r] = r return P - cpdef base_ring(self): + cpdef base_ring(self) noexcept: r""" Return the base ring of the matrix representing the matroid, in this case `\ZZ`. @@ -5825,7 +5825,7 @@ cdef class RegularMatroid(LinearMatroid): """ return ZZ - cpdef characteristic(self): + cpdef characteristic(self) noexcept: """ Return the characteristic of the base ring of the matrix representing the matroid, in this case `0`. @@ -5869,7 +5869,7 @@ cdef class RegularMatroid(LinearMatroid): self._prow[x] = py BasisExchangeMatroid._exchange(self, x, y) - cdef _exchange_value_internal(self, long x, long y): + cdef _exchange_value_internal(self, long x, long y) noexcept: r""" Return the (x, y) entry of the current representation. @@ -5896,7 +5896,7 @@ cdef class RegularMatroid(LinearMatroid): S = "Regular matroid of rank " + str(self.rank()) + " on " + str(self.size()) + " elements with " + str(self.bases_count()) + " bases" return S - cpdef bases_count(self): + cpdef bases_count(self) noexcept: """ Count the number of bases. @@ -5916,7 +5916,7 @@ cdef class RegularMatroid(LinearMatroid): self._bases_count = (R * R.transpose()).det() return self._bases_count - cpdef _projection(self): + cpdef _projection(self) noexcept: """ Return the projection matrix onto the row space. @@ -5956,7 +5956,7 @@ cdef class RegularMatroid(LinearMatroid): self._r_projection = R.transpose() * (R * R.transpose()).adjugate() * R return self._r_projection - cpdef _invariant(self): + cpdef _invariant(self) noexcept: """ Compute a regular matroid invariant. @@ -6006,7 +6006,7 @@ cdef class RegularMatroid(LinearMatroid): self._r_invariant = hash(tuple([tuple([(w, A[w]) for w in sorted(A)]), tuple([(w, B[w]) for w in sorted(B)]), N])) return self._r_invariant - cpdef _hypergraph(self): + cpdef _hypergraph(self) noexcept: """ Create a bipartite digraph and a vertex partition. @@ -6089,7 +6089,7 @@ cdef class RegularMatroid(LinearMatroid): # self._r_hypergraph = self._r_hypergraph.max_refined() # return self._r_hypergraph - cpdef _is_isomorphic(self, other, certificate=False): + cpdef _is_isomorphic(self, other, certificate=False) noexcept: """ Test if ``self`` is isomorphic to ``other``. @@ -6157,7 +6157,7 @@ cdef class RegularMatroid(LinearMatroid): else: return LinearMatroid._is_isomorphic(self, other) - cpdef _fast_isom_test(self, other): + cpdef _fast_isom_test(self, other) noexcept: r""" Run a quick test to see if two regular matroids are isomorphic. @@ -6198,7 +6198,7 @@ cdef class RegularMatroid(LinearMatroid): if self._is_field_isomorphism(other, m): return True - cdef _hypertest(self, other): + cdef _hypertest(self, other) noexcept: """ Test if the hypergraphs associated with ``self`` and ``other`` are isomorphic, and if so return an isomorphism. @@ -6231,7 +6231,7 @@ cdef class RegularMatroid(LinearMatroid): idx={str(f):f for f in other.groundset()} return {e:idx[m[str(e)]] for e in self.groundset() if str(e) in m} - cpdef has_line_minor(self, k, hyperlines=None, certificate=False): + cpdef has_line_minor(self, k, hyperlines=None, certificate=False) noexcept: r""" Test if the matroid has a `U_{2, k}`-minor. @@ -6284,7 +6284,7 @@ cdef class RegularMatroid(LinearMatroid): return False return Matroid.has_line_minor(self, k, hyperlines, certificate) - cpdef _linear_extension_chains(self, F, fundamentals=None): + cpdef _linear_extension_chains(self, F, fundamentals=None) noexcept: r""" Create a list of chains that determine single-element extensions of this linear matroid representation. @@ -6321,7 +6321,7 @@ cdef class RegularMatroid(LinearMatroid): fundamentals = set([1]) return LinearMatroid._linear_extension_chains(self, F, fundamentals) - cpdef is_graphic(self): + cpdef is_graphic(self) noexcept: """ Test if the regular matroid is graphic. @@ -6354,7 +6354,7 @@ cdef class RegularMatroid(LinearMatroid): """ return BinaryMatroid(reduced_matrix=self._reduced_representation()).is_graphic() - cpdef is_valid(self): + cpdef is_valid(self) noexcept: r""" Test if the data obey the matroid axioms. @@ -6385,7 +6385,7 @@ cdef class RegularMatroid(LinearMatroid): # representation - cpdef binary_matroid(self, randomized_tests=1, verify = True): + cpdef binary_matroid(self, randomized_tests=1, verify = True) noexcept: r""" Return a binary matroid representing ``self``. @@ -6417,7 +6417,7 @@ cdef class RegularMatroid(LinearMatroid): A, E = self.representation(B = self.basis(), reduced = False, labels = True) return BinaryMatroid(matrix = A, groundset = E) - cpdef is_binary(self, randomized_tests=1): + cpdef is_binary(self, randomized_tests=1) noexcept: r""" Decide if ``self`` is a binary matroid. @@ -6445,7 +6445,7 @@ cdef class RegularMatroid(LinearMatroid): """ return True - cpdef ternary_matroid(self, randomized_tests=1, verify = True): + cpdef ternary_matroid(self, randomized_tests=1, verify = True) noexcept: r""" Return a ternary matroid representing ``self``. @@ -6477,7 +6477,7 @@ cdef class RegularMatroid(LinearMatroid): A, E = self.representation(B = self.basis(), reduced = False, labels = True) return TernaryMatroid(matrix = A, groundset = E) - cpdef is_ternary(self, randomized_tests=1): + cpdef is_ternary(self, randomized_tests=1) noexcept: r""" Decide if ``self`` is a ternary matroid. diff --git a/src/sage/matroids/matroid.pxd b/src/sage/matroids/matroid.pxd index e9ddfec96ae..6c385f10e32 100644 --- a/src/sage/matroids/matroid.pxd +++ b/src/sage/matroids/matroid.pxd @@ -7,36 +7,36 @@ cdef class Matroid(SageObject): cdef int _stored_size # virtual methods - cpdef groundset(self) - cpdef _rank(self, X) + cpdef groundset(self) noexcept + cpdef _rank(self, X) noexcept # internal methods, assuming verified input - cpdef _max_independent(self, X) - cpdef _circuit(self, X) - cpdef _fundamental_circuit(self, B, e) - cpdef _closure(self, X) - cpdef _corank(self, X) - cpdef _max_coindependent(self, X) - cpdef _cocircuit(self, X) - cpdef _fundamental_cocircuit(self, B, e) - cpdef _coclosure(self, X) - cpdef _augment(self, X, Y) - - cpdef _is_independent(self, X) - cpdef _is_basis(self, X) - cpdef _is_circuit(self, X) - cpdef _is_closed(self, X) - cpdef _is_coindependent(self, X) - cpdef _is_cobasis(self, X) - cpdef _is_cocircuit(self, X) - cpdef _is_coclosed(self, X) - - cpdef _minor(self, contractions, deletions) - cpdef _has_minor(self, N, bint certificate=*) - cpdef _line_length(self, F) - cpdef _extension(self, element, hyperplanes) - - cdef inline _subset_internal(self, X): + cpdef _max_independent(self, X) noexcept + cpdef _circuit(self, X) noexcept + cpdef _fundamental_circuit(self, B, e) noexcept + cpdef _closure(self, X) noexcept + cpdef _corank(self, X) noexcept + cpdef _max_coindependent(self, X) noexcept + cpdef _cocircuit(self, X) noexcept + cpdef _fundamental_cocircuit(self, B, e) noexcept + cpdef _coclosure(self, X) noexcept + cpdef _augment(self, X, Y) noexcept + + cpdef _is_independent(self, X) noexcept + cpdef _is_basis(self, X) noexcept + cpdef _is_circuit(self, X) noexcept + cpdef _is_closed(self, X) noexcept + cpdef _is_coindependent(self, X) noexcept + cpdef _is_cobasis(self, X) noexcept + cpdef _is_cocircuit(self, X) noexcept + cpdef _is_coclosed(self, X) noexcept + + cpdef _minor(self, contractions, deletions) noexcept + cpdef _has_minor(self, N, bint certificate=*) noexcept + cpdef _line_length(self, F) noexcept + cpdef _extension(self, element, hyperplanes) noexcept + + cdef inline _subset_internal(self, X) noexcept: """ Convert ``X`` to a ``frozenset`` and check that it is a subset of the groundset. @@ -48,7 +48,7 @@ cdef class Matroid(SageObject): raise ValueError(f"{X!r} is not a subset of the groundset") return S - cdef inline __subset_all(self, X): + cdef inline __subset_all(self, X) noexcept: """ If ``X`` is ``None``, return the groundset. @@ -66,157 +66,157 @@ cdef class Matroid(SageObject): return S # ** user-facing methods ** - cpdef size(self) + cpdef size(self) noexcept # matroid oracle - cpdef rank(self, X=*) - cpdef full_rank(self) - cpdef basis(self) - cpdef max_independent(self, X) - cpdef circuit(self, X=*) - cpdef fundamental_circuit(self, B, e) - cpdef closure(self, X) - cpdef k_closure(self, X, k) - - cpdef augment(self, X, Y=*) - - cpdef corank(self, X=*) - cpdef full_corank(self) - cpdef cobasis(self) - cpdef max_coindependent(self, X) - cpdef cocircuit(self, X=*) - cpdef fundamental_cocircuit(self, B, e) - cpdef coclosure(self, X) - - cpdef loops(self) - cpdef is_independent(self, X) - cpdef is_dependent(self, X) - cpdef is_basis(self, X) - cpdef is_circuit(self, X) - cpdef is_closed(self, X) - cpdef is_subset_k_closed(self, X, int k) - - cpdef coloops(self) - cpdef is_coindependent(self, X) - cpdef is_codependent(self, X) - cpdef is_cobasis(self, X) - cpdef is_cocircuit(self, X) - cpdef is_coclosed(self, X) + cpdef rank(self, X=*) noexcept + cpdef full_rank(self) noexcept + cpdef basis(self) noexcept + cpdef max_independent(self, X) noexcept + cpdef circuit(self, X=*) noexcept + cpdef fundamental_circuit(self, B, e) noexcept + cpdef closure(self, X) noexcept + cpdef k_closure(self, X, k) noexcept + + cpdef augment(self, X, Y=*) noexcept + + cpdef corank(self, X=*) noexcept + cpdef full_corank(self) noexcept + cpdef cobasis(self) noexcept + cpdef max_coindependent(self, X) noexcept + cpdef cocircuit(self, X=*) noexcept + cpdef fundamental_cocircuit(self, B, e) noexcept + cpdef coclosure(self, X) noexcept + + cpdef loops(self) noexcept + cpdef is_independent(self, X) noexcept + cpdef is_dependent(self, X) noexcept + cpdef is_basis(self, X) noexcept + cpdef is_circuit(self, X) noexcept + cpdef is_closed(self, X) noexcept + cpdef is_subset_k_closed(self, X, int k) noexcept + + cpdef coloops(self) noexcept + cpdef is_coindependent(self, X) noexcept + cpdef is_codependent(self, X) noexcept + cpdef is_cobasis(self, X) noexcept + cpdef is_cocircuit(self, X) noexcept + cpdef is_coclosed(self, X) noexcept # verification - cpdef is_valid(self) + cpdef is_valid(self) noexcept # enumeration - cpdef circuits(self) - cpdef nonspanning_circuits(self) - cpdef cocircuits(self) - cpdef noncospanning_cocircuits(self) - cpdef circuit_closures(self) - cpdef nonspanning_circuit_closures(self) - cpdef bases(self) - cpdef independent_sets(self) - cpdef independent_r_sets(self, long r) - cpdef nonbases(self) - cpdef dependent_r_sets(self, long r) - cpdef _extend_flags(self, flags) - cpdef _flags(self, r) - cpdef flats(self, r) - cpdef coflats(self, r) - cpdef hyperplanes(self) - cpdef f_vector(self) - cpdef broken_circuits(self, ordering=*) - cpdef no_broken_circuits_sets(self, ordering=*) + cpdef circuits(self) noexcept + cpdef nonspanning_circuits(self) noexcept + cpdef cocircuits(self) noexcept + cpdef noncospanning_cocircuits(self) noexcept + cpdef circuit_closures(self) noexcept + cpdef nonspanning_circuit_closures(self) noexcept + cpdef bases(self) noexcept + cpdef independent_sets(self) noexcept + cpdef independent_r_sets(self, long r) noexcept + cpdef nonbases(self) noexcept + cpdef dependent_r_sets(self, long r) noexcept + cpdef _extend_flags(self, flags) noexcept + cpdef _flags(self, r) noexcept + cpdef flats(self, r) noexcept + cpdef coflats(self, r) noexcept + cpdef hyperplanes(self) noexcept + cpdef f_vector(self) noexcept + cpdef broken_circuits(self, ordering=*) noexcept + cpdef no_broken_circuits_sets(self, ordering=*) noexcept # isomorphism - cpdef is_isomorphic(self, other, certificate=*) - cpdef _is_isomorphic(self, other, certificate=*) - cpdef isomorphism(self, other) - cpdef _isomorphism(self, other) - cpdef equals(self, other) - cpdef is_isomorphism(self, other, morphism) - cpdef _is_isomorphism(self, other, morphism) + cpdef is_isomorphic(self, other, certificate=*) noexcept + cpdef _is_isomorphic(self, other, certificate=*) noexcept + cpdef isomorphism(self, other) noexcept + cpdef _isomorphism(self, other) noexcept + cpdef equals(self, other) noexcept + cpdef is_isomorphism(self, other, morphism) noexcept + cpdef _is_isomorphism(self, other, morphism) noexcept # minors, dual, truncation - cpdef minor(self, contractions=*, deletions=*) - cpdef contract(self, X) - cpdef delete(self, X) - cpdef _backslash_(self, X) - cpdef dual(self) - cpdef truncation(self) - cpdef has_minor(self, N, bint certificate=*) - cpdef has_line_minor(self, k, hyperlines=*, certificate=*) - cpdef _has_line_minor(self, k, hyperlines, certificate=*) + cpdef minor(self, contractions=*, deletions=*) noexcept + cpdef contract(self, X) noexcept + cpdef delete(self, X) noexcept + cpdef _backslash_(self, X) noexcept + cpdef dual(self) noexcept + cpdef truncation(self) noexcept + cpdef has_minor(self, N, bint certificate=*) noexcept + cpdef has_line_minor(self, k, hyperlines=*, certificate=*) noexcept + cpdef _has_line_minor(self, k, hyperlines, certificate=*) noexcept # extension - cpdef extension(self, element=*, subsets=*) - cpdef coextension(self, element=*, subsets=*) - cpdef modular_cut(self, subsets) - cpdef linear_subclasses(self, line_length=*, subsets=*) - cpdef extensions(self, element=*, line_length=*, subsets=*) + cpdef extension(self, element=*, subsets=*) noexcept + cpdef coextension(self, element=*, subsets=*) noexcept + cpdef modular_cut(self, subsets) noexcept + cpdef linear_subclasses(self, line_length=*, subsets=*) noexcept + cpdef extensions(self, element=*, line_length=*, subsets=*) noexcept # connectivity - cpdef simplify(self) - cpdef cosimplify(self) - cpdef is_simple(self) - cpdef is_cosimple(self) - cpdef components(self) - cpdef is_connected(self, certificate=*) - cpdef connectivity(self, S, T=*) - cpdef _connectivity(self, S, T) - cpdef is_kconnected(self, k, certificate=*) - cpdef link(self, S, T) - cpdef _link(self, S, T) - cpdef _is_3connected_shifting(self, certificate=*) - cpdef _is_4connected_shifting(self, certificate=*) - cpdef _shifting_all(self, X, P_rows, P_cols, Q_rows, Q_cols, m) - cpdef _shifting(self, X, X_1, Y_2, X_2, Y_1, m) - cpdef is_3connected(self, certificate=*, algorithm=*) - cpdef is_4connected(self, certificate=*, algorithm=*) - cpdef _is_3connected_CE(self, certificate=*) - cpdef _is_3connected_BC(self, certificate=*) - cpdef _is_3connected_BC_recursion(self, basis, fund_cocircuits) + cpdef simplify(self) noexcept + cpdef cosimplify(self) noexcept + cpdef is_simple(self) noexcept + cpdef is_cosimple(self) noexcept + cpdef components(self) noexcept + cpdef is_connected(self, certificate=*) noexcept + cpdef connectivity(self, S, T=*) noexcept + cpdef _connectivity(self, S, T) noexcept + cpdef is_kconnected(self, k, certificate=*) noexcept + cpdef link(self, S, T) noexcept + cpdef _link(self, S, T) noexcept + cpdef _is_3connected_shifting(self, certificate=*) noexcept + cpdef _is_4connected_shifting(self, certificate=*) noexcept + cpdef _shifting_all(self, X, P_rows, P_cols, Q_rows, Q_cols, m) noexcept + cpdef _shifting(self, X, X_1, Y_2, X_2, Y_1, m) noexcept + cpdef is_3connected(self, certificate=*, algorithm=*) noexcept + cpdef is_4connected(self, certificate=*, algorithm=*) noexcept + cpdef _is_3connected_CE(self, certificate=*) noexcept + cpdef _is_3connected_BC(self, certificate=*) noexcept + cpdef _is_3connected_BC_recursion(self, basis, fund_cocircuits) noexcept # representability - cpdef _local_binary_matroid(self, basis=*) - cpdef binary_matroid(self, randomized_tests=*, verify=*) - cpdef is_binary(self, randomized_tests=*) - cpdef _local_ternary_matroid(self, basis=*) - cpdef ternary_matroid(self, randomized_tests=*, verify=*) - cpdef is_ternary(self, randomized_tests=*) + cpdef _local_binary_matroid(self, basis=*) noexcept + cpdef binary_matroid(self, randomized_tests=*, verify=*) noexcept + cpdef is_binary(self, randomized_tests=*) noexcept + cpdef _local_ternary_matroid(self, basis=*) noexcept + cpdef ternary_matroid(self, randomized_tests=*, verify=*) noexcept + cpdef is_ternary(self, randomized_tests=*) noexcept # matroid k-closed - cpdef is_k_closed(self, int k) + cpdef is_k_closed(self, int k) noexcept # matroid chordality - cpdef _is_circuit_chordal(self, frozenset C, bint certificate=*) - cpdef is_circuit_chordal(self, C, bint certificate=*) - cpdef is_chordal(self, k1=*, k2=*, bint certificate=*) - cpdef chordality(self) + cpdef _is_circuit_chordal(self, frozenset C, bint certificate=*) noexcept + cpdef is_circuit_chordal(self, C, bint certificate=*) noexcept + cpdef is_chordal(self, k1=*, k2=*, bint certificate=*) noexcept + cpdef chordality(self) noexcept # optimization - cpdef max_weight_independent(self, X=*, weights=*) - cpdef max_weight_coindependent(self, X=*, weights=*) - cpdef is_max_weight_independent_generic(self, X=*, weights=*) - cpdef is_max_weight_coindependent_generic(self, X=*, weights=*) - cpdef intersection(self, other, weights=*) - cpdef _intersection(self, other, weights) - cpdef _intersection_augmentation(self, other, weights, Y) - cpdef intersection_unweighted(self, other) - cpdef _intersection_unweighted(self, other) - cpdef _intersection_augmentation_unweighted(self, other, Y) - cpdef partition(self) + cpdef max_weight_independent(self, X=*, weights=*) noexcept + cpdef max_weight_coindependent(self, X=*, weights=*) noexcept + cpdef is_max_weight_independent_generic(self, X=*, weights=*) noexcept + cpdef is_max_weight_coindependent_generic(self, X=*, weights=*) noexcept + cpdef intersection(self, other, weights=*) noexcept + cpdef _intersection(self, other, weights) noexcept + cpdef _intersection_augmentation(self, other, weights, Y) noexcept + cpdef intersection_unweighted(self, other) noexcept + cpdef _intersection_unweighted(self, other) noexcept + cpdef _intersection_augmentation_unweighted(self, other, Y) noexcept + cpdef partition(self) noexcept # invariants - cpdef _internal(self, B) - cpdef _external(self, B) - cpdef tutte_polynomial(self, x=*, y=*) - cpdef flat_cover(self, solver=*, verbose=*, integrality_tolerance=*) + cpdef _internal(self, B) noexcept + cpdef _external(self, B) noexcept + cpdef tutte_polynomial(self, x=*, y=*) noexcept + cpdef flat_cover(self, solver=*, verbose=*, integrality_tolerance=*) noexcept # misc - cpdef bergman_complex(self) - cpdef augmented_bergman_complex(self) + cpdef bergman_complex(self) noexcept + cpdef augmented_bergman_complex(self) noexcept # visualization - cpdef plot(self,B=*,lineorders=*,pos_method=*,pos_dict=*,save_pos=*) - cpdef show(self,B=*,lineorders=*,pos_method=*,pos_dict=*,save_pos=*,lims=*) - cpdef _fix_positions(self,pos_dict=*,lineorders=*) + cpdef plot(self,B=*,lineorders=*,pos_method=*,pos_dict=*,save_pos=*) noexcept + cpdef show(self,B=*,lineorders=*,pos_method=*,pos_dict=*,save_pos=*,lims=*) noexcept + cpdef _fix_positions(self,pos_dict=*,lineorders=*) noexcept diff --git a/src/sage/matroids/matroid.pyx b/src/sage/matroids/matroid.pyx index 93976cd6e43..51692e8f1c1 100644 --- a/src/sage/matroids/matroid.pyx +++ b/src/sage/matroids/matroid.pyx @@ -459,7 +459,7 @@ cdef class Matroid(SageObject): # virtual methods - cpdef groundset(self): + cpdef groundset(self) noexcept: """ Return the groundset of the matroid. @@ -485,7 +485,7 @@ cdef class Matroid(SageObject): """ raise NotImplementedError("subclasses need to implement this.") - cpdef _rank(self, X): + cpdef _rank(self, X) noexcept: r""" Return the rank of a set ``X``. @@ -520,7 +520,7 @@ cdef class Matroid(SageObject): # for better efficiency, its best to override the following methods in # each derived class - cpdef _max_independent(self, X): + cpdef _max_independent(self, X) noexcept: """ Compute a maximal independent subset. @@ -552,7 +552,7 @@ cdef class Matroid(SageObject): res.discard(e) return frozenset(res) - cpdef _circuit(self, X): + cpdef _circuit(self, X) noexcept: """ Return a minimal dependent subset. @@ -591,7 +591,7 @@ cdef class Matroid(SageObject): l -= 1 return frozenset(Z) - cpdef _fundamental_circuit(self, B, e): + cpdef _fundamental_circuit(self, B, e) noexcept: r""" Return the `B`-fundamental circuit using `e`. @@ -614,7 +614,7 @@ cdef class Matroid(SageObject): """ return self._circuit(B.union([e])) - cpdef _closure(self, X): + cpdef _closure(self, X) noexcept: """ Return the closure of a set. @@ -643,7 +643,7 @@ cdef class Matroid(SageObject): X.discard(y) return frozenset(X) - cpdef _corank(self, X): + cpdef _corank(self, X) noexcept: """ Return the corank of a set. @@ -665,7 +665,7 @@ cdef class Matroid(SageObject): """ return len(X) + self._rank(self.groundset().difference(X)) - self.full_rank() - cpdef _max_coindependent(self, X): + cpdef _max_coindependent(self, X) noexcept: """ Compute a maximal coindependent subset. @@ -697,7 +697,7 @@ cdef class Matroid(SageObject): res.discard(e) return frozenset(res) - cpdef _cocircuit(self, X): + cpdef _cocircuit(self, X) noexcept: """ Return a minimal codependent subset. @@ -736,7 +736,7 @@ cdef class Matroid(SageObject): l -= 1 return frozenset(Z) - cpdef _fundamental_cocircuit(self, B, e): + cpdef _fundamental_cocircuit(self, B, e) noexcept: r""" Return the `B`-fundamental circuit using `e`. @@ -759,7 +759,7 @@ cdef class Matroid(SageObject): """ return self._cocircuit(self.groundset().difference(B).union([e])) - cpdef _coclosure(self, X): + cpdef _coclosure(self, X) noexcept: """ Return the coclosure of a set. @@ -788,7 +788,7 @@ cdef class Matroid(SageObject): X.discard(y) return frozenset(X) - cpdef _augment(self, X, Y): + cpdef _augment(self, X, Y) noexcept: r""" Return a maximal subset `I` of `Y` such that `r(X + I)=r(X) + r(I)`. @@ -828,7 +828,7 @@ cdef class Matroid(SageObject): # override the following methods for even better efficiency - cpdef _is_independent(self, X): + cpdef _is_independent(self, X) noexcept: """ Test if input is independent. @@ -852,7 +852,7 @@ cdef class Matroid(SageObject): """ return len(X) == self._rank(X) - cpdef _is_basis(self, X): + cpdef _is_basis(self, X) noexcept: """ Test if input is a basis. @@ -888,7 +888,7 @@ cdef class Matroid(SageObject): """ return self._is_independent(X) - cpdef _is_circuit(self, X): + cpdef _is_circuit(self, X) noexcept: """ Test if input is a circuit. @@ -923,7 +923,7 @@ cdef class Matroid(SageObject): Z.add(x) return True - cpdef _is_closed(self, X): + cpdef _is_closed(self, X) noexcept: """ Test if input is a closed set. @@ -955,7 +955,7 @@ cdef class Matroid(SageObject): X.discard(y) return True - cpdef _is_coindependent(self, X): + cpdef _is_coindependent(self, X) noexcept: """ Test if input is coindependent. @@ -979,7 +979,7 @@ cdef class Matroid(SageObject): """ return self._corank(X) == len(X) - cpdef _is_cobasis(self, X): + cpdef _is_cobasis(self, X) noexcept: """ Test if input is a cobasis. @@ -1010,7 +1010,7 @@ cdef class Matroid(SageObject): """ return self._is_basis(self.groundset().difference(X)) - cpdef _is_cocircuit(self, X): + cpdef _is_cocircuit(self, X) noexcept: """ Test if input is a cocircuit. @@ -1045,7 +1045,7 @@ cdef class Matroid(SageObject): Z.add(x) return True - cpdef _is_coclosed(self, X): + cpdef _is_coclosed(self, X) noexcept: """ Test if input is a coclosed set. @@ -1077,7 +1077,7 @@ cdef class Matroid(SageObject): X.discard(y) return True - cpdef _minor(self, contractions, deletions): + cpdef _minor(self, contractions, deletions) noexcept: r""" Return a minor. @@ -1116,7 +1116,7 @@ cdef class Matroid(SageObject): from . import minor_matroid return minor_matroid.MinorMatroid(self, contractions, deletions) - cpdef _has_minor(self, N, bint certificate=False): + cpdef _has_minor(self, N, bint certificate=False) noexcept: """ Test if matroid has the specified minor, and optionally return frozensets ``X`` and ``Y`` so that ``N`` is isomorphic to ``self.minor(X, Y)``. @@ -1172,7 +1172,7 @@ cdef class Matroid(SageObject): return False, None return False - cpdef _line_length(self, F): + cpdef _line_length(self, F) noexcept: """ Compute the length of the line specified through flat ``F``. @@ -1198,7 +1198,7 @@ cdef class Matroid(SageObject): """ return len(self.minor(contractions=F).simplify()) - cpdef _extension(self, element, hyperplanes): + cpdef _extension(self, element, hyperplanes) noexcept: """ Extend the matroid by a new element. @@ -1266,7 +1266,7 @@ cdef class Matroid(SageObject): """ return self.size() - cpdef size(self): + cpdef size(self) noexcept: """ Return the size of the groundset. @@ -1343,7 +1343,7 @@ cdef class Matroid(SageObject): # User-visible methods - cpdef rank(self, X=None): + cpdef rank(self, X=None) noexcept: r""" Return the rank of ``X``. @@ -1377,7 +1377,7 @@ cdef class Matroid(SageObject): return self.full_rank() return self._rank(self._subset_internal(X)) - cpdef full_rank(self): + cpdef full_rank(self) noexcept: r""" Return the rank of the matroid. @@ -1400,7 +1400,7 @@ cdef class Matroid(SageObject): self._stored_full_rank = self._rank(self.groundset()) return self._stored_full_rank - cpdef basis(self): + cpdef basis(self) noexcept: r""" Return an arbitrary basis of the matroid. @@ -1429,7 +1429,7 @@ cdef class Matroid(SageObject): """ return self._max_independent(self.groundset()) - cpdef max_independent(self, X): + cpdef max_independent(self, X) noexcept: """ Compute a maximal independent subset of ``X``. @@ -1456,7 +1456,7 @@ cdef class Matroid(SageObject): """ return self._max_independent(self._subset_internal(X)) - cpdef circuit(self, X=None): + cpdef circuit(self, X=None) noexcept: """ Return a circuit. @@ -1498,7 +1498,7 @@ cdef class Matroid(SageObject): """ return self._circuit(self.__subset_all(X)) - cpdef fundamental_circuit(self, B, e): + cpdef fundamental_circuit(self, B, e) noexcept: r""" Return the `B`-fundamental circuit using `e`. @@ -1533,7 +1533,7 @@ cdef class Matroid(SageObject): raise ValueError("input e is not an element of the groundset.") return self._fundamental_circuit(B, e) - cpdef closure(self, X): + cpdef closure(self, X) noexcept: """ Return the closure of a set ``X``. @@ -1561,7 +1561,7 @@ cdef class Matroid(SageObject): """ return self._closure(self._subset_internal(X)) - cpdef k_closure(self, X, k): + cpdef k_closure(self, X, k) noexcept: r""" Return the ``k``-closure of ``X``. @@ -1611,7 +1611,7 @@ cdef class Matroid(SageObject): S = cl return S - cpdef augment(self, X, Y=None): + cpdef augment(self, X, Y=None) noexcept: r""" Return a maximal subset `I` of `Y - X` such that `r(X + I) = r(X) + r(I)`. @@ -1649,7 +1649,7 @@ cdef class Matroid(SageObject): Y = self.__subset_all(Y) return self._augment(X, Y.difference(X)) - cpdef corank(self, X=None): + cpdef corank(self, X=None) noexcept: r""" Return the corank of ``X``, or the corank of the groundset if ``X`` is ``None``. @@ -1686,7 +1686,7 @@ cdef class Matroid(SageObject): """ return self._corank(self.__subset_all(X)) - cpdef full_corank(self): + cpdef full_corank(self) noexcept: """ Return the corank of the matroid. @@ -1710,7 +1710,7 @@ cdef class Matroid(SageObject): """ return self.size() - self.full_rank() - cpdef cobasis(self): + cpdef cobasis(self) noexcept: """ Return an arbitrary cobasis of the matroid. @@ -1746,7 +1746,7 @@ cdef class Matroid(SageObject): """ return self.max_coindependent(self.groundset()) - cpdef max_coindependent(self, X): + cpdef max_coindependent(self, X) noexcept: """ Compute a maximal coindependent subset of ``X``. @@ -1784,7 +1784,7 @@ cdef class Matroid(SageObject): """ return self._max_coindependent(self._subset_internal(X)) - cpdef coclosure(self, X): + cpdef coclosure(self, X) noexcept: """ Return the coclosure of a set ``X``. @@ -1816,7 +1816,7 @@ cdef class Matroid(SageObject): """ return self._coclosure(self._subset_internal(X)) - cpdef cocircuit(self, X=None): + cpdef cocircuit(self, X=None) noexcept: """ Return a cocircuit. @@ -1864,7 +1864,7 @@ cdef class Matroid(SageObject): """ return self._cocircuit(self.__subset_all(X)) - cpdef fundamental_cocircuit(self, B, e): + cpdef fundamental_cocircuit(self, B, e) noexcept: r""" Return the `B`-fundamental cocircuit using `e`. @@ -1903,7 +1903,7 @@ cdef class Matroid(SageObject): raise ValueError("input e is not an element of B.") return self._fundamental_cocircuit(B, e) - cpdef loops(self): + cpdef loops(self) noexcept: r""" Return the set of loops of the matroid. @@ -1924,7 +1924,7 @@ cdef class Matroid(SageObject): """ return self._closure(set()) - cpdef is_independent(self, X): + cpdef is_independent(self, X) noexcept: r""" Check if a subset ``X`` is independent in the matroid. @@ -1950,7 +1950,7 @@ cdef class Matroid(SageObject): """ return self._is_independent(self._subset_internal(X)) - cpdef is_dependent(self, X): + cpdef is_dependent(self, X) noexcept: r""" Check if a subset ``X`` is dependent in the matroid. @@ -1976,7 +1976,7 @@ cdef class Matroid(SageObject): """ return not self._is_independent(self._subset_internal(X)) - cpdef is_basis(self, X): + cpdef is_basis(self, X) noexcept: r""" Check if a subset is a basis of the matroid. @@ -2005,7 +2005,7 @@ cdef class Matroid(SageObject): return False return self._is_basis(X) - cpdef is_closed(self, X): + cpdef is_closed(self, X) noexcept: r""" Test if a subset is a closed set of the matroid. @@ -2038,7 +2038,7 @@ cdef class Matroid(SageObject): """ return self._is_closed(self._subset_internal(X)) - cpdef is_subset_k_closed(self, X, int k): + cpdef is_subset_k_closed(self, X, int k) noexcept: r""" Test if ``X`` is a ``k``-closed set of the matroid. @@ -2093,7 +2093,7 @@ cdef class Matroid(SageObject): return False return True - cpdef is_circuit(self, X): + cpdef is_circuit(self, X) noexcept: r""" Test if a subset is a circuit of the matroid. @@ -2121,7 +2121,7 @@ cdef class Matroid(SageObject): """ return self._is_circuit(self._subset_internal(X)) - cpdef coloops(self): + cpdef coloops(self) noexcept: r""" Return the set of coloops of the matroid. @@ -2148,7 +2148,7 @@ cdef class Matroid(SageObject): """ return self._coclosure(set()) - cpdef is_coindependent(self, X): + cpdef is_coindependent(self, X) noexcept: r""" Check if a subset is coindependent in the matroid. @@ -2181,7 +2181,7 @@ cdef class Matroid(SageObject): """ return self._is_coindependent(self._subset_internal(X)) - cpdef is_codependent(self, X): + cpdef is_codependent(self, X) noexcept: r""" Check if a subset is codependent in the matroid. @@ -2214,7 +2214,7 @@ cdef class Matroid(SageObject): """ return not self._is_coindependent(self._subset_internal(X)) - cpdef is_cobasis(self, X): + cpdef is_cobasis(self, X) noexcept: r""" Check if a subset is a cobasis of the matroid. @@ -2251,7 +2251,7 @@ cdef class Matroid(SageObject): return False return self._is_cobasis(X) - cpdef is_cocircuit(self, X): + cpdef is_cocircuit(self, X) noexcept: r""" Test if a subset is a cocircuit of the matroid. @@ -2285,7 +2285,7 @@ cdef class Matroid(SageObject): """ return self._is_cocircuit(self._subset_internal(X)) - cpdef is_coclosed(self, X): + cpdef is_coclosed(self, X) noexcept: r""" Test if a subset is a coclosed set of the matroid. @@ -2320,7 +2320,7 @@ cdef class Matroid(SageObject): # verification - cpdef is_valid(self): + cpdef is_valid(self) noexcept: r""" Test if the data obey the matroid axioms. @@ -2372,7 +2372,7 @@ cdef class Matroid(SageObject): # enumeration - cpdef circuits(self): + cpdef circuits(self) noexcept: """ Return the list of circuits of the matroid. @@ -2400,7 +2400,7 @@ cdef class Matroid(SageObject): for e in self.groundset().difference(B)]) return list(C) - cpdef nonspanning_circuits(self): + cpdef nonspanning_circuits(self) noexcept: """ Return the list of nonspanning circuits of the matroid. @@ -2430,7 +2430,7 @@ cdef class Matroid(SageObject): C.add(self._circuit(N)) return list(C) - cpdef cocircuits(self): + cpdef cocircuits(self) noexcept: """ Return the list of cocircuits of the matroid. @@ -2455,7 +2455,7 @@ cdef class Matroid(SageObject): C.update([self._cocircuit(self.groundset().difference(B).union(set([e]))) for e in B]) return list(C) - cpdef noncospanning_cocircuits(self): + cpdef noncospanning_cocircuits(self) noexcept: """ Return the list of noncospanning cocircuits of the matroid. @@ -2481,7 +2481,7 @@ cdef class Matroid(SageObject): """ return self.dual().nonspanning_circuits() - cpdef circuit_closures(self): + cpdef circuit_closures(self) noexcept: """ Return the list of closures of circuits of the matroid. @@ -2517,7 +2517,7 @@ cdef class Matroid(SageObject): CC[len(C) - 1].add(self.closure(C)) return {r: CC[r] for r in range(self.rank() + 1) if CC[r]} - cpdef nonspanning_circuit_closures(self): + cpdef nonspanning_circuit_closures(self) noexcept: """ Return the list of closures of nonspanning circuits of the matroid. @@ -2550,7 +2550,7 @@ cdef class Matroid(SageObject): CC[len(C) - 1].add(self.closure(C)) return {r: CC[r] for r in range(self.rank() + 1) if CC[r]} - cpdef nonbases(self): + cpdef nonbases(self) noexcept: r""" Return the list of nonbases of the matroid. @@ -2584,7 +2584,7 @@ cdef class Matroid(SageObject): res.append(X) return res - cpdef dependent_r_sets(self, long r): + cpdef dependent_r_sets(self, long r) noexcept: r""" Return the list of dependent subsets of fixed size. @@ -2617,7 +2617,7 @@ cdef class Matroid(SageObject): res.append(X) return res - cpdef bases(self): + cpdef bases(self) noexcept: r""" Return the list of bases of the matroid. @@ -2649,7 +2649,7 @@ cdef class Matroid(SageObject): res.append(X) return res - cpdef independent_sets(self): + cpdef independent_sets(self) noexcept: r""" Return the list of independent subsets of the matroid. @@ -2693,7 +2693,7 @@ cdef class Matroid(SageObject): r -= 1 return res - cpdef independent_r_sets(self, long r): + cpdef independent_r_sets(self, long r) noexcept: r""" Return the list of size-``r`` independent subsets of the matroid. @@ -2733,7 +2733,7 @@ cdef class Matroid(SageObject): res.append(X) return res - cpdef _extend_flags(self, flags): + cpdef _extend_flags(self, flags) noexcept: r""" Recursion for the ``self._flags(r)`` method. @@ -2759,7 +2759,7 @@ cdef class Matroid(SageObject): X = newX return newflags - cpdef _flags(self, r): + cpdef _flags(self, r) noexcept: r""" Compute rank-``r`` flats, with extra information for more speed. @@ -2797,7 +2797,7 @@ cdef class Matroid(SageObject): flags = self._extend_flags(flags) return flags - cpdef flats(self, r): + cpdef flats(self, r) noexcept: r""" Return the collection of flats of the matroid of specified rank. @@ -2826,7 +2826,7 @@ cdef class Matroid(SageObject): return SetSystem(list(self.groundset()), subsets=[f[0] for f in self._flags(r)]) - cpdef coflats(self, r): + cpdef coflats(self, r) noexcept: r""" Return the collection of coflats of the matroid of specified corank. @@ -2869,7 +2869,7 @@ cdef class Matroid(SageObject): for X in self.flats(i)] return LatticePoset((F, lambda x, y: x < y)) - cpdef hyperplanes(self): + cpdef hyperplanes(self) noexcept: """ Return the set of hyperplanes of the matroid. @@ -2893,7 +2893,7 @@ cdef class Matroid(SageObject): """ return self.flats(self.full_rank() - 1) - cpdef f_vector(self): + cpdef f_vector(self) noexcept: r""" Return the `f`-vector of the matroid. @@ -2919,7 +2919,7 @@ cdef class Matroid(SageObject): f_vec.append(len(flags)) return f_vec - cpdef broken_circuits(self, ordering=None): + cpdef broken_circuits(self, ordering=None) noexcept: r""" Return the list of broken circuits of ``self``. @@ -2961,7 +2961,7 @@ cdef class Matroid(SageObject): break return frozenset(ret) - cpdef no_broken_circuits_sets(self, ordering=None): + cpdef no_broken_circuits_sets(self, ordering=None) noexcept: r""" Return the no broken circuits (NBC) sets of ``self``. @@ -3197,7 +3197,7 @@ cdef class Matroid(SageObject): # isomorphism and equality - cpdef is_isomorphic(self, other, certificate=False): + cpdef is_isomorphic(self, other, certificate=False) noexcept: r""" Test matroid isomorphism. @@ -3241,7 +3241,7 @@ cdef class Matroid(SageObject): raise TypeError("can only test for isomorphism between matroids.") return self._is_isomorphic(other, certificate) - cpdef _is_isomorphic(self, other, certificate=False): + cpdef _is_isomorphic(self, other, certificate=False) noexcept: """ Test if ``self`` is isomorphic to ``other``. @@ -3282,7 +3282,7 @@ cdef class Matroid(SageObject): return True return (self.full_rank() == other.full_rank() and self.nonbases()._isomorphism(other.nonbases()) is not None) - cpdef isomorphism(self, other): + cpdef isomorphism(self, other) noexcept: r""" Return a matroid isomorphism. @@ -3321,7 +3321,7 @@ cdef class Matroid(SageObject): raise TypeError("can only give isomorphism between matroids.") return self._isomorphism(other) - cpdef _isomorphism(self, other): + cpdef _isomorphism(self, other) noexcept: """ Return isomorphism from ``self`` to ``other``, if such an isomorphism exists. @@ -3354,7 +3354,7 @@ cdef class Matroid(SageObject): else: return None - cpdef equals(self, other): + cpdef equals(self, other) noexcept: """ Test for matroid equality. @@ -3441,7 +3441,7 @@ cdef class Matroid(SageObject): morphism = {e: e for e in self.groundset()} return self._is_isomorphism(other, morphism) - cpdef is_isomorphism(self, other, morphism): + cpdef is_isomorphism(self, other, morphism) noexcept: r""" Test if a provided morphism induces a matroid isomorphism. @@ -3580,7 +3580,7 @@ cdef class Matroid(SageObject): return False return self._is_isomorphism(other, mf) - cpdef _is_isomorphism(self, other, morphism): + cpdef _is_isomorphism(self, other, morphism) noexcept: r""" Version of :meth:`is_isomorphism` that does no type checking. @@ -3699,7 +3699,7 @@ cdef class Matroid(SageObject): # Minors and duality - cpdef minor(self, contractions=None, deletions=None): + cpdef minor(self, contractions=None, deletions=None) noexcept: r""" Return the minor of ``self`` obtained by contracting, respectively deleting, the element(s) of ``contractions`` and ``deletions``. @@ -3815,7 +3815,7 @@ cdef class Matroid(SageObject): conset, delset = sanitize_contractions_deletions(self, contractions, deletions) return self._minor(conset, delset) - cpdef contract(self, X): + cpdef contract(self, X) noexcept: r""" Contract elements. @@ -3895,7 +3895,7 @@ cdef class Matroid(SageObject): """ return self.contract(X) - cpdef delete(self, X): + cpdef delete(self, X) noexcept: r""" Delete elements. @@ -3961,7 +3961,7 @@ cdef class Matroid(SageObject): """ return self.minor(deletions=X) - cpdef _backslash_(self, X): + cpdef _backslash_(self, X) noexcept: r""" Shorthand for ``self.delete(X)``. @@ -3978,7 +3978,7 @@ cdef class Matroid(SageObject): deprecation(36394, 'the backslash operator has been deprecated; use M.delete(X) instead') return self.delete(X) - cpdef dual(self): + cpdef dual(self) noexcept: r""" Return the dual of the matroid. @@ -4012,7 +4012,7 @@ cdef class Matroid(SageObject): from . import dual_matroid return dual_matroid.DualMatroid(self) - cpdef truncation(self): + cpdef truncation(self) noexcept: """ Return a rank-1 truncation of the matroid. @@ -4043,7 +4043,7 @@ cdef class Matroid(SageObject): return self._extension(l, [])._minor(contractions=frozenset([l]), deletions=frozenset([])) - cpdef has_minor(self, N, bint certificate=False): + cpdef has_minor(self, N, bint certificate=False) noexcept: """ Check if ``self`` has a minor isomorphic to ``N``, and optionally return frozensets ``X`` and ``Y`` so that ``N`` is isomorphic to ``self.minor(X, Y)``. @@ -4090,7 +4090,7 @@ cdef class Matroid(SageObject): raise ValueError("N must be a matroid.") return self._has_minor(N, certificate) - cpdef has_line_minor(self, k, hyperlines=None, certificate=False): + cpdef has_line_minor(self, k, hyperlines=None, certificate=False) noexcept: r""" Test if the matroid has a `U_{2, k}`-minor. @@ -4161,7 +4161,7 @@ cdef class Matroid(SageObject): # get simplified away anyway. return self._has_line_minor(k, hyperlines, certificate) - cpdef _has_line_minor(self, k, hyperlines, certificate=False): + cpdef _has_line_minor(self, k, hyperlines, certificate=False) noexcept: r""" Test if the matroid has a `U_{2, k}`-minor. @@ -4208,7 +4208,7 @@ cdef class Matroid(SageObject): # extensions - cpdef extension(self, element=None, subsets=None): + cpdef extension(self, element=None, subsets=None) noexcept: r""" Return an extension of the matroid. @@ -4285,7 +4285,7 @@ cdef class Matroid(SageObject): hyperplanes = [H for H in self.modular_cut(subsets) if self._rank(H) == r] return self._extension(element, hyperplanes) - cpdef coextension(self, element=None, subsets=None): + cpdef coextension(self, element=None, subsets=None) noexcept: r""" Return a coextension of the matroid. @@ -4349,7 +4349,7 @@ cdef class Matroid(SageObject): """ return self.dual().extension(element, subsets).dual() - cpdef modular_cut(self, subsets): + cpdef modular_cut(self, subsets) noexcept: r""" Compute the modular cut generated by ``subsets``. @@ -4439,7 +4439,7 @@ cdef class Matroid(SageObject): final_list.add(F) return final_list - cpdef linear_subclasses(self, line_length=None, subsets=None): + cpdef linear_subclasses(self, line_length=None, subsets=None) noexcept: r""" Return an iterable set of linear subclasses of the matroid. @@ -4508,7 +4508,7 @@ cdef class Matroid(SageObject): from . import extension return extension.LinearSubclasses(self, line_length=line_length, subsets=subsets) - cpdef extensions(self, element=None, line_length=None, subsets=None): + cpdef extensions(self, element=None, line_length=None, subsets=None) noexcept: r""" Return an iterable set of single-element extensions of the matroid. @@ -4639,7 +4639,7 @@ cdef class Matroid(SageObject): # connectivity - cpdef simplify(self): + cpdef simplify(self) noexcept: r""" Return the simplification of the matroid. @@ -4678,7 +4678,7 @@ cdef class Matroid(SageObject): return self._minor(contractions=frozenset([]), deletions=self.groundset().difference(res)) - cpdef cosimplify(self): + cpdef cosimplify(self) noexcept: r""" Return the cosimplification of the matroid. @@ -4717,7 +4717,7 @@ cdef class Matroid(SageObject): return self._minor(contractions=self.groundset().difference(res), deletions=frozenset([])) - cpdef is_simple(self): + cpdef is_simple(self) noexcept: """ Test if the matroid is simple. @@ -4750,7 +4750,7 @@ cdef class Matroid(SageObject): return False return True - cpdef is_cosimple(self): + cpdef is_cosimple(self) noexcept: r""" Test if the matroid is cosimple. @@ -4786,7 +4786,7 @@ cdef class Matroid(SageObject): return False return True - cpdef components(self): + cpdef components(self) noexcept: """ Return a list of the components of the matroid. @@ -4827,7 +4827,7 @@ cdef class Matroid(SageObject): components = components2 return components - cpdef is_connected(self, certificate=False): + cpdef is_connected(self, certificate=False) noexcept: r""" Test if the matroid is connected. @@ -4867,7 +4867,7 @@ cdef class Matroid(SageObject): else: return False - cpdef connectivity(self, S, T=None): + cpdef connectivity(self, S, T=None) noexcept: r""" Evaluate the connectivity function of the matroid. @@ -4908,7 +4908,7 @@ cdef class Matroid(SageObject): raise ValueError("S and T are not disjoint") return len(self._link(S, T)[0]) - self.full_rank() + self._rank(S) + self._rank(T) - cpdef _connectivity(self, S, T): + cpdef _connectivity(self, S, T) noexcept: r""" Return the connectivity of two subsets ``S`` and ``T`` in the matroid. @@ -4947,7 +4947,7 @@ cdef class Matroid(SageObject): """ return len(self._link(S,T)[0]) - self.full_rank() + self.rank(S) + self.rank(T) - cpdef link(self, S, T): + cpdef link(self, S, T) noexcept: r""" Given disjoint subsets `S` and `T`, return a connector `I` and a separation `X`, which are optimal dual solutions in Tutte's Linking Theorem: @@ -4994,7 +4994,7 @@ cdef class Matroid(SageObject): raise ValueError("S and T are not disjoint") return self._link(S, T) - cpdef _link(self, S, T): + cpdef _link(self, S, T) noexcept: r""" Given disjoint subsets `S` and `T`, return a connector `I` and a separation `X`, which are optimal dual solutions in Tutte's Linking Theorem: @@ -5077,7 +5077,7 @@ cdef class Matroid(SageObject): I = I.symmetric_difference(path) return frozenset(I), frozenset(predecessor)|S - cpdef is_kconnected(self, k, certificate=False): + cpdef is_kconnected(self, k, certificate=False) noexcept: r""" Return ``True`` if the matroid is `k`-connected, ``False`` otherwise. It can optionally return a separator as a witness. @@ -5203,7 +5203,7 @@ cdef class Matroid(SageObject): return True, None return True - cpdef is_3connected(self, certificate=False, algorithm=None): + cpdef is_3connected(self, certificate=False, algorithm=None) noexcept: r""" Return ``True`` if the matroid is 3-connected, ``False`` otherwise. It can optionally return a separator as a witness. @@ -5283,7 +5283,7 @@ cdef class Matroid(SageObject): return self._is_3connected_shifting(certificate) raise ValueError("Not a valid algorithm.") - cpdef is_4connected(self, certificate=False, algorithm=None): + cpdef is_4connected(self, certificate=False, algorithm=None) noexcept: r""" Return ``True`` if the matroid is 4-connected, ``False`` otherwise. It can optionally return a separator as a witness. @@ -5335,7 +5335,7 @@ cdef class Matroid(SageObject): return self._is_4connected_shifting(certificate) raise ValueError("Not a valid algorithm.") - cpdef _is_3connected_CE(self, certificate=False): + cpdef _is_3connected_CE(self, certificate=False) noexcept: r""" Return ``True`` if the matroid is 3-connected, ``False`` otherwise. @@ -5463,7 +5463,7 @@ cdef class Matroid(SageObject): else: return True - cpdef _is_3connected_shifting(self, certificate=False): + cpdef _is_3connected_shifting(self, certificate=False) noexcept: r""" Return ``True`` if the matroid is 3-connected, ``False`` otherwise. It can optionally return a separator as a witness. @@ -5541,7 +5541,7 @@ cdef class Matroid(SageObject): return True, None return True - cpdef _is_4connected_shifting(self, certificate=False): + cpdef _is_4connected_shifting(self, certificate=False) noexcept: r""" Return ``True`` if the matroid is 4-connected, ``False`` otherwise. It can optionally return a separator as a witness. @@ -5645,7 +5645,7 @@ cdef class Matroid(SageObject): return True, None return True - cpdef _shifting_all(self, X, P_rows, P_cols, Q_rows, Q_cols, m): + cpdef _shifting_all(self, X, P_rows, P_cols, Q_rows, Q_cols, m) noexcept: r""" Given a basis ``X``. If the submatrix of the partial matrix using rows `P_rows` columns `P_cols` and submatrix using rows `Q_rows` columns @@ -5707,7 +5707,7 @@ cdef class Matroid(SageObject): return True, cert return False, None - cpdef _shifting(self, X, X_1, Y_2, X_2, Y_1, m): + cpdef _shifting(self, X, X_1, Y_2, X_2, Y_1, m) noexcept: r""" Given a basis ``X``. If the submatrix of the partial matrix using rows `X_1` columns `Y_2` and submatrix using rows `X_2` columns @@ -5799,7 +5799,7 @@ cdef class Matroid(SageObject): return False, None return True, S_2 - cpdef _is_3connected_BC(self, certificate=False): + cpdef _is_3connected_BC(self, certificate=False) noexcept: r""" Return ``True`` if the matroid is 3-connected, ``False`` otherwise. @@ -5855,7 +5855,7 @@ cdef class Matroid(SageObject): fund_cocircuits = set([self._fundamental_cocircuit(basis, e) for e in basis]) return self._is_3connected_BC_recursion(self.basis(), fund_cocircuits) - cpdef _is_3connected_BC_recursion(self, basis, fund_cocircuits): + cpdef _is_3connected_BC_recursion(self, basis, fund_cocircuits) noexcept: r""" A helper function for ``_is_3connected_BC``. This method assumes the matroid is both simple and cosimple. Under the assumption, it return @@ -5955,7 +5955,7 @@ cdef class Matroid(SageObject): # representability - cpdef _local_binary_matroid(self, basis=None): + cpdef _local_binary_matroid(self, basis=None) noexcept: r""" Return a binary matroid `M` so that relative to a fixed basis `B`, `X` is a basis of ``self`` if and only if `X` is a basis of `M` @@ -5996,7 +5996,7 @@ cdef class Matroid(SageObject): from sage.matroids.linear_matroid import BinaryMatroid return BinaryMatroid(groundset=E, matrix=A, basis=basis, keep_initial_representation=False) - cpdef binary_matroid(self, randomized_tests=1, verify = True): + cpdef binary_matroid(self, randomized_tests=1, verify = True) noexcept: r""" Return a binary matroid representing ``self``, if such a representation exists. @@ -6054,7 +6054,7 @@ cdef class Matroid(SageObject): else: return None - cpdef is_binary(self, randomized_tests=1): + cpdef is_binary(self, randomized_tests=1) noexcept: r""" Decide if ``self`` is a binary matroid. @@ -6092,7 +6092,7 @@ cdef class Matroid(SageObject): """ return self.binary_matroid(randomized_tests=randomized_tests, verify=True) is not None - cpdef _local_ternary_matroid(self, basis=None): + cpdef _local_ternary_matroid(self, basis=None) noexcept: r""" Return a ternary matroid `M` so that if ``self`` is ternary, then `M` is field isomorphic to ``self``. @@ -6183,7 +6183,7 @@ cdef class Matroid(SageObject): from sage.matroids.linear_matroid import TernaryMatroid return TernaryMatroid(groundset=E, matrix=A, basis=basis, keep_initial_representation=False) - cpdef ternary_matroid(self, randomized_tests=1, verify = True): + cpdef ternary_matroid(self, randomized_tests=1, verify = True) noexcept: r""" Return a ternary matroid representing ``self``, if such a representation exists. @@ -6241,7 +6241,7 @@ cdef class Matroid(SageObject): else: return None - cpdef is_ternary(self, randomized_tests=1): + cpdef is_ternary(self, randomized_tests=1) noexcept: r""" Decide if ``self`` is a ternary matroid. @@ -6281,7 +6281,7 @@ cdef class Matroid(SageObject): # matroid k-closed - cpdef is_k_closed(self, int k): + cpdef is_k_closed(self, int k) noexcept: r""" Return if ``self`` is a ``k``-closed matroid. @@ -6318,7 +6318,7 @@ cdef class Matroid(SageObject): # matroid chordality - cpdef _is_circuit_chordal(self, frozenset C, bint certificate=False): + cpdef _is_circuit_chordal(self, frozenset C, bint certificate=False) noexcept: """ Check if the circuit ``C`` has a chord. @@ -6366,7 +6366,7 @@ cdef class Matroid(SageObject): return False, None return False - cpdef is_circuit_chordal(self, C, bint certificate=False): + cpdef is_circuit_chordal(self, C, bint certificate=False) noexcept: r""" Check if the circuit ``C`` has a chord. @@ -6408,7 +6408,7 @@ cdef class Matroid(SageObject): raise ValueError("input C is not a circuit") return self._is_circuit_chordal(frozenset(C), certificate) - cpdef is_chordal(self, k1=4, k2=None, bint certificate=False): + cpdef is_chordal(self, k1=4, k2=None, bint certificate=False) noexcept: r""" Return if a matroid is ``[k1, k2]``-chordal. @@ -6463,7 +6463,7 @@ cdef class Matroid(SageObject): return False return True - cpdef chordality(self): + cpdef chordality(self) noexcept: r""" Return the minimal `k` such that the matroid ``M`` is `k`-chordal. @@ -6495,7 +6495,7 @@ cdef class Matroid(SageObject): # optimization - cpdef max_weight_independent(self, X=None, weights=None): + cpdef max_weight_independent(self, X=None, weights=None) noexcept: r""" Return a maximum-weight independent set contained in a subset. @@ -6582,7 +6582,7 @@ cdef class Matroid(SageObject): res.discard(e) return frozenset(res) - cpdef max_weight_coindependent(self, X=None, weights=None): + cpdef max_weight_coindependent(self, X=None, weights=None) noexcept: r""" Return a maximum-weight coindependent set contained in ``X``. @@ -6674,7 +6674,7 @@ cdef class Matroid(SageObject): res.discard(e) return frozenset(res) - cpdef is_max_weight_independent_generic(self, X=None, weights=None): + cpdef is_max_weight_independent_generic(self, X=None, weights=None) noexcept: r""" Test if only one basis of the subset ``X`` has maximal weight. @@ -6823,7 +6823,7 @@ cdef class Matroid(SageObject): del res[-1] return True - cpdef is_max_weight_coindependent_generic(self, X=None, weights=None): + cpdef is_max_weight_coindependent_generic(self, X=None, weights=None) noexcept: r""" Test if only one cobasis of the subset ``X`` has maximal weight. @@ -6980,7 +6980,7 @@ cdef class Matroid(SageObject): del res[-1] return True - cpdef intersection(self, other, weights=None): + cpdef intersection(self, other, weights=None) noexcept: r""" Return a maximum-weight common independent set. @@ -7038,7 +7038,7 @@ cdef class Matroid(SageObject): raise TypeError("the weights argument does not seem to be a collection of weights for the groundset.") return self._intersection(other, wt) - cpdef _intersection(self, other, weights): + cpdef _intersection(self, other, weights) noexcept: r""" Return a maximum-weight common independent. @@ -7078,7 +7078,7 @@ cdef class Matroid(SageObject): U = self._intersection_augmentation(other, weights, Y) return Y - cpdef _intersection_augmentation(self, other, weights, Y): + cpdef _intersection_augmentation(self, other, weights, Y) noexcept: r""" Return an augmenting set for the matroid intersection problem. @@ -7169,7 +7169,7 @@ cdef class Matroid(SageObject): path.add(u) return True, frozenset(path) - cpdef intersection_unweighted(self, other): + cpdef intersection_unweighted(self, other) noexcept: r""" Return a maximum-cardinality common independent set. @@ -7205,7 +7205,7 @@ cdef class Matroid(SageObject): raise ValueError("matroid intersection requires equal groundsets.") return self._intersection_unweighted(other) - cpdef _intersection_unweighted(self, other): + cpdef _intersection_unweighted(self, other) noexcept: r""" Return a maximum common independent. @@ -7241,7 +7241,7 @@ cdef class Matroid(SageObject): U = self._intersection_augmentation_unweighted(other, Y) return Y - cpdef _intersection_augmentation_unweighted(self, other, Y): + cpdef _intersection_augmentation_unweighted(self, other, Y) noexcept: r""" Return a common independent set larger than `Y` or report failure. @@ -7377,7 +7377,7 @@ cdef class Matroid(SageObject): predecessor[v] = u return True, Y - cpdef partition(self): + cpdef partition(self) noexcept: r""" Return a minimum number of disjoint independent sets that covers the groundset. @@ -7443,7 +7443,7 @@ cdef class Matroid(SageObject): # invariants - cpdef _internal(self, B): + cpdef _internal(self, B) noexcept: """ Return the set of internally active elements of a basis `B`. @@ -7482,7 +7482,7 @@ cdef class Matroid(SageObject): A.add(e) return A - cpdef _external(self, B): + cpdef _external(self, B) noexcept: """ Return the set of externally active elements of a basis `B`. @@ -7522,7 +7522,7 @@ cdef class Matroid(SageObject): A.add(e) return A - cpdef tutte_polynomial(self, x=None, y=None): + cpdef tutte_polynomial(self, x=None, y=None) noexcept: r""" Return the Tutte polynomial of the matroid. @@ -7583,7 +7583,7 @@ cdef class Matroid(SageObject): T = T(a, b) return T - cpdef flat_cover(self, solver=None, verbose=0, integrality_tolerance=1e-3): + cpdef flat_cover(self, solver=None, verbose=0, integrality_tolerance=1e-3) noexcept: """ Return a minimum-size cover of the nonbases by non-spanning flats. @@ -7738,7 +7738,7 @@ cdef class Matroid(SageObject): ret.rename("Chow ring of {} over {}".format(self, R)) return ret - cpdef plot(self, B=None, lineorders=None, pos_method=None,pos_dict=None,save_pos=False): + cpdef plot(self, B=None, lineorders=None, pos_method=None,pos_dict=None,save_pos=False) noexcept: """ Return geometric representation as a sage graphics object. @@ -7799,7 +7799,7 @@ cdef class Matroid(SageObject): lineorders2=matroids_plot_helpers.lineorders_union(self._cached_info['lineorders'],lineorders) return matroids_plot_helpers.geomrep(self,B,lineorders2,pd=pos_dict, sp=save_pos) - cpdef show(self,B=None,lineorders=None,pos_method=None,pos_dict=None,save_pos=False,lims=None): + cpdef show(self,B=None,lineorders=None,pos_method=None,pos_dict=None,save_pos=False,lims=None) noexcept: """ Show the geometric representation of the matroid. @@ -7848,7 +7848,7 @@ cdef class Matroid(SageObject): G.show(xmin=lims[0], xmax=lims[1], ymin=lims[2], ymax=lims[3]) return - cpdef _fix_positions(self,pos_dict=None,lineorders=None): + cpdef _fix_positions(self,pos_dict=None,lineorders=None) noexcept: """ Cache point positions and line orders without actually plotting @@ -7916,7 +7916,7 @@ cdef class Matroid(SageObject): from sage.topology.simplicial_complex import SimplicialComplex return SimplicialComplex(self.no_broken_circuits_sets(ordering)) - cpdef bergman_complex(self): + cpdef bergman_complex(self) noexcept: r""" Return the Bergman complex of ``self``. @@ -7941,7 +7941,7 @@ cdef class Matroid(SageObject): L = self.lattice_of_flats() return L.subposet(L.list()[1: -1]).order_complex() - cpdef augmented_bergman_complex(self): + cpdef augmented_bergman_complex(self) noexcept: r""" Return the augmented Bergman complex of ``self``. diff --git a/src/sage/matroids/set_system.pxd b/src/sage/matroids/set_system.pxd index c1b0b75f1e5..69a4bc8443c 100644 --- a/src/sage/matroids/set_system.pxd +++ b/src/sage/matroids/set_system.pxd @@ -8,29 +8,29 @@ cdef class SetSystem: cdef long _len, _capacity cdef bitset_t _temp - cdef copy(self) - cdef _relabel(self, l) - cpdef _complements(self) + cdef copy(self) noexcept + cdef _relabel(self, l) noexcept + cpdef _complements(self) noexcept - cdef resize(self, k=*) - cdef _append(self, bitset_t X) - cdef append(self, X) - cdef _subset(self, long k) - cdef subset(self, k) - cpdef _get_groundset(self) + cdef resize(self, k=*) noexcept + cdef _append(self, bitset_t X) noexcept + cdef append(self, X) noexcept + cdef _subset(self, long k) noexcept + cdef subset(self, k) noexcept + cpdef _get_groundset(self) noexcept - cdef list _incidence_count(self, E) - cdef SetSystem _groundset_partition(self, SetSystem P, list cnt) - cdef long subset_characteristic(self, SetSystem P, long e) - cdef subsets_partition(self, SetSystem P=*, E=*) - cdef _distinguish(self, Py_ssize_t v) - cpdef is_connected(self) + cdef list _incidence_count(self, E) noexcept + cdef SetSystem _groundset_partition(self, SetSystem P, list cnt) noexcept + cdef long subset_characteristic(self, SetSystem P, long e) noexcept + cdef subsets_partition(self, SetSystem P=*, E=*) noexcept + cdef _distinguish(self, Py_ssize_t v) noexcept + cpdef is_connected(self) noexcept - cdef initial_partition(self, SetSystem P=*, E=*) - cpdef _equitable_partition(self, SetSystem P=*, EP=*) - cpdef _heuristic_partition(self, SetSystem P=*, EP=*) - cpdef _isomorphism(self, SetSystem other, SetSystem SP=*, SetSystem OP=*) - cpdef _equivalence(self, is_equiv, SetSystem other, SetSystem SP=*, SetSystem OP=*) + cdef initial_partition(self, SetSystem P=*, E=*) noexcept + cpdef _equitable_partition(self, SetSystem P=*, EP=*) noexcept + cpdef _heuristic_partition(self, SetSystem P=*, EP=*) noexcept + cpdef _isomorphism(self, SetSystem other, SetSystem SP=*, SetSystem OP=*) noexcept + cpdef _equivalence(self, is_equiv, SetSystem other, SetSystem SP=*, SetSystem OP=*) noexcept cdef class SetSystemIterator: cdef SetSystem _H diff --git a/src/sage/matroids/set_system.pyx b/src/sage/matroids/set_system.pyx index cb4daf4099a..1c943ed6203 100644 --- a/src/sage/matroids/set_system.pyx +++ b/src/sage/matroids/set_system.pyx @@ -202,14 +202,14 @@ cdef class SetSystem: """ return "Iterator over a system of subsets" - cdef copy(self): + cdef copy(self) noexcept: cdef SetSystem S S = SetSystem(self._groundset, capacity=len(self)) for i in range(len(self)): S._append(self._subsets[i]) return S - cdef _relabel(self, l): + cdef _relabel(self, l) noexcept: """ Relabel each element `e` of the ground set as `l(e)`, where `l` is a given injective map. @@ -235,7 +235,7 @@ cdef class SetSystem: for i in range(self._groundset_size): self._idx[self._groundset[i]] = i - cpdef _complements(self): + cpdef _complements(self) noexcept: """ Return a SetSystem containing the complements of each element in the groundset. @@ -260,7 +260,7 @@ cdef class SetSystem: S._append(self._temp) return S - cdef inline resize(self, k=None): + cdef inline resize(self, k=None) noexcept: """ Change the capacity of the SetSystem. """ @@ -273,7 +273,7 @@ cdef class SetSystem: self._subsets = check_reallocarray(self._subsets, k2, sizeof(bitset_t)) self._capacity = k2 - cdef inline _append(self, bitset_t X): + cdef inline _append(self, bitset_t X) noexcept: """ Append subset in internal, bitset format """ @@ -283,7 +283,7 @@ cdef class SetSystem: bitset_copy(self._subsets[self._len], X) self._len += 1 - cdef inline append(self, X): + cdef inline append(self, X) noexcept: """ Append subset. """ @@ -295,13 +295,13 @@ cdef class SetSystem: bitset_add(self._subsets[self._len], self._idx[x]) self._len += 1 - cdef inline _subset(self, long k): + cdef inline _subset(self, long k) noexcept: """ Return the k-th subset, in index format. """ return bitset_list(self._subsets[k]) - cdef subset(self, k): + cdef subset(self, k) noexcept: """ Return the k-th subset. """ @@ -313,7 +313,7 @@ cdef class SetSystem: i = bitset_next(self._subsets[k], i + 1) return frozenset(F) - cpdef _get_groundset(self): + cpdef _get_groundset(self) noexcept: """ Return the ground set of this SetSystem. @@ -326,7 +326,7 @@ cdef class SetSystem: """ return frozenset(self._groundset) - cpdef is_connected(self): + cpdef is_connected(self) noexcept: """ Test if the :class:`SetSystem` is connected. @@ -381,7 +381,7 @@ cdef class SetSystem: # isomorphism - cdef list _incidence_count(self, E): + cdef list _incidence_count(self, E) noexcept: """ For the sub-collection indexed by ``E``, count how often each element occurs. @@ -396,7 +396,7 @@ cdef class SetSystem: i = bitset_next(self._subsets[e], i + 1) return cnt - cdef SetSystem _groundset_partition(self, SetSystem P, list cnt): + cdef SetSystem _groundset_partition(self, SetSystem P, list cnt) noexcept: """ Helper method for partition methods below. """ @@ -437,7 +437,7 @@ cdef class SetSystem: bitset_discard(P._subsets[i], v) P._append(self._temp) - cdef long subset_characteristic(self, SetSystem P, long e): + cdef long subset_characteristic(self, SetSystem P, long e) noexcept: """ Helper method for partition methods below. """ @@ -449,7 +449,7 @@ cdef class SetSystem: c += bitset_len(self._temp) return c - cdef subsets_partition(self, SetSystem P=None, E=None): + cdef subsets_partition(self, SetSystem P=None, E=None) noexcept: """ Helper method for partition methods below. """ @@ -478,7 +478,7 @@ cdef class SetSystem: EP.append(ep) return EP, hash(tuple(eh)) - cdef _distinguish(self, Py_ssize_t v): + cdef _distinguish(self, Py_ssize_t v) noexcept: """ Helper method for partition methods below. """ @@ -493,7 +493,7 @@ cdef class SetSystem: return S # partition functions - cdef initial_partition(self, SetSystem P=None, E=None): + cdef initial_partition(self, SetSystem P=None, E=None) noexcept: """ Helper method for partition methods below. """ @@ -508,7 +508,7 @@ cdef class SetSystem: self._groundset_partition(P, cnt) return P - cpdef _equitable_partition(self, SetSystem P=None, EP=None): + cpdef _equitable_partition(self, SetSystem P=None, EP=None) noexcept: r""" Return an equitable ordered partition of the ground set of the hypergraph whose edges are the subsets in this SetSystem. @@ -589,7 +589,7 @@ cdef class SetSystem: return P, EP, h - cpdef _heuristic_partition(self, SetSystem P=None, EP=None): + cpdef _heuristic_partition(self, SetSystem P=None, EP=None) noexcept: """ Return an heuristic ordered partition into singletons of the ground set of the hypergraph whose edges are the subsets in this SetSystem. @@ -637,7 +637,7 @@ cdef class SetSystem: return self._heuristic_partition(P._distinguish(bitset_first(P._subsets[i])), EP) return P, EP, h - cpdef _isomorphism(self, SetSystem other, SetSystem SP=None, SetSystem OP=None): + cpdef _isomorphism(self, SetSystem other, SetSystem SP=None, SetSystem OP=None) noexcept: """ Return a groundset isomorphism between this SetSystem and an other. @@ -697,7 +697,7 @@ cdef class SetSystem: return None return dict([(self._groundset[bitset_first(SP._subsets[i])], other._groundset[bitset_first(OP._subsets[i])]) for i in range(len(SP))]) - cpdef _equivalence(self, is_equiv, SetSystem other, SetSystem SP=None, SetSystem OP=None): + cpdef _equivalence(self, is_equiv, SetSystem other, SetSystem SP=None, SetSystem OP=None) noexcept: """ Return a groundset isomorphism that is an equivalence between this SetSystem and an other. diff --git a/src/sage/matroids/union_matroid.pxd b/src/sage/matroids/union_matroid.pxd index 5511a62af3b..6e3a6e8d96e 100644 --- a/src/sage/matroids/union_matroid.pxd +++ b/src/sage/matroids/union_matroid.pxd @@ -3,17 +3,17 @@ from .matroid cimport Matroid cdef class MatroidUnion(Matroid): cdef list matroids cdef frozenset _groundset - cpdef groundset(self) - cpdef _rank(self, X) + cpdef groundset(self) noexcept + cpdef _rank(self, X) noexcept cdef class MatroidSum(Matroid): cdef list summands cdef frozenset _groundset - cpdef groundset(self) - cpdef _rank(self, X) + cpdef groundset(self) noexcept + cpdef _rank(self, X) noexcept cdef class PartitionMatroid(Matroid): cdef dict p cdef frozenset _groundset - cpdef groundset(self) - cpdef _rank(self, X) + cpdef groundset(self) noexcept + cpdef _rank(self, X) noexcept diff --git a/src/sage/matroids/union_matroid.pyx b/src/sage/matroids/union_matroid.pyx index f97de43c766..802b8d609f4 100644 --- a/src/sage/matroids/union_matroid.pyx +++ b/src/sage/matroids/union_matroid.pyx @@ -53,7 +53,7 @@ cdef class MatroidUnion(Matroid): E.update(M.groundset()) self._groundset = frozenset(E) - cpdef groundset(self): + cpdef groundset(self) noexcept: """ Return the groundset of the matroid. @@ -72,7 +72,7 @@ cdef class MatroidUnion(Matroid): """ return self._groundset - cpdef _rank(self, X): + cpdef _rank(self, X) noexcept: r""" Return the rank of a set ``X``. @@ -187,7 +187,7 @@ cdef class MatroidSum(Matroid): S = S + M._repr_() +"\n" return S[:-1] - cpdef groundset(self): + cpdef groundset(self) noexcept: """ Return the groundset of the matroid. @@ -206,7 +206,7 @@ cdef class MatroidSum(Matroid): """ return self._groundset - cpdef _rank(self, X): + cpdef _rank(self, X) noexcept: r""" Return the rank of a set ``X``. @@ -286,7 +286,7 @@ cdef class PartitionMatroid(Matroid): E.update(P) self._groundset = frozenset(E) - cpdef groundset(self): + cpdef groundset(self) noexcept: """ Return the groundset of the matroid. @@ -305,7 +305,7 @@ cdef class PartitionMatroid(Matroid): """ return self._groundset - cpdef _rank(self, X): + cpdef _rank(self, X) noexcept: r""" Return the rank of a set ``X``. diff --git a/src/sage/misc/allocator.pxd b/src/sage/misc/allocator.pxd index 7945a75241f..ba4321cf71c 100644 --- a/src/sage/misc/allocator.pxd +++ b/src/sage/misc/allocator.pxd @@ -1,5 +1,5 @@ from cpython.object cimport * -cdef hook_tp_functions_type(object t, newfunc tp_new, destructor tp_dealloc, bint useGC) +cdef hook_tp_functions_type(object t, newfunc tp_new, destructor tp_dealloc, bint useGC) noexcept -cdef hook_tp_functions(object global_dummy, newfunc tp_new, destructor tp_dealloc, bint useGC) +cdef hook_tp_functions(object global_dummy, newfunc tp_new, destructor tp_dealloc, bint useGC) noexcept diff --git a/src/sage/misc/allocator.pyx b/src/sage/misc/allocator.pyx index b7fafdce286..b6d865b00e6 100644 --- a/src/sage/misc/allocator.pyx +++ b/src/sage/misc/allocator.pyx @@ -1,6 +1,6 @@ from cpython.ref cimport Py_INCREF -cdef _hook_tp_functions_type(PyTypeObject *t, newfunc tp_new, destructor tp_dealloc, bint useGC): +cdef _hook_tp_functions_type(PyTypeObject *t, newfunc tp_new, destructor tp_dealloc, bint useGC) noexcept: """ Initialize the fast integer creation functions. """ @@ -25,12 +25,12 @@ cdef _hook_tp_functions_type(PyTypeObject *t, newfunc tp_new, destructor tp_deal t.tp_dealloc = tp_dealloc -cdef hook_tp_functions_type(object tp, newfunc tp_new, destructor tp_dealloc, bint useGC): +cdef hook_tp_functions_type(object tp, newfunc tp_new, destructor tp_dealloc, bint useGC) noexcept: cdef PyTypeObject *t = tp _hook_tp_functions_type(t, tp_new, tp_dealloc, useGC) -cdef hook_tp_functions(object global_dummy, newfunc tp_new, destructor tp_dealloc, bint useGC): +cdef hook_tp_functions(object global_dummy, newfunc tp_new, destructor tp_dealloc, bint useGC) noexcept: """ Initialize the fast integer creation functions. """ diff --git a/src/sage/misc/binary_tree.pyx b/src/sage/misc/binary_tree.pyx index b23c9ee7266..6287753a335 100644 --- a/src/sage/misc/binary_tree.pyx +++ b/src/sage/misc/binary_tree.pyx @@ -11,7 +11,7 @@ from cysignals.memory cimport sig_malloc, sig_free from cpython.ref cimport PyObject, Py_INCREF, Py_XDECREF -cdef binary_tree_node *BinaryTreeNode(int key, object value): +cdef binary_tree_node *BinaryTreeNode(int key, object value) noexcept: cdef binary_tree_node *t t = sig_malloc(sizeof(binary_tree_node)) t.key = key @@ -21,18 +21,18 @@ cdef binary_tree_node *BinaryTreeNode(int key, object value): t.value = value return t -cdef void free_binary_tree_node(binary_tree_node *self): +cdef void free_binary_tree_node(binary_tree_node *self) noexcept: Py_XDECREF(self.value) sig_free(self) -cdef inline void binary_tree_dealloc(binary_tree_node *self): +cdef inline void binary_tree_dealloc(binary_tree_node *self) noexcept: if self != NULL: binary_tree_dealloc(self.left) binary_tree_dealloc(self.right) free_binary_tree_node(self) -cdef void binary_tree_insert(binary_tree_node *self, int key, object value): +cdef void binary_tree_insert(binary_tree_node *self, int key, object value) noexcept: if self.key == key: return elif self.key > key: @@ -46,7 +46,7 @@ cdef void binary_tree_insert(binary_tree_node *self, int key, object value): else: binary_tree_insert(self.right, key, value) -cdef object binary_tree_get(binary_tree_node *self, int key): +cdef object binary_tree_get(binary_tree_node *self, int key) noexcept: if self.key == key: return self.value elif self.key > key: @@ -60,7 +60,7 @@ cdef object binary_tree_get(binary_tree_node *self, int key): else: return binary_tree_get(self.right, key) -cdef object binary_tree_delete(binary_tree_node *self, int key): +cdef object binary_tree_delete(binary_tree_node *self, int key) noexcept: cdef object t if self.key > key: if self.left == NULL: @@ -81,7 +81,7 @@ cdef object binary_tree_delete(binary_tree_node *self, int key): else: return binary_tree_delete(self.right, key) -cdef binary_tree_node *binary_tree_left_excise(binary_tree_node *self): +cdef binary_tree_node *binary_tree_left_excise(binary_tree_node *self) noexcept: cdef binary_tree_node *left cdef binary_tree_node *cur if self.left == NULL: @@ -99,7 +99,7 @@ cdef binary_tree_node *binary_tree_left_excise(binary_tree_node *self): -cdef binary_tree_node *binary_tree_right_excise(binary_tree_node *self): +cdef binary_tree_node *binary_tree_right_excise(binary_tree_node *self) noexcept: cdef binary_tree_node *right cdef binary_tree_node *cur if self.right == NULL: @@ -116,7 +116,7 @@ cdef binary_tree_node *binary_tree_right_excise(binary_tree_node *self): return right -cdef binary_tree_node *binary_tree_head_excise(binary_tree_node *self): +cdef binary_tree_node *binary_tree_head_excise(binary_tree_node *self) noexcept: cdef binary_tree_node *cur cdef int right # We have a pointer we're about to free. Chances are, we'll never @@ -152,7 +152,7 @@ LIST_POSTORDER = 4 LIST_KEYS = 8 LIST_VALUES = 16 -cdef object binary_tree_list(binary_tree_node *cur, int behavior): +cdef object binary_tree_list(binary_tree_node *cur, int behavior) noexcept: if behavior & LIST_KEYS: item = int(cur.key) else: diff --git a/src/sage/misc/bindable_class.py b/src/sage/misc/bindable_class.py index 86d04bc8770..9213db6008e 100644 --- a/src/sage/misc/bindable_class.py +++ b/src/sage/misc/bindable_class.py @@ -213,7 +213,7 @@ class BoundClass(functools.partial): __doc__ = None # See warning above def __init__(self, *args): - super(BoundClass, self).__init__() + super().__init__() self.__doc__ = self.func.__doc__ def __repr__(self): diff --git a/src/sage/misc/c3.pyx b/src/sage/misc/c3.pyx index d777a0e25ca..47fed790dfe 100644 --- a/src/sage/misc/c3.pyx +++ b/src/sage/misc/c3.pyx @@ -21,7 +21,7 @@ AUTHOR: # **************************************************************************** -cpdef list C3_algorithm(object start, str bases, str attribute, bint proper): +cpdef list C3_algorithm(object start, str bases, str attribute, bint proper) noexcept: """ An implementation of the C3 algorithm. diff --git a/src/sage/misc/c3_controlled.pxd b/src/sage/misc/c3_controlled.pxd index d5dd5c23183..7383b0cf999 100644 --- a/src/sage/misc/c3_controlled.pxd +++ b/src/sage/misc/c3_controlled.pxd @@ -1 +1 @@ -cpdef tuple C3_sorted_merge(list lists, key=?) +cpdef tuple C3_sorted_merge(list lists, key=?) noexcept diff --git a/src/sage/misc/c3_controlled.pyx b/src/sage/misc/c3_controlled.pyx index 442dda7264f..6e34f0a4ba8 100644 --- a/src/sage/misc/c3_controlled.pyx +++ b/src/sage/misc/c3_controlled.pyx @@ -659,7 +659,7 @@ def C3_merge(list lists): raise ValueError("Cannot merge the items %s."%', '.join(repr(head) for head in heads)) return out -cpdef identity(x): +cpdef identity(x) noexcept: r""" EXAMPLES:: @@ -669,7 +669,7 @@ cpdef identity(x): """ return x -cpdef tuple C3_sorted_merge(list lists, key=identity): +cpdef tuple C3_sorted_merge(list lists, key=identity) noexcept: r""" Return the sorted input lists merged using the ``C3`` algorithm, with a twist. diff --git a/src/sage/misc/cachefunc.pxd b/src/sage/misc/cachefunc.pxd index 8e5d9dfa42a..747e9b60df0 100644 --- a/src/sage/misc/cachefunc.pxd +++ b/src/sage/misc/cachefunc.pxd @@ -1,7 +1,7 @@ from .function_mangling cimport ArgumentFixer -cpdef dict_key(o) -cpdef cache_key(o) +cpdef dict_key(o) noexcept +cpdef cache_key(o) noexcept cdef class CachedFunction(): cdef public str __name__ @@ -11,8 +11,8 @@ cdef class CachedFunction(): cdef public cache # not always of type cdef bint is_classmethod cdef int argfix_init(self) except -1 - cdef get_key_args_kwds(self, tuple args, dict kwds) - cdef fix_args_kwds(self, tuple args, dict kwds) + cdef get_key_args_kwds(self, tuple args, dict kwds) noexcept + cdef fix_args_kwds(self, tuple args, dict kwds) noexcept cdef empty_key cdef key cdef bint do_pickle @@ -23,7 +23,7 @@ cdef class CachedMethod(): cdef public str __cached_module__ cdef CachedFunction _cachedfunc cdef Py_ssize_t nargs - cpdef _get_instance_cache(self, inst) + cpdef _get_instance_cache(self, inst) noexcept cdef class CacheDict(dict): pass diff --git a/src/sage/misc/cachefunc.pyx b/src/sage/misc/cachefunc.pyx index 2b1d38c12b9..20b3b5acbe4 100644 --- a/src/sage/misc/cachefunc.pyx +++ b/src/sage/misc/cachefunc.pyx @@ -535,7 +535,7 @@ cdef class NonpicklingDict(dict): cdef unhashable_key = object() -cpdef inline dict_key(o): +cpdef inline dict_key(o) noexcept: """ Return a key to cache object ``o`` in a dict. @@ -560,7 +560,7 @@ cpdef inline dict_key(o): return o -cpdef inline cache_key(o): +cpdef inline cache_key(o) noexcept: r""" Helper function to return a hashable key for ``o`` which can be used for caching. @@ -600,7 +600,7 @@ cpdef inline cache_key(o): return o -cdef cache_key_unhashable(o): +cdef cache_key_unhashable(o) noexcept: """ Return a key for caching an item which is unhashable. """ @@ -786,7 +786,7 @@ cdef class CachedFunction(): def __module__(self): return self.__cached_module__ - cdef get_key_args_kwds(self, tuple args, dict kwds): + cdef get_key_args_kwds(self, tuple args, dict kwds) noexcept: """ Return the key in the cache to be used when ``args`` and ``kwds`` are passed in as parameters. @@ -814,7 +814,7 @@ cdef class CachedFunction(): self._argument_fixer = ArgumentFixer(self.f, classmethod=self.is_classmethod) - cdef fix_args_kwds(self, tuple args, dict kwds): + cdef fix_args_kwds(self, tuple args, dict kwds) noexcept: r""" Normalize parameters to obtain a key for the cache. @@ -1841,7 +1841,7 @@ cdef class CachedMethodCaller(CachedFunction): """ return self.f(self._instance, *args, **kwds) - cdef fix_args_kwds(self, tuple args, dict kwds): + cdef fix_args_kwds(self, tuple args, dict kwds) noexcept: r""" Normalize parameters to obtain a key for the cache. @@ -2505,7 +2505,7 @@ cdef class GloballyCachedMethodCaller(CachedMethodCaller): The only difference is that the instance is used as part of the key. """ - cdef get_key_args_kwds(self, tuple args, dict kwds): + cdef get_key_args_kwds(self, tuple args, dict kwds) noexcept: """ Return the key in the cache to be used when ``args`` and ``kwds`` are passed in as parameters. @@ -2750,7 +2750,7 @@ cdef class CachedMethod(): """ return self.__get__(inst)(*args, **kwds) - cpdef _get_instance_cache(self, inst): + cpdef _get_instance_cache(self, inst) noexcept: """ Return the cache dictionary. @@ -3238,7 +3238,7 @@ cdef class CachedInParentMethod(CachedMethod): self._cache_name = '_cache__' + 'element_' + (name or f.__name__) self._cachedfunc = CachedFunction(f, classmethod=True, name=name, key=key, do_pickle=do_pickle) - cpdef _get_instance_cache(self, inst): + cpdef _get_instance_cache(self, inst) noexcept: """ Return the cache dictionary, which is stored in the parent. diff --git a/src/sage/misc/citation.pyx b/src/sage/misc/citation.pyx index 9377ce73636..aca83edf22c 100644 --- a/src/sage/misc/citation.pyx +++ b/src/sage/misc/citation.pyx @@ -143,7 +143,7 @@ cdef extern from *: """ -cpdef inline bint cython_profile_enabled(): +cpdef inline bint cython_profile_enabled() noexcept: """ Return whether Cython profiling is enabled. diff --git a/src/sage/misc/cython.py b/src/sage/misc/cython.py index 5631cc092e3..c0c803bf943 100644 --- a/src/sage/misc/cython.py +++ b/src/sage/misc/cython.py @@ -421,7 +421,7 @@ def cython(filename, verbose=0, compile_message=False, os.curdir) # This emulates running "setup.py build" with the correct options - dist = Distribution() + # # setuptools plugins considered harmful: # If build isolation is not in use and setuptools_scm is installed, # then its file_finders entry point is invoked, which we don't need. @@ -429,7 +429,12 @@ def cython(filename, verbose=0, compile_message=False, # LookupError: pyproject.toml does not contain a tool.setuptools_scm section # LookupError: setuptools-scm was unable to detect version ... # We just remove all handling of "setuptools.finalize_distribution_options" entry points. - dist._removed = staticmethod(lambda ep: True) + class Distribution_no_finalize_distribution_options(Distribution): + @staticmethod + def _removed(ep): + return True + + dist = Distribution_no_finalize_distribution_options() dist.ext_modules = [ext] dist.include_dirs = includes buildcmd = dist.get_command_obj("build") diff --git a/src/sage/misc/fast_methods.pxd b/src/sage/misc/fast_methods.pxd index de5c496c168..4df34feab62 100644 --- a/src/sage/misc/fast_methods.pxd +++ b/src/sage/misc/fast_methods.pxd @@ -4,7 +4,7 @@ cdef extern from "Python.h": cdef class FastHashable_class: cdef Py_ssize_t _hash -cdef inline long hash_by_id(void * p): +cdef inline long hash_by_id(void * p) noexcept: r""" This function is a copy paste from the default Python hash function. """ diff --git a/src/sage/misc/func_persist.py b/src/sage/misc/func_persist.py index 12dd35d1f88..cf020479440 100644 --- a/src/sage/misc/func_persist.py +++ b/src/sage/misc/func_persist.py @@ -45,7 +45,6 @@ def bern(n): from . import persist - class func_persist: r""" Put ``@func_persist`` right before your function @@ -57,7 +56,7 @@ def __init__(self, f, dir='func_persist'): os.makedirs(dir, exist_ok=True) self.__doc__ = '%s%s%s' % ( f.__name__, - inspect.formatargspec(*inspect.getargs(f.__code__)), + inspect.signature(f), f.__doc__) def __call__(self, *args, **kwds): diff --git a/src/sage/misc/function_mangling.pxd b/src/sage/misc/function_mangling.pxd index 01604088adc..74f1a6e2282 100644 --- a/src/sage/misc/function_mangling.pxd +++ b/src/sage/misc/function_mangling.pxd @@ -7,4 +7,4 @@ cdef class ArgumentFixer: cdef dict _defaults cdef public tuple _default_tuple - cdef fix_to_pos_args_kwds(self, tuple args, dict kwargs) + cdef fix_to_pos_args_kwds(self, tuple args, dict kwargs) noexcept diff --git a/src/sage/misc/function_mangling.pyx b/src/sage/misc/function_mangling.pyx index 1392fc4f2fd..c614f97e9df 100644 --- a/src/sage/misc/function_mangling.pyx +++ b/src/sage/misc/function_mangling.pyx @@ -284,7 +284,7 @@ cdef class ArgumentFixer: """ return self.fix_to_pos_args_kwds(args, kwds) - cdef fix_to_pos_args_kwds(self, tuple args, dict kwds): + cdef fix_to_pos_args_kwds(self, tuple args, dict kwds) noexcept: """ Fast Cython implementation of :meth:`fix_to_pos`. """ diff --git a/src/sage/misc/lazy_import.pyx b/src/sage/misc/lazy_import.pyx index 7fc73407ace..0ac9fb03d95 100644 --- a/src/sage/misc/lazy_import.pyx +++ b/src/sage/misc/lazy_import.pyx @@ -79,7 +79,7 @@ except ImportError: FeatureNotPresentError = () -cdef inline obj(x): +cdef inline obj(x) noexcept: if type(x) is LazyImport: return (x).get_object() else: @@ -92,7 +92,7 @@ cdef bint startup_guard = True cdef bint finish_startup_called = False -cpdef finish_startup(): +cpdef finish_startup() noexcept: """ Finish the startup phase. @@ -113,7 +113,7 @@ cpdef finish_startup(): finish_startup_called = True -cpdef ensure_startup_finished(): +cpdef ensure_startup_finished() noexcept: """ Make sure that the startup phase is finished. @@ -129,7 +129,7 @@ cpdef ensure_startup_finished(): startup_guard = False -cpdef bint is_during_startup(): +cpdef bint is_during_startup() noexcept: """ Return whether Sage is currently starting up. @@ -147,7 +147,7 @@ cpdef bint is_during_startup(): return startup_guard -cpdef test_fake_startup(): +cpdef test_fake_startup() noexcept: """ For testing purposes only. @@ -216,7 +216,7 @@ cdef class LazyImport(): self._deprecation = deprecation self._feature = feature - cdef inline get_object(self): + cdef inline get_object(self) noexcept: """ Faster, Cython-only partially-inlined version of ``_get_object``. """ @@ -224,7 +224,7 @@ cdef class LazyImport(): return self._object return self._get_object() - cpdef _get_object(self): + cpdef _get_object(self) noexcept: """ Return the wrapped object, importing it if necessary. diff --git a/src/sage/misc/lazy_list.pxd b/src/sage/misc/lazy_list.pxd index f8b51b47835..d512cfb69f4 100644 --- a/src/sage/misc/lazy_list.pxd +++ b/src/sage/misc/lazy_list.pxd @@ -3,10 +3,10 @@ cdef class lazy_list_generic(): cdef lazy_list_generic master # a reference if self is a slice cdef Py_ssize_t start, stop, step - cpdef get(self, Py_ssize_t i) + cpdef get(self, Py_ssize_t i) noexcept cpdef int _fit(self, Py_ssize_t n) except -1 cpdef int _update_cache_up_to(self, Py_ssize_t i) except -1 - cpdef list _get_cache_(self) + cpdef list _get_cache_(self) noexcept cdef class lazy_list_from_iterator(lazy_list_generic): cdef object iterator diff --git a/src/sage/misc/lazy_list.pyx b/src/sage/misc/lazy_list.pyx index cd750933860..71847e566ad 100644 --- a/src/sage/misc/lazy_list.pyx +++ b/src/sage/misc/lazy_list.pyx @@ -610,7 +610,7 @@ cdef class lazy_list_generic(): return 1 return 0 - cpdef get(self, Py_ssize_t i): + cpdef get(self, Py_ssize_t i) noexcept: r""" Return the element at position ``i``. @@ -880,7 +880,7 @@ cdef class lazy_list_generic(): self.cache.extend(l) return 0 - cpdef list _get_cache_(self): + cpdef list _get_cache_(self) noexcept: r""" Return the internal cache. diff --git a/src/sage/misc/lazy_string.pxd b/src/sage/misc/lazy_string.pxd index 7f7354e03ca..d74a18763a2 100644 --- a/src/sage/misc/lazy_string.pxd +++ b/src/sage/misc/lazy_string.pxd @@ -2,5 +2,5 @@ cdef class _LazyString(): cdef func cdef args cdef kwargs - cdef val(self) - cpdef update_lazy_string(self, args, kwds) + cdef val(self) noexcept + cpdef update_lazy_string(self, args, kwds) noexcept diff --git a/src/sage/misc/lazy_string.pyx b/src/sage/misc/lazy_string.pyx index dd92fb38142..4777c44a7a2 100644 --- a/src/sage/misc/lazy_string.pyx +++ b/src/sage/misc/lazy_string.pyx @@ -203,7 +203,7 @@ cdef class _LazyString(): self.args = args self.kwargs = kwargs - cdef val(self): + cdef val(self) noexcept: cdef f = self.func if isinstance(f, str): return f % self.args @@ -503,7 +503,7 @@ cdef class _LazyString(): except Exception: return '<%s broken>' % self.__class__.__name__ - cpdef update_lazy_string(self, args, kwds): + cpdef update_lazy_string(self, args, kwds) noexcept: """ Change this lazy string in-place. diff --git a/src/sage/misc/misc_c.pxd b/src/sage/misc/misc_c.pxd index acb36ab6d99..17ef467911a 100644 --- a/src/sage/misc/misc_c.pxd +++ b/src/sage/misc/misc_c.pxd @@ -1,2 +1,2 @@ -cpdef list normalize_index(object key, int size) +cpdef list normalize_index(object key, int size) noexcept diff --git a/src/sage/misc/misc_c.pyx b/src/sage/misc/misc_c.pyx index 1a856b4ea36..b60794c32d0 100644 --- a/src/sage/misc/misc_c.pyx +++ b/src/sage/misc/misc_c.pyx @@ -147,7 +147,7 @@ def prod(x, z=None, Py_ssize_t recursion_cutoff=5): return prod -cdef balanced_list_prod(L, Py_ssize_t offset, Py_ssize_t count, Py_ssize_t cutoff): +cdef balanced_list_prod(L, Py_ssize_t offset, Py_ssize_t count, Py_ssize_t cutoff) noexcept: """ INPUT: @@ -182,7 +182,7 @@ cdef balanced_list_prod(L, Py_ssize_t offset, Py_ssize_t count, Py_ssize_t cutof return balanced_list_prod(L, offset, k, cutoff) * balanced_list_prod(L, offset + k, count - k, cutoff) -cpdef iterator_prod(L, z=None): +cpdef iterator_prod(L, z=None) noexcept: """ Attempt to do a balanced product of an arbitrary and unknown length sequence (such as a generator). Intermediate multiplications are always @@ -397,7 +397,7 @@ def balanced_sum(x, z=None, Py_ssize_t recursion_cutoff=5): return sum -cdef balanced_list_sum(L, Py_ssize_t offset, Py_ssize_t count, Py_ssize_t cutoff): +cdef balanced_list_sum(L, Py_ssize_t offset, Py_ssize_t count, Py_ssize_t cutoff) noexcept: """ INPUT: @@ -432,7 +432,7 @@ cdef balanced_list_sum(L, Py_ssize_t offset, Py_ssize_t count, Py_ssize_t cutoff return balanced_list_sum(L, offset, k, cutoff) + balanced_list_sum(L, offset + k, count - k, cutoff) -cpdef list normalize_index(object key, int size): +cpdef list normalize_index(object key, int size) noexcept: """ Normalize an index key and return a valid index or list of indices within the range(0, size). diff --git a/src/sage/misc/nested_class.pyx b/src/sage/misc/nested_class.pyx index 4863fe45554..e397b356c22 100644 --- a/src/sage/misc/nested_class.pyx +++ b/src/sage/misc/nested_class.pyx @@ -93,7 +93,7 @@ __all__ = ['modify_for_nested_pickle', 'nested_pickle', #, 'SubClass', 'CopiedClass', 'A1' ] -cpdef modify_for_nested_pickle(cls, str name_prefix, module, first_run=True): +cpdef modify_for_nested_pickle(cls, str name_prefix, module, first_run=True) noexcept: r""" Modify the subclasses of the given class to be picklable, by giving them a mangled name and putting the mangled name in the diff --git a/src/sage/misc/parser.pyx b/src/sage/misc/parser.pyx index ee5b041383c..ef0219d5a80 100644 --- a/src/sage/misc/parser.pyx +++ b/src/sage/misc/parser.pyx @@ -92,10 +92,10 @@ def token_to_str(int token): return chr(token) -cdef inline bint is_alphanumeric(c): +cdef inline bint is_alphanumeric(c) noexcept: return c.isalnum() or c == '_' -cdef inline bint is_whitespace(c): +cdef inline bint is_whitespace(c) noexcept: return c.isspace() @@ -203,7 +203,7 @@ cdef class Tokenizer: token = self.next() return all - cpdef reset(self, int pos = 0): + cpdef reset(self, int pos = 0) noexcept: """ Reset the tokenizer to a given position. @@ -327,7 +327,7 @@ cdef class Tokenizer: self.pos = pos return ERROR - cpdef int next(self): + cpdef int next(self) noexcept: """ Returns the next token in the string. @@ -350,7 +350,7 @@ cdef class Tokenizer: self.token = self.find() return self.token - cpdef int last(self): + cpdef int last(self) noexcept: """ Returns the last token seen. @@ -369,7 +369,7 @@ cdef class Tokenizer: """ return self.token - cpdef int peek(self): + cpdef int peek(self) noexcept: """ Returns the next token that will be encountered, without changing the state of self. @@ -420,7 +420,7 @@ cdef class Tokenizer: self.pos = self.last_pos self.token = 0 - cpdef last_token_string(self): + cpdef last_token_string(self) noexcept: """ Return the actual contents of the last token. @@ -530,7 +530,7 @@ cdef class Parser: """ return self.callable_constructor - cpdef parse(self, s, bint accept_eqn=True): + cpdef parse(self, s, bint accept_eqn=True) noexcept: """ Parse the given string. @@ -552,7 +552,7 @@ cdef class Parser: self.parse_error(tokens) return expr - cpdef parse_expression(self, s): + cpdef parse_expression(self, s) noexcept: """ Parse an expression. @@ -569,7 +569,7 @@ cdef class Parser: self.parse_error(tokens) return expr - cpdef parse_sequence(self, s): + cpdef parse_sequence(self, s) noexcept: """ Parse a (possibly nested) set of lists and tuples. @@ -593,7 +593,7 @@ cdef class Parser: all = all[0] return all - cpdef p_matrix(self, Tokenizer tokens): + cpdef p_matrix(self, Tokenizer tokens) noexcept: """ Parse a matrix @@ -621,7 +621,7 @@ cdef class Parser: else: self.parse_error(tokens, "Malformed matrix") - cpdef p_sequence(self, Tokenizer tokens): + cpdef p_sequence(self, Tokenizer tokens) noexcept: """ Parse a (possibly nested) set of lists and tuples. @@ -666,7 +666,7 @@ cdef class Parser: tokens.backtrack() return all - cpdef p_list(self, Tokenizer tokens): + cpdef p_list(self, Tokenizer tokens) noexcept: """ Parse a list of items. @@ -688,7 +688,7 @@ cdef class Parser: self.parse_error(tokens, "Malformed list") return all - cpdef p_tuple(self, Tokenizer tokens): + cpdef p_tuple(self, Tokenizer tokens) noexcept: """ Parse a tuple of items. @@ -723,7 +723,7 @@ cdef class Parser: return self.p_eqn(tokens) # eqn ::= expr op expr | expr - cpdef p_eqn(self, Tokenizer tokens): + cpdef p_eqn(self, Tokenizer tokens) noexcept: r""" Parse an equation or expression. @@ -769,7 +769,7 @@ cdef class Parser: return lhs # expr ::= term | expr '+' term | expr '-' term - cpdef p_expr(self, Tokenizer tokens): + cpdef p_expr(self, Tokenizer tokens) noexcept: """ Parse a list of one or more terms. @@ -804,7 +804,7 @@ cdef class Parser: return operand1 # term ::= factor | term '*' factor | term '/' factor - cpdef p_term(self, Tokenizer tokens): + cpdef p_term(self, Tokenizer tokens) noexcept: """ Parse a single term (consisting of one or more factors). @@ -845,7 +845,7 @@ cdef class Parser: return operand1 # factor ::= '+' factor | '-' factor | power - cpdef p_factor(self, Tokenizer tokens): + cpdef p_factor(self, Tokenizer tokens) noexcept: """ Parse a single factor, which consists of any number of unary +/- and a power. @@ -872,7 +872,7 @@ cdef class Parser: return self.p_power(tokens) # power ::= (atom | atom!) ^ factor | atom | atom! - cpdef p_power(self, Tokenizer tokens): + cpdef p_power(self, Tokenizer tokens) noexcept: """ Parses a power. Note that exponentiation groups right to left. @@ -917,7 +917,7 @@ cdef class Parser: return operand1 # atom ::= int | float | name | '(' expr ')' | name '(' args ')' - cpdef p_atom(self, Tokenizer tokens): + cpdef p_atom(self, Tokenizer tokens) noexcept: """ Parse an atom. This is either a parenthesized expression, a function call, or a literal name/int/float. @@ -973,7 +973,7 @@ cdef class Parser: self.parse_error(tokens) # args = arg (',' arg)* | EMPTY - cpdef p_args(self, Tokenizer tokens): + cpdef p_args(self, Tokenizer tokens) noexcept: """ Returns a list, dict pair. @@ -1003,7 +1003,7 @@ cdef class Parser: return args, kwds # arg = expr | name '=' expr - cpdef p_arg(self, Tokenizer tokens): + cpdef p_arg(self, Tokenizer tokens) noexcept: """ Returns an expr, or a (name, expr) tuple corresponding to a single function call argument. @@ -1044,7 +1044,7 @@ cdef class Parser: tokens.backtrack() return self.p_expr(tokens) - cdef parse_error(self, Tokenizer tokens, msg="Malformed expression"): + cdef parse_error(self, Tokenizer tokens, msg="Malformed expression") noexcept: raise SyntaxError(msg, tokens.s, tokens.pos) diff --git a/src/sage/misc/persist.pyx b/src/sage/misc/persist.pyx index 80d4f9b23d5..670a9a6ac17 100644 --- a/src/sage/misc/persist.pyx +++ b/src/sage/misc/persist.pyx @@ -75,7 +75,7 @@ already_pickled = { } already_unpickled = { } -cdef _normalize_filename(s): +cdef _normalize_filename(s) noexcept: """ Append the .sobj extension to a filename if it doesn't already have it. """ @@ -1130,7 +1130,8 @@ def unpickle_all(target, debug=False, run_test_suite=False): Successfully unpickled 1 objects. Failed to unpickle 0 objects. """ - import os.path, tarfile + import os.path + import tarfile ok_count = 0 fail_count = 0 diff --git a/src/sage/misc/randstate.pxd b/src/sage/misc/randstate.pxd index 434dad3a5f2..c83873a7c99 100644 --- a/src/sage/misc/randstate.pxd +++ b/src/sage/misc/randstate.pxd @@ -16,14 +16,14 @@ cdef class randstate: cdef object _gp_saved_seeds - cpdef set_seed_libc(self, bint force) - cpdef set_seed_ntl(self, bint force) + cpdef set_seed_libc(self, bint force) noexcept + cpdef set_seed_ntl(self, bint force) noexcept - cpdef int c_random(self) - cpdef double c_rand_double(self) + cpdef int c_random(self) noexcept + cpdef double c_rand_double(self) noexcept - cpdef ZZ_seed(self) - cpdef long_seed(self) + cpdef ZZ_seed(self) noexcept + cpdef long_seed(self) noexcept -cpdef randstate current_randstate() -cpdef int random() +cpdef randstate current_randstate() noexcept +cpdef int random() noexcept diff --git a/src/sage/misc/randstate.pyx b/src/sage/misc/randstate.pyx index 06d6f8ce894..5c883c928b4 100644 --- a/src/sage/misc/randstate.pyx +++ b/src/sage/misc/randstate.pyx @@ -443,7 +443,7 @@ cdef randstate _pari_seed_randstate # randstate object was the most recent one to seed it. _gp_seed_randstates = weakref.WeakKeyDictionary() -cpdef randstate current_randstate(): +cpdef randstate current_randstate() noexcept: r""" Return the current random number state. @@ -610,7 +610,7 @@ cdef class randstate: self._python_random = rand return rand - cpdef ZZ_seed(self): + cpdef ZZ_seed(self) noexcept: r""" When called on the current :class:`randstate`, returns a 128-bit :mod:`Integer ` suitable for seeding another @@ -625,7 +625,7 @@ cdef class randstate: from sage.rings.integer_ring import ZZ return ZZ.random_element(long(1)<<128) - cpdef long_seed(self): + cpdef long_seed(self) noexcept: r""" When called on the current :class:`randstate`, returns a 128-bit Python long suitable for seeding another random number generator. @@ -639,7 +639,7 @@ cdef class randstate: from sage.rings.integer_ring import ZZ return long(ZZ.random_element(long(1)<<128)) - cpdef set_seed_libc(self, bint force): + cpdef set_seed_libc(self, bint force) noexcept: r""" Checks to see if ``self`` was the most recent :class:`randstate` to seed the libc random number generator. If not, seeds the @@ -664,7 +664,7 @@ cdef class randstate: c_libc_srandom(gmp_urandomb_ui(self.gmp_state, sizeof(int)*8)) _libc_seed_randstate = self - cpdef set_seed_ntl(self, bint force): + cpdef set_seed_ntl(self, bint force) noexcept: r""" Checks to see if ``self`` was the most recent :class:`randstate` to seed the NTL random number generator. If not, seeds @@ -805,7 +805,7 @@ cdef class randstate: _pari_seed_randstate = self - cpdef int c_random(self): + cpdef int c_random(self) noexcept: r""" Returns a 31-bit random number. Intended for internal use only; instead of calling ``current_randstate().c_random()``, @@ -828,7 +828,7 @@ cdef class randstate: """ return gmp_urandomb_ui(self.gmp_state, 31) - cpdef double c_rand_double(self): + cpdef double c_rand_double(self) noexcept: r""" Returns a random floating-point number between 0 and 1. @@ -922,7 +922,7 @@ cdef class randstate: return False -cpdef set_random_seed(seed=None): +cpdef set_random_seed(seed=None) noexcept: r""" Set the current random number seed from the given ``seed`` (which must be coercible to a Python long). @@ -954,7 +954,7 @@ set_random_seed() # Create an alias for randstate to be used in context managers seed = randstate -cpdef int random(): +cpdef int random() noexcept: r""" Returns a 31-bit random number. Intended as a drop-in replacement for the libc :func:`random()` function. @@ -1025,7 +1025,7 @@ def benchmark_mt(): for i from 0 <= i < 100000: gmp_urandomb_ui(rstate.gmp_state, 32) -cpdef int _doctest_libc_random(): +cpdef int _doctest_libc_random() noexcept: r""" Returns the result of :func:`random()` from libc. diff --git a/src/sage/misc/sage_ostools.pyx b/src/sage/misc/sage_ostools.pyx index 678b6731b82..0034f7a5d89 100644 --- a/src/sage/misc/sage_ostools.pyx +++ b/src/sage/misc/sage_ostools.pyx @@ -81,7 +81,7 @@ def restore_cwd(chdir=None): os.chdir(orig_cwd) -cdef file_and_fd(x, int* fd): +cdef file_and_fd(x, int* fd) noexcept: """ If ``x`` is a file, return ``x`` and set ``*fd`` to its file descriptor. If ``x`` is an integer, return ``None`` and set diff --git a/src/sage/misc/sageinspect.py b/src/sage/misc/sageinspect.py index 811afc48755..bbd03bcb24c 100644 --- a/src/sage/misc/sageinspect.py +++ b/src/sage/misc/sageinspect.py @@ -1810,10 +1810,10 @@ def formatannotation(annotation, base_module=None): def sage_formatargspec(args, varargs=None, varkw=None, defaults=None, kwonlyargs=(), kwonlydefaults=None, annotations={}, formatarg=str, - formatvarargs=lambda name: '*' + name, - formatvarkw=lambda name: '**' + name, - formatvalue=lambda value: '=' + repr(value), - formatreturns=lambda text: ' -> ' + text, + formatvarargs=None, + formatvarkw=None, + formatvalue=None, + formatreturns=None, formatannotation=formatannotation): """ Format an argument spec from the values returned by getfullargspec. @@ -1843,6 +1843,15 @@ def sage_formatargspec(args, varargs=None, varkw=None, defaults=None, sage: sage_formatargspec(args, defaults=defaults) '(a, b, c=3)' """ + if formatvarargs is None: + formatvarargs = lambda name: '*' + name + if formatvarkw is None: + formatvarkw = lambda name: '**' + name + if formatvalue is None: + formatvalue = lambda value: '=' + repr(value) + if formatreturns is None: + formatreturns = lambda text: ' -> ' + text + def formatargandannotation(arg): result = formatarg(arg) if arg in annotations: @@ -2383,7 +2392,7 @@ def sage_getsourcelines(obj): '\n', ' cdef GEx _gobj\n', '\n', - ' cpdef object pyobject(self):\n'] + ' cpdef object pyobject(self) noexcept:\n'] sage: lines[-1] # last line # needs sage.symbolic ' return S\n' diff --git a/src/sage/misc/search.pxd b/src/sage/misc/search.pxd index 8cc43ba1b0f..0986f27c51d 100644 --- a/src/sage/misc/search.pxd +++ b/src/sage/misc/search.pxd @@ -1 +1 @@ -cpdef search(object v, object x) \ No newline at end of file +cpdef search(object v, object x) noexcept \ No newline at end of file diff --git a/src/sage/misc/search.pyx b/src/sage/misc/search.pyx index a9e7149113e..3991bbc8f3e 100644 --- a/src/sage/misc/search.pyx +++ b/src/sage/misc/search.pyx @@ -25,7 +25,7 @@ extra comparison. Also, the function names make more sense. import bisect -cpdef search(object v, object x): +cpdef search(object v, object x) noexcept: """ Return (True,i) where i is such that v[i] == x if there is such an i, or (False,j) otherwise, where j is the position where x should be inserted diff --git a/src/sage/modular/arithgroup/arithgroup_element.pyx b/src/sage/modular/arithgroup/arithgroup_element.pyx index dee0b479c74..41b268ea4ef 100644 --- a/src/sage/modular/arithgroup/arithgroup_element.pyx +++ b/src/sage/modular/arithgroup/arithgroup_element.pyx @@ -158,7 +158,7 @@ cdef class ArithmeticSubgroupElement(MultiplicativeGroupElement): """ return '%s' % self.__x._latex_() - cpdef _richcmp_(self, right_r, int op): + cpdef _richcmp_(self, right_r, int op) noexcept: """ Compare self to right, where right is guaranteed to have the same parent as self. @@ -204,7 +204,7 @@ cdef class ArithmeticSubgroupElement(MultiplicativeGroupElement): """ return True - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Return self * right. diff --git a/src/sage/modular/arithgroup/farey_symbol.pyx b/src/sage/modular/arithgroup/farey_symbol.pyx index 863c1d6b654..cd80cb32f3e 100644 --- a/src/sage/modular/arithgroup/farey_symbol.pyx +++ b/src/sage/modular/arithgroup/farey_symbol.pyx @@ -1030,30 +1030,30 @@ cdef class Farey: #--- conversions ------------------------------------------------------------ -cdef public long convert_to_long(n): +cdef public long convert_to_long(n) noexcept: cdef long m = n return m -cdef public object convert_to_Integer(mpz_class a): +cdef public object convert_to_Integer(mpz_class a) noexcept: A = Integer() A.set_from_mpz(a.get_mpz_t()) return A -cdef public object convert_to_rational(mpq_class r): +cdef public object convert_to_rational(mpq_class r) noexcept: a = Integer() a.set_from_mpz(r.get_num_mpz_t()) b = Integer() b.set_from_mpz(r.get_den_mpz_t()) return a/b -cdef public object convert_to_cusp(mpq_class r): +cdef public object convert_to_cusp(mpq_class r) noexcept: a = Integer() a.set_from_mpz(r.get_num_mpz_t()) b = Integer() b.set_from_mpz(r.get_den_mpz_t()) return Cusp(a/b) -cdef public object convert_to_SL2Z(cpp_SL2Z M): +cdef public object convert_to_SL2Z(cpp_SL2Z M) noexcept: a = convert_to_Integer(M.a()) b = convert_to_Integer(M.b()) c = convert_to_Integer(M.c()) diff --git a/src/sage/modular/hypergeometric_misc.pxd b/src/sage/modular/hypergeometric_misc.pxd index 00bf9a97e9a..4198ca8848b 100644 --- a/src/sage/modular/hypergeometric_misc.pxd +++ b/src/sage/modular/hypergeometric_misc.pxd @@ -1,2 +1,2 @@ cpdef hgm_coeffs(long long p, int f, int prec, gamma, m, int D, - gtable, int gtable_prec, bint use_longs) + gtable, int gtable_prec, bint use_longs) noexcept diff --git a/src/sage/modular/hypergeometric_misc.pyx b/src/sage/modular/hypergeometric_misc.pyx index af2c4f74e15..a930d2414bf 100644 --- a/src/sage/modular/hypergeometric_misc.pyx +++ b/src/sage/modular/hypergeometric_misc.pyx @@ -7,7 +7,7 @@ from cysignals.signals cimport sig_check cpdef hgm_coeffs(long long p, int f, int prec, gamma, m, int D, - gtable, int gtable_prec, bint use_longs): + gtable, int gtable_prec, bint use_longs) noexcept: r""" Compute coefficients for the hypergeometric trace formula. diff --git a/src/sage/modular/modform/eis_series_cython.pyx b/src/sage/modular/modform/eis_series_cython.pyx index c29fef9cef7..29ba08039d7 100644 --- a/src/sage/modular/modform/eis_series_cython.pyx +++ b/src/sage/modular/modform/eis_series_cython.pyx @@ -14,7 +14,7 @@ from sage.libs.flint.fmpz_poly cimport * from sage.libs.gmp.mpz cimport * from sage.libs.flint.fmpz_poly cimport Fmpz_poly -cpdef Ek_ZZ(int k, int prec=10): +cpdef Ek_ZZ(int k, int prec=10) noexcept: """ Return list of prec integer coefficients of the weight k Eisenstein series of level 1, normalized so the coefficient of q @@ -140,7 +140,7 @@ cpdef Ek_ZZ(int k, int prec=10): return val -cpdef eisenstein_series_poly(int k, int prec = 10) : +cpdef eisenstein_series_poly(int k, int prec = 10) noexcept: r""" Return the q-expansion up to precision ``prec`` of the weight `k` Eisenstein series, as a FLINT :class:`~sage.libs.flint.fmpz_poly.Fmpz_poly` diff --git a/src/sage/modular/modform/l_series_gross_zagier_coeffs.pyx b/src/sage/modular/modform/l_series_gross_zagier_coeffs.pyx index f91a3e256f0..ffebe813c92 100644 --- a/src/sage/modular/modform/l_series_gross_zagier_coeffs.pyx +++ b/src/sage/modular/modform/l_series_gross_zagier_coeffs.pyx @@ -12,7 +12,7 @@ from libc.math cimport ceil, floor, sqrt from libc.string cimport memcpy -cpdef to_series(L, var): +cpdef to_series(L, var) noexcept: """ Create a power series element out of a list ``L`` in the variable`` var``. diff --git a/src/sage/modular/modsym/heilbronn.pyx b/src/sage/modular/modsym/heilbronn.pyx index 45f0921034d..ba42d70aa9e 100644 --- a/src/sage/modular/modsym/heilbronn.pyx +++ b/src/sage/modular/modsym/heilbronn.pyx @@ -46,7 +46,7 @@ from sage.matrix.matrix_cyclo_dense cimport Matrix_cyclo_dense ctypedef long long llong -cdef int llong_prod_mod(int a, int b, int N): +cdef int llong_prod_mod(int a, int b, int N) noexcept: cdef int c c = ((( a) * ( b)) % ( N)) if c < 0: @@ -83,10 +83,10 @@ cdef int list_append4(list* L, int a, int b, int c, int d) except -1: list_append(L, c) list_append(L, d) -cdef void list_clear(list L): +cdef void list_clear(list L) noexcept: sig_free(L.v) -cdef void list_init(list* L): +cdef void list_init(list* L) noexcept: L.n = 16 L.i = 0 L.v = expand(0, 0, L.n) @@ -170,7 +170,7 @@ cdef class Heilbronn: self.list.v[4*i+2], self.list.v[4*i+3]]) return L - cdef apply_only(self, int u, int v, int N, int* a, int* b): + cdef apply_only(self, int u, int v, int N, int* a, int* b) noexcept: """ INPUT: @@ -210,7 +210,7 @@ cdef class Heilbronn: b[i] = llong_prod_mod(u,self.list.v[4*i+1],N) + llong_prod_mod(v,self.list.v[4*i+3], N) sig_off() - cdef apply_to_polypart(self, fmpz_poly_t* ans, int i, int k): + cdef apply_to_polypart(self, fmpz_poly_t* ans, int i, int k) noexcept: r""" INPUT: diff --git a/src/sage/modular/modsym/manin_symbol.pyx b/src/sage/modular/modsym/manin_symbol.pyx index c02c1f26dbf..52026160b38 100644 --- a/src/sage/modular/modsym/manin_symbol.pyx +++ b/src/sage/modular/modsym/manin_symbol.pyx @@ -199,7 +199,7 @@ cdef class ManinSymbol(Element): """ return self._repr_() - cpdef _richcmp_(self, right, int op): + cpdef _richcmp_(self, right, int op) noexcept: """ Comparison function for ManinSymbols. diff --git a/src/sage/modular/modsym/p1list.pxd b/src/sage/modular/modsym/p1list.pxd index b66f28b8ad6..17254d4a8fb 100644 --- a/src/sage/modular/modsym/p1list.pxd +++ b/src/sage/modular/modsym/p1list.pxd @@ -24,5 +24,5 @@ cdef class P1List: cdef int (*_normalize)(int N, int u, int v, int* uu, int* vv, int* ss, int compute_s) except -1 - cpdef index(self, int u, int v) - cdef index_and_scalar(self, int u, int v, int* i, int* s) + cpdef index(self, int u, int v) noexcept + cdef index_and_scalar(self, int u, int v, int* i, int* s) noexcept diff --git a/src/sage/modular/modsym/p1list.pyx b/src/sage/modular/modsym/p1list.pyx index 1fc3e2de952..0427ae068a3 100644 --- a/src/sage/modular/modsym/p1list.pyx +++ b/src/sage/modular/modsym/p1list.pyx @@ -991,7 +991,7 @@ cdef class P1List(): _, j = search(self.__list, (uu,vv)) return j - cpdef index(self, int u, int v): + cpdef index(self, int u, int v) noexcept: r""" Return the index of the class of `(u,v)` in the fixed list of representatives of @@ -1034,7 +1034,7 @@ cdef class P1List(): except KeyError: return -1 - cdef index_and_scalar(self, int u, int v, int* i, int* s): + cdef index_and_scalar(self, int u, int v, int* i, int* s) noexcept: r""" Compute the index of the class of `(u,v)` in the fixed list of representatives of `\mathbb{P}^1(\ZZ/N\ZZ)` and scalar s diff --git a/src/sage/modular/pollack_stevens/dist.pxd b/src/sage/modular/pollack_stevens/dist.pxd index 95689892050..0a38551d8a6 100644 --- a/src/sage/modular/pollack_stevens/dist.pxd +++ b/src/sage/modular/pollack_stevens/dist.pxd @@ -5,17 +5,17 @@ from sage.rings.padics.pow_computer cimport PowComputer_class cdef class Dist(ModuleElement): - cpdef normalize(self, include_zeroth_moment=*) + cpdef normalize(self, include_zeroth_moment=*) noexcept cdef long ordp - cpdef long _ord_p(self) - cdef long _relprec(self) - cdef _unscaled_moment(self, long i) + cpdef long _ord_p(self) noexcept + cdef long _relprec(self) noexcept + cdef _unscaled_moment(self, long i) noexcept cdef class Dist_vector(Dist): cdef public _moments - cdef Dist_vector _new_c(self) - cdef Dist_vector _addsub(self, Dist_vector right, bint negate) - cpdef _add_(self, other) + cdef Dist_vector _new_c(self) noexcept + cdef Dist_vector _addsub(self, Dist_vector right, bint negate) noexcept + cpdef _add_(self, other) noexcept cdef class WeightKAction(Action): @@ -30,8 +30,8 @@ cdef class WeightKAction(Action): cdef public _dettwist cdef public _Sigma0 - cpdef acting_matrix(self, g, M) - cpdef _compute_acting_matrix(self, g, M) + cpdef acting_matrix(self, g, M) noexcept + cpdef _compute_acting_matrix(self, g, M) noexcept cdef class WeightKAction_vector(WeightKAction): pass diff --git a/src/sage/modular/pollack_stevens/dist.pyx b/src/sage/modular/pollack_stevens/dist.pyx index 7a869a1c05a..fe1f5583cd5 100644 --- a/src/sage/modular/pollack_stevens/dist.pyx +++ b/src/sage/modular/pollack_stevens/dist.pyx @@ -138,7 +138,7 @@ cdef class Dist(ModuleElement): """ return self.parent().prime() ** (self.ordp) * self._moments - cpdef normalize(self, include_zeroth_moment=True): + cpdef normalize(self, include_zeroth_moment=True) noexcept: r""" Normalize so that the precision of the `i`-th moment is `n-i`, where `n` is the number of moments. @@ -158,13 +158,13 @@ cdef class Dist(ModuleElement): """ raise NotImplementedError - cdef long _relprec(self): + cdef long _relprec(self) noexcept: raise NotImplementedError - cdef _unscaled_moment(self, long i): + cdef _unscaled_moment(self, long i) noexcept: raise NotImplementedError - cpdef long _ord_p(self): + cpdef long _ord_p(self) noexcept: r""" Return power of `p` by which the moments are shifted. @@ -481,7 +481,7 @@ cdef class Dist(ModuleElement): pass return alpha - cpdef _richcmp_(_left, _right, int op): + cpdef _richcmp_(_left, _right, int op) noexcept: r""" Comparison. @@ -800,7 +800,7 @@ cdef class Dist_vector(Dist): """ return (self.__class__, (self._moments, self.parent(), self.ordp, False)) - cdef Dist_vector _new_c(self): + cdef Dist_vector _new_c(self) noexcept: r""" Creates an empty distribution. @@ -866,7 +866,7 @@ cdef class Dist_vector(Dist): return QQ(self.moment(0)) raise TypeError("k must be 0") - cdef long _relprec(self): + cdef long _relprec(self) noexcept: """ Return the number of moments. @@ -880,7 +880,7 @@ cdef class Dist_vector(Dist): """ return len(self._moments) - cdef _unscaled_moment(self, long n): + cdef _unscaled_moment(self, long n) noexcept: r""" Return the `n`-th moment, unscaled by the overall power of `p` stored in ``self.ordp``. @@ -894,7 +894,7 @@ cdef class Dist_vector(Dist): """ return self._moments[n] - cdef Dist_vector _addsub(self, Dist_vector right, bint negate): + cdef Dist_vector _addsub(self, Dist_vector right, bint negate) noexcept: r""" Common code for the sum and the difference of two distributions @@ -934,7 +934,7 @@ cdef class Dist_vector(Dist): ans._moments = smoments + rmoments return ans - cpdef _add_(self, _right): + cpdef _add_(self, _right) noexcept: r""" Sum of two distributions. @@ -947,7 +947,7 @@ cdef class Dist_vector(Dist): """ return self._addsub(_right, False) - cpdef _sub_(self, _right): + cpdef _sub_(self, _right) noexcept: r""" Difference of two distributions. @@ -960,7 +960,7 @@ cdef class Dist_vector(Dist): """ return self._addsub(_right, True) - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: r""" Scalar product of a distribution with a ring element that coerces into the base ring. @@ -1044,7 +1044,7 @@ cdef class Dist_vector(Dist): """ return Integer(len(self._moments) + self.ordp) - cpdef normalize(self, include_zeroth_moment=True): + cpdef normalize(self, include_zeroth_moment=True) noexcept: r""" Normalize by reducing modulo `Fil^N`, where `N` is the number of moments. @@ -1270,7 +1270,7 @@ cdef class WeightKAction(Action): self._actmat = {} self._maxprecs = {} - cpdef acting_matrix(self, g, M): + cpdef acting_matrix(self, g, M) noexcept: r""" The matrix defining the action of ``g`` at precision ``M``. @@ -1328,7 +1328,7 @@ cdef class WeightKAction(Action): mats[M] = A return A - cpdef _compute_acting_matrix(self, g, M): + cpdef _compute_acting_matrix(self, g, M) noexcept: r""" Compute the matrix defining the action of ``g`` at precision ``M``. @@ -1357,7 +1357,7 @@ cdef class WeightKAction(Action): cdef class WeightKAction_vector(WeightKAction): - cpdef _compute_acting_matrix(self, g, M): + cpdef _compute_acting_matrix(self, g, M) noexcept: r""" Compute the matrix defining the action of ``g`` at precision ``M``. @@ -1419,7 +1419,7 @@ cdef class WeightKAction_vector(WeightKAction): B *= (a * d - b * c) ** (self._dettwist) return B - cpdef _act_(self, g, _v): + cpdef _act_(self, g, _v) noexcept: r""" The right action of ``g`` on a distribution. diff --git a/src/sage/modules/finite_submodule_iter.pxd b/src/sage/modules/finite_submodule_iter.pxd index 8173f265673..900f041e3a0 100644 --- a/src/sage/modules/finite_submodule_iter.pxd +++ b/src/sage/modules/finite_submodule_iter.pxd @@ -13,7 +13,7 @@ cdef class FiniteZZsubmodule_iterator: cdef int _count cdef int _order cdef bint _immutable - cdef ModuleElement _iteration(FiniteZZsubmodule_iterator self) + cdef ModuleElement _iteration(FiniteZZsubmodule_iterator self) noexcept cdef class FiniteFieldsubspace_iterator(FiniteZZsubmodule_iterator): pass diff --git a/src/sage/modules/finite_submodule_iter.pyx b/src/sage/modules/finite_submodule_iter.pyx index bb4a730cad9..ab335200e0d 100644 --- a/src/sage/modules/finite_submodule_iter.pyx +++ b/src/sage/modules/finite_submodule_iter.pyx @@ -190,7 +190,7 @@ cdef class FiniteZZsubmodule_iterator: """ return self - cdef ModuleElement _iteration(FiniteZZsubmodule_iterator self): + cdef ModuleElement _iteration(FiniteZZsubmodule_iterator self) noexcept: """ This is the core implementation of the iteration. diff --git a/src/sage/modules/free_module.py b/src/sage/modules/free_module.py index 8f584a211ef..5a65b4260f0 100644 --- a/src/sage/modules/free_module.py +++ b/src/sage/modules/free_module.py @@ -5387,7 +5387,7 @@ def _coerce_map_from_(self, M): if (self.base_ring().has_coerce_map_from(M.base_ring()) and self.rank() == M.degree()): return True - return super(FreeModule_ambient, self)._coerce_map_from_(M) + return super()._coerce_map_from_(M) def _dense_module(self): """ diff --git a/src/sage/modules/free_module_element.pxd b/src/sage/modules/free_module_element.pxd index 64a1760a259..e524a458474 100644 --- a/src/sage/modules/free_module_element.pxd +++ b/src/sage/modules/free_module_element.pxd @@ -2,15 +2,15 @@ from sage.structure.element cimport Vector cdef class FreeModuleElement(Vector): cdef int set_unsafe(self, Py_ssize_t i, value) except -1 - cdef get_unsafe(self, Py_ssize_t i) - cpdef int hamming_weight(self) + cdef get_unsafe(self, Py_ssize_t i) noexcept + cpdef int hamming_weight(self) noexcept cdef class FreeModuleElement_generic_dense(FreeModuleElement): # data cdef list _entries # cdef'd methods - cdef _new_c(self, object v) + cdef _new_c(self, object v) noexcept cdef class FreeModuleElement_generic_sparse(FreeModuleElement): @@ -18,5 +18,5 @@ cdef class FreeModuleElement_generic_sparse(FreeModuleElement): cdef dict _entries # cdef'd methods - cdef _new_c(self, object v) + cdef _new_c(self, object v) noexcept diff --git a/src/sage/modules/free_module_element.pyx b/src/sage/modules/free_module_element.pyx index c9af9bcbdf7..a2c077cc8c8 100644 --- a/src/sage/modules/free_module_element.pyx +++ b/src/sage/modules/free_module_element.pyx @@ -1762,7 +1762,7 @@ cdef class FreeModuleElement(Vector): # abstract base class s = sum(a ** p for a in abs_self) return s**(__one__/p) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ EXAMPLES:: @@ -1842,7 +1842,7 @@ cdef class FreeModuleElement(Vector): # abstract base class raise IndexError("vector index out of range") return self.get_unsafe(n) - cdef get_unsafe(self, Py_ssize_t i): + cdef get_unsafe(self, Py_ssize_t i) noexcept: """ Cython function to get the `i`'th entry of this vector. @@ -2484,7 +2484,7 @@ cdef class FreeModuleElement(Vector): # abstract base class else: return points(v, **kwds) - cpdef _dot_product_coerce_(left, Vector right): + cpdef _dot_product_coerce_(left, Vector right) noexcept: """ Return the dot product of left and right. @@ -3584,7 +3584,7 @@ cdef class FreeModuleElement(Vector): # abstract base class """ return self.is_dense_c() - cdef bint is_dense_c(self): + cdef bint is_dense_c(self) noexcept: return self.parent().is_dense() def is_sparse(self): @@ -3602,7 +3602,7 @@ cdef class FreeModuleElement(Vector): # abstract base class """ return self.is_sparse_c() - cdef bint is_sparse_c(self): + cdef bint is_sparse_c(self) noexcept: return self.parent().is_sparse() def is_vector(self): @@ -3760,7 +3760,7 @@ cdef class FreeModuleElement(Vector): # abstract base class """ return self.nonzero_positions() - cpdef int hamming_weight(self): + cpdef int hamming_weight(self) noexcept: """ Return the number of positions ``i`` such that ``self[i] != 0``. @@ -4227,7 +4227,7 @@ cdef class FreeModuleElement_generic_dense(FreeModuleElement): sage: isinstance(hash(v), int) True """ - cdef _new_c(self, object v): + cdef _new_c(self, object v) noexcept: """ Create a new dense free module element with minimal overhead and no type checking. @@ -4245,10 +4245,10 @@ cdef class FreeModuleElement_generic_dense(FreeModuleElement): x._degree = self._degree return x - cdef bint is_dense_c(self): + cdef bint is_dense_c(self) noexcept: return 1 - cdef bint is_sparse_c(self): + cdef bint is_sparse_c(self) noexcept: return 0 def __copy__(self): @@ -4371,7 +4371,7 @@ cdef class FreeModuleElement_generic_dense(FreeModuleElement): @cython.boundscheck(False) @cython.wraparound(False) - cpdef _add_(left, right): + cpdef _add_(left, right) noexcept: """ Add left and right. @@ -4388,7 +4388,7 @@ cdef class FreeModuleElement_generic_dense(FreeModuleElement): @cython.boundscheck(False) @cython.wraparound(False) - cpdef _sub_(left, right): + cpdef _sub_(left, right) noexcept: """ Subtract right from left. @@ -4406,7 +4406,7 @@ cdef class FreeModuleElement_generic_dense(FreeModuleElement): v = [( a[i])._sub_( b[i]) for i in range(left._degree)] return left._new_c(v) - cpdef _rmul_(self, Element left): + cpdef _rmul_(self, Element left) noexcept: """ EXAMPLES:: @@ -4420,7 +4420,7 @@ cdef class FreeModuleElement_generic_dense(FreeModuleElement): v = [left * x for x in self._entries] return self._new_c(v) - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: """ EXAMPLES:: @@ -4438,7 +4438,7 @@ cdef class FreeModuleElement_generic_dense(FreeModuleElement): @cython.boundscheck(False) @cython.wraparound(False) - cpdef _pairwise_product_(left, Vector right): + cpdef _pairwise_product_(left, Vector right) noexcept: """ EXAMPLES:: @@ -4470,7 +4470,7 @@ cdef class FreeModuleElement_generic_dense(FreeModuleElement): @cython.boundscheck(False) @cython.wraparound(False) - cdef get_unsafe(self, Py_ssize_t i): + cdef get_unsafe(self, Py_ssize_t i) noexcept: """ EXAMPLES:: @@ -4678,7 +4678,7 @@ cdef class FreeModuleElement_generic_sparse(FreeModuleElement): sage: (b-a).dict() {2: -1} """ - cdef _new_c(self, object v): + cdef _new_c(self, object v) noexcept: """ Create a new sparse free module element with minimal overhead and no type checking. @@ -4696,10 +4696,10 @@ cdef class FreeModuleElement_generic_sparse(FreeModuleElement): x._degree = self._degree return x - cdef bint is_dense_c(self): + cdef bint is_dense_c(self) noexcept: return 0 - cdef bint is_sparse_c(self): + cdef bint is_sparse_c(self) noexcept: return 1 def __copy__(self): @@ -4829,7 +4829,7 @@ cdef class FreeModuleElement_generic_sparse(FreeModuleElement): entries_dict = dict(entries_dict) # make a copy/convert to dict self._entries = entries_dict - cpdef _add_(left, right): + cpdef _add_(left, right) noexcept: """ Add left and right. @@ -4851,7 +4851,7 @@ cdef class FreeModuleElement_generic_sparse(FreeModuleElement): v[i] = a return left._new_c(v) - cpdef _sub_(left, right): + cpdef _sub_(left, right) noexcept: """ EXAMPLES:: @@ -4871,7 +4871,7 @@ cdef class FreeModuleElement_generic_sparse(FreeModuleElement): v[i] = -a return left._new_c(v) - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: """ EXAMPLES:: @@ -4887,7 +4887,7 @@ cdef class FreeModuleElement_generic_sparse(FreeModuleElement): v[i] = prod return self._new_c(v) - cpdef _rmul_(self, Element left): + cpdef _rmul_(self, Element left) noexcept: """ EXAMPLES:: @@ -4903,7 +4903,7 @@ cdef class FreeModuleElement_generic_sparse(FreeModuleElement): v[i] = prod return self._new_c(v) - cpdef _dot_product_coerce_(left, Vector right): + cpdef _dot_product_coerce_(left, Vector right) noexcept: """ Return the dot product of left and right. @@ -4955,7 +4955,7 @@ cdef class FreeModuleElement_generic_sparse(FreeModuleElement): z += a * e[i] return z - cpdef _pairwise_product_(left, Vector right): + cpdef _pairwise_product_(left, Vector right) noexcept: """ EXAMPLES:: @@ -4973,7 +4973,7 @@ cdef class FreeModuleElement_generic_sparse(FreeModuleElement): v[i] = prod return left._new_c(v) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Compare two sparse free module elements. @@ -5104,7 +5104,7 @@ cdef class FreeModuleElement_generic_sparse(FreeModuleElement): raise IndexError("vector index out of range") return self.get_unsafe(n) - cdef get_unsafe(self, Py_ssize_t i): + cdef get_unsafe(self, Py_ssize_t i) noexcept: """ EXAMPLES:: @@ -5269,7 +5269,7 @@ cdef class FreeModuleElement_generic_sparse(FreeModuleElement): """ return sorted(self._entries) - cpdef int hamming_weight(self): + cpdef int hamming_weight(self) noexcept: """ Returns the number of positions ``i`` such that ``self[i] != 0``. diff --git a/src/sage/modules/module.pyx b/src/sage/modules/module.pyx index 818d139c3ba..21bb44f8e67 100644 --- a/src/sage/modules/module.pyx +++ b/src/sage/modules/module.pyx @@ -132,7 +132,7 @@ cdef class Module(Parent): category = Modules(base) Parent.__init__(self, base=base, category=category, names=names) - cpdef _coerce_map_from_(self, M): + cpdef _coerce_map_from_(self, M) noexcept: """ Return a coercion map from `M` to ``self``, or None. diff --git a/src/sage/modules/vector_double_dense.pyx b/src/sage/modules/vector_double_dense.pyx index 551da99669e..a47d91a7fdd 100644 --- a/src/sage/modules/vector_double_dense.pyx +++ b/src/sage/modules/vector_double_dense.pyx @@ -81,7 +81,7 @@ cdef class Vector_double_dense(Vector_numpy_dense): 30.0 """ - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Add two vectors together. @@ -101,7 +101,7 @@ cdef class Vector_double_dense(Vector_numpy_dense): return self._new(_left._vector_numpy + _right._vector_numpy) - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Return self - right @@ -121,7 +121,7 @@ cdef class Vector_double_dense(Vector_numpy_dense): return self._new(_left._vector_numpy - _right._vector_numpy) - cpdef _dot_product_(self, Vector right): + cpdef _dot_product_(self, Vector right) noexcept: """ Dot product of self and right. @@ -145,7 +145,7 @@ cdef class Vector_double_dense(Vector_numpy_dense): return self._sage_dtype(numpy.dot(_left._vector_numpy, _right._vector_numpy)) - cpdef _pairwise_product_(self, Vector right): + cpdef _pairwise_product_(self, Vector right) noexcept: """ Return the component-wise product of self and right. @@ -168,7 +168,7 @@ cdef class Vector_double_dense(Vector_numpy_dense): return self._new(_left._vector_numpy * _right._vector_numpy) - cpdef _rmul_(self, Element left): + cpdef _rmul_(self, Element left) noexcept: """ Multiply a scalar and vector @@ -184,7 +184,7 @@ cdef class Vector_double_dense(Vector_numpy_dense): return self._new(self._python_dtype(left)*self._vector_numpy) - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: """ Multiply a scalar and vector diff --git a/src/sage/modules/vector_integer_dense.pxd b/src/sage/modules/vector_integer_dense.pxd index 6a221546b34..322a10c369b 100644 --- a/src/sage/modules/vector_integer_dense.pxd +++ b/src/sage/modules/vector_integer_dense.pxd @@ -6,7 +6,7 @@ cdef class Vector_integer_dense(FreeModuleElement): cdef mpz_t* _entries cdef int _init(self, Py_ssize_t degree, Parent parent) except -1 - cdef inline Vector_integer_dense _new_c(self): + cdef inline Vector_integer_dense _new_c(self) noexcept: cdef type t = type(self) cdef Vector_integer_dense x = (t.__new__(t)) x._init(self._degree, self._parent) diff --git a/src/sage/modules/vector_integer_dense.pyx b/src/sage/modules/vector_integer_dense.pyx index 177ada5dea1..52e0bbd4064 100644 --- a/src/sage/modules/vector_integer_dense.pyx +++ b/src/sage/modules/vector_integer_dense.pyx @@ -65,9 +65,9 @@ cimport sage.modules.free_module_element as free_module_element from sage.libs.gmp.mpz cimport * cdef class Vector_integer_dense(free_module_element.FreeModuleElement): - cdef bint is_dense_c(self): + cdef bint is_dense_c(self) noexcept: return 1 - cdef bint is_sparse_c(self): + cdef bint is_sparse_c(self) noexcept: return 0 def __copy__(self): @@ -130,7 +130,7 @@ cdef class Vector_integer_dense(free_module_element.FreeModuleElement): mpz_clear(self._entries[i]) sig_free(self._entries) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ EXAMPLES:: @@ -159,7 +159,7 @@ cdef class Vector_integer_dense(free_module_element.FreeModuleElement): return rich_to_bool(op, 1) return rich_to_bool(op, 0) - cdef get_unsafe(self, Py_ssize_t i): + cdef get_unsafe(self, Py_ssize_t i) noexcept: """ EXAMPLES:: @@ -215,7 +215,7 @@ cdef class Vector_integer_dense(free_module_element.FreeModuleElement): return (unpickle_v1, (self._parent, self.list(), self._degree, not self._is_immutable)) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: cdef Vector_integer_dense z, r r = right z = self._new_c() @@ -225,7 +225,7 @@ cdef class Vector_integer_dense(free_module_element.FreeModuleElement): return z - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: cdef Vector_integer_dense z, r r = right z = self._new_c() @@ -234,7 +234,7 @@ cdef class Vector_integer_dense(free_module_element.FreeModuleElement): mpz_sub(z._entries[i], self._entries[i], r._entries[i]) return z - cpdef _dot_product_(self, Vector right): + cpdef _dot_product_(self, Vector right) noexcept: """ Dot product of dense vectors over the integers. @@ -258,7 +258,7 @@ cdef class Vector_integer_dense(free_module_element.FreeModuleElement): mpz_clear(t) return z - cpdef _pairwise_product_(self, Vector right): + cpdef _pairwise_product_(self, Vector right) noexcept: """ EXAMPLES:: @@ -274,7 +274,7 @@ cdef class Vector_integer_dense(free_module_element.FreeModuleElement): mpz_mul(z._entries[i], self._entries[i], r._entries[i]) return z - cpdef _rmul_(self, Element left): + cpdef _rmul_(self, Element left) noexcept: cdef Vector_integer_dense z cdef Integer a a = left @@ -284,7 +284,7 @@ cdef class Vector_integer_dense(free_module_element.FreeModuleElement): mpz_mul(z._entries[i], self._entries[i], a.value) return z - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: cdef Vector_integer_dense z cdef Integer a a = right @@ -294,7 +294,7 @@ cdef class Vector_integer_dense(free_module_element.FreeModuleElement): mpz_mul(z._entries[i], self._entries[i], a.value) return z - cpdef _neg_(self): + cpdef _neg_(self) noexcept: cdef Vector_integer_dense z z = self._new_c() cdef Py_ssize_t i diff --git a/src/sage/modules/vector_integer_sparse.pxd b/src/sage/modules/vector_integer_sparse.pxd index 463b3b2c0e1..4791b778497 100644 --- a/src/sage/modules/vector_integer_sparse.pxd +++ b/src/sage/modules/vector_integer_sparse.pxd @@ -14,15 +14,15 @@ cdef struct mpz_vector: cdef int allocate_mpz_vector(mpz_vector* v, Py_ssize_t num_nonzero) except -1 cdef int mpz_vector_init(mpz_vector* v, Py_ssize_t degree, Py_ssize_t num_nonzero) except -1 -cdef void mpz_vector_clear(mpz_vector* v) -cdef Py_ssize_t mpz_binary_search0(mpz_t* v, Py_ssize_t n, mpz_t x) -cdef Py_ssize_t mpz_binary_search(mpz_t* v, Py_ssize_t n, mpz_t x, Py_ssize_t* ins) +cdef void mpz_vector_clear(mpz_vector* v) noexcept +cdef Py_ssize_t mpz_binary_search0(mpz_t* v, Py_ssize_t n, mpz_t x) noexcept +cdef Py_ssize_t mpz_binary_search(mpz_t* v, Py_ssize_t n, mpz_t x, Py_ssize_t* ins) noexcept cdef int mpz_vector_get_entry(mpz_t ans, mpz_vector* v, Py_ssize_t n) except -1 -cdef bint mpz_vector_is_entry_zero_unsafe(mpz_vector* v, Py_ssize_t n) -cdef object mpz_vector_to_list(mpz_vector* v) +cdef bint mpz_vector_is_entry_zero_unsafe(mpz_vector* v, Py_ssize_t n) noexcept +cdef object mpz_vector_to_list(mpz_vector* v) noexcept cdef int mpz_vector_set_entry(mpz_vector* v, Py_ssize_t n, mpz_t x) except -1 cdef int mpz_vector_set_entry_str(mpz_vector* v, Py_ssize_t n, char *x_str) except -1 cdef int add_mpz_vector_init(mpz_vector* sum, mpz_vector* v, mpz_vector* w, mpz_t multiple) except -1 cdef int mpz_vector_scale(mpz_vector* v, mpz_t scalar) except -1 cdef int mpz_vector_scalar_multiply(mpz_vector* v, mpz_vector* w, mpz_t scalar) except -1 -cdef int mpz_vector_cmp(mpz_vector* v, mpz_vector* w) +cdef int mpz_vector_cmp(mpz_vector* v, mpz_vector* w) noexcept diff --git a/src/sage/modules/vector_integer_sparse.pyx b/src/sage/modules/vector_integer_sparse.pyx index de91aab408e..9fdecf6a326 100644 --- a/src/sage/modules/vector_integer_sparse.pyx +++ b/src/sage/modules/vector_integer_sparse.pyx @@ -42,7 +42,7 @@ cdef int mpz_vector_init(mpz_vector* v, Py_ssize_t degree, Py_ssize_t num_nonzer v.num_nonzero = num_nonzero v.degree = degree -cdef void mpz_vector_clear(mpz_vector* v): +cdef void mpz_vector_clear(mpz_vector* v) noexcept: cdef Py_ssize_t i # Free all mpz objects allocated in creating v for i from 0 <= i < v.num_nonzero: @@ -54,7 +54,7 @@ cdef void mpz_vector_clear(mpz_vector* v): sig_free(v.entries) sig_free(v.positions) -cdef Py_ssize_t mpz_binary_search0(mpz_t* v, Py_ssize_t n, mpz_t x): +cdef Py_ssize_t mpz_binary_search0(mpz_t* v, Py_ssize_t n, mpz_t x) noexcept: """ Find the position of the integers x in the array v, which has length n. Returns -1 if x is not in the array v. @@ -79,7 +79,7 @@ cdef Py_ssize_t mpz_binary_search0(mpz_t* v, Py_ssize_t n, mpz_t x): return k return -1 -cdef Py_ssize_t mpz_binary_search(mpz_t* v, Py_ssize_t n, mpz_t x, Py_ssize_t* ins): +cdef Py_ssize_t mpz_binary_search(mpz_t* v, Py_ssize_t n, mpz_t x, Py_ssize_t* ins) noexcept: """ Find the position of the integer x in the array v, which has length n. Returns -1 if x is not in the array v, and in this case ins is @@ -142,7 +142,7 @@ cdef int mpz_vector_get_entry(mpz_t ans, mpz_vector* v, Py_ssize_t n) except -1: mpz_set(ans, v.entries[m]) return 0 -cdef bint mpz_vector_is_entry_zero_unsafe(mpz_vector* v, Py_ssize_t n): +cdef bint mpz_vector_is_entry_zero_unsafe(mpz_vector* v, Py_ssize_t n) noexcept: """ Return if the ``n``-th entry of the sparse vector ``v`` is zero. @@ -151,7 +151,7 @@ cdef bint mpz_vector_is_entry_zero_unsafe(mpz_vector* v, Py_ssize_t n): """ return binary_search0(v.positions, v.num_nonzero, n) == -1 -cdef object mpz_vector_to_list(mpz_vector* v): +cdef object mpz_vector_to_list(mpz_vector* v) noexcept: """ Returns a Python list of 2-tuples (i,x), where x=v[i] runs through the nonzero elements of x, in order. @@ -388,7 +388,7 @@ cdef int mpz_vector_scalar_multiply(mpz_vector* v, mpz_vector* w, mpz_t scalar) v.positions[i] = w.positions[i] return 0 -cdef int mpz_vector_cmp(mpz_vector* v, mpz_vector* w): +cdef int mpz_vector_cmp(mpz_vector* v, mpz_vector* w) noexcept: if v.degree < w.degree: return -1 elif v.degree > w.degree: diff --git a/src/sage/modules/vector_mod2_dense.pxd b/src/sage/modules/vector_mod2_dense.pxd index a5542fe1345..98a77624019 100644 --- a/src/sage/modules/vector_mod2_dense.pxd +++ b/src/sage/modules/vector_mod2_dense.pxd @@ -6,5 +6,5 @@ cdef class Vector_mod2_dense(FreeModuleElement): cdef mzd_t* _entries cdef object _base_ring - cdef _new_c(self) - cdef _init(self, Py_ssize_t degree, parent) + cdef _new_c(self) noexcept + cdef _init(self, Py_ssize_t degree, parent) noexcept diff --git a/src/sage/modules/vector_mod2_dense.pyx b/src/sage/modules/vector_mod2_dense.pyx index 93fc3f32cd1..243d8020138 100644 --- a/src/sage/modules/vector_mod2_dense.pyx +++ b/src/sage/modules/vector_mod2_dense.pyx @@ -50,7 +50,7 @@ cimport sage.modules.free_module_element as free_module_element from sage.libs.m4ri cimport * cdef class Vector_mod2_dense(free_module_element.FreeModuleElement): - cdef _new_c(self): + cdef _new_c(self) noexcept: """ EXAMPLES:: @@ -65,7 +65,7 @@ cdef class Vector_mod2_dense(free_module_element.FreeModuleElement): y._init(self._degree, self._parent) return y - cdef bint is_dense_c(self): + cdef bint is_dense_c(self) noexcept: """ EXAMPLES:: @@ -75,7 +75,7 @@ cdef class Vector_mod2_dense(free_module_element.FreeModuleElement): """ return 1 - cdef bint is_sparse_c(self): + cdef bint is_sparse_c(self) noexcept: """ EXAMPLES:: @@ -105,7 +105,7 @@ cdef class Vector_mod2_dense(free_module_element.FreeModuleElement): mzd_copy(y._entries, self._entries) return y - cdef _init(self, Py_ssize_t degree, parent): + cdef _init(self, Py_ssize_t degree, parent) noexcept: """ EXAMPLES:: @@ -227,7 +227,7 @@ cdef class Vector_mod2_dense(free_module_element.FreeModuleElement): if self._entries: mzd_free(self._entries) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ EXAMPLES:: @@ -253,7 +253,7 @@ cdef class Vector_mod2_dense(free_module_element.FreeModuleElement): c = mzd_cmp(left._entries, (right)._entries) return rich_to_bool(op, c) - cdef get_unsafe(self, Py_ssize_t i): + cdef get_unsafe(self, Py_ssize_t i) noexcept: """ EXAMPLES:: @@ -302,7 +302,7 @@ cdef class Vector_mod2_dense(free_module_element.FreeModuleElement): return unpickle_v0, (self._parent, self.list(), self._degree, self._is_immutable) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ EXAMPLES:: @@ -317,7 +317,7 @@ cdef class Vector_mod2_dense(free_module_element.FreeModuleElement): mzd_add(z._entries, self._entries, (right)._entries) return z - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ EXAMPLES:: @@ -332,7 +332,7 @@ cdef class Vector_mod2_dense(free_module_element.FreeModuleElement): mzd_add(z._entries, self._entries, (right)._entries) return z - cpdef int hamming_weight(self): + cpdef int hamming_weight(self) noexcept: """ Return the number of positions ``i`` such that ``self[i] != 0``. @@ -349,7 +349,7 @@ cdef class Vector_mod2_dense(free_module_element.FreeModuleElement): return res - cpdef _dot_product_(self, Vector right): + cpdef _dot_product_(self, Vector right) noexcept: """ EXAMPLES:: @@ -397,7 +397,7 @@ cdef class Vector_mod2_dense(free_module_element.FreeModuleElement): return n - cpdef _pairwise_product_(self, Vector right): + cpdef _pairwise_product_(self, Vector right) noexcept: """ EXAMPLES:: @@ -419,7 +419,7 @@ cdef class Vector_mod2_dense(free_module_element.FreeModuleElement): zrow[i] = (lrow[i] & rrow[i]) return z - cpdef _lmul_(self, Element left): + cpdef _lmul_(self, Element left) noexcept: """ EXAMPLES:: @@ -450,7 +450,7 @@ cdef class Vector_mod2_dense(free_module_element.FreeModuleElement): else: return self._new_c() - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ EXAMPLES:: diff --git a/src/sage/modules/vector_modn_dense.pxd b/src/sage/modules/vector_modn_dense.pxd index 4e0aff593fe..2482f999d37 100644 --- a/src/sage/modules/vector_modn_dense.pxd +++ b/src/sage/modules/vector_modn_dense.pxd @@ -6,6 +6,6 @@ cdef class Vector_modn_dense(FreeModuleElement): cdef mod_int _p cdef object _base_ring - cdef _new_c(self) - cdef _init(self, Py_ssize_t degree, parent, mod_int p) + cdef _new_c(self) noexcept + cdef _init(self, Py_ssize_t degree, parent, mod_int p) noexcept diff --git a/src/sage/modules/vector_modn_dense.pyx b/src/sage/modules/vector_modn_dense.pyx index 8608672031d..57103bd48c4 100644 --- a/src/sage/modules/vector_modn_dense.pyx +++ b/src/sage/modules/vector_modn_dense.pyx @@ -135,16 +135,16 @@ cimport sage.modules.free_module_element as free_module_element cdef class Vector_modn_dense(free_module_element.FreeModuleElement): - cdef _new_c(self): + cdef _new_c(self) noexcept: cdef Vector_modn_dense y y = Vector_modn_dense.__new__(Vector_modn_dense) y._init(self._degree, self._parent, self._p) return y - cdef bint is_dense_c(self): + cdef bint is_dense_c(self) noexcept: return 1 - cdef bint is_sparse_c(self): + cdef bint is_sparse_c(self) noexcept: return 0 def __copy__(self): @@ -155,7 +155,7 @@ cdef class Vector_modn_dense(free_module_element.FreeModuleElement): y._entries[i] = self._entries[i] return y - cdef _init(self, Py_ssize_t degree, parent, mod_int p): + cdef _init(self, Py_ssize_t degree, parent, mod_int p) noexcept: self._degree = degree self._parent = parent self._p = p @@ -194,7 +194,7 @@ cdef class Vector_modn_dense(free_module_element.FreeModuleElement): def __dealloc__(self): sig_free(self._entries) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ EXAMPLES:: @@ -220,7 +220,7 @@ cdef class Vector_modn_dense(free_module_element.FreeModuleElement): return rich_to_bool(op, 1) return rich_to_bool(op, 0) - cdef get_unsafe(self, Py_ssize_t i): + cdef get_unsafe(self, Py_ssize_t i) noexcept: """ EXAMPLES:: @@ -276,7 +276,7 @@ cdef class Vector_modn_dense(free_module_element.FreeModuleElement): return unpickle_v1, (self._parent, self.list(), self._degree, self._p, not self._is_immutable) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: cdef Vector_modn_dense z, r r = right z = self._new_c() @@ -286,7 +286,7 @@ cdef class Vector_modn_dense(free_module_element.FreeModuleElement): return z - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: cdef Vector_modn_dense z, r r = right z = self._new_c() @@ -295,7 +295,7 @@ cdef class Vector_modn_dense(free_module_element.FreeModuleElement): z._entries[i] = (self._p + self._entries[i] - r._entries[i]) % self._p return z - cpdef _dot_product_(self, Vector right): + cpdef _dot_product_(self, Vector right) noexcept: cdef size_t i cdef IntegerMod_int n cdef IntegerMod_int64 m @@ -316,7 +316,7 @@ cdef class Vector_modn_dense(free_module_element.FreeModuleElement): m.ivalue = (m.ivalue + self._entries[i] * r._entries[i]) % self._p return m - cpdef _pairwise_product_(self, Vector right): + cpdef _pairwise_product_(self, Vector right) noexcept: """ EXAMPLES:: @@ -334,7 +334,7 @@ cdef class Vector_modn_dense(free_module_element.FreeModuleElement): z._entries[i] = (self._entries[i] * r._entries[i]) % self._p return z - cpdef _lmul_(self, Element left): + cpdef _lmul_(self, Element left) noexcept: cdef Vector_modn_dense z cdef mod_int a = ivalue(left) @@ -345,7 +345,7 @@ cdef class Vector_modn_dense(free_module_element.FreeModuleElement): z._entries[i] = (self._entries[i] * a) % self._p return z - cpdef _neg_(self): + cpdef _neg_(self) noexcept: cdef Vector_modn_dense z z = self._new_c() cdef Py_ssize_t i diff --git a/src/sage/modules/vector_modn_sparse.pxd b/src/sage/modules/vector_modn_sparse.pxd index 41d2dd1dd43..d345ecd1e12 100644 --- a/src/sage/modules/vector_modn_sparse.pxd +++ b/src/sage/modules/vector_modn_sparse.pxd @@ -9,12 +9,12 @@ cdef struct c_vector_modint: cdef int allocate_c_vector_modint(c_vector_modint* v, Py_ssize_t num_nonzero) except -1 cdef int init_c_vector_modint(c_vector_modint* v, int p, Py_ssize_t degree, Py_ssize_t num_nonzero) except -1 -cdef void clear_c_vector_modint(c_vector_modint* v) -cdef Py_ssize_t binary_search0_modn(Py_ssize_t* v, Py_ssize_t n, int_fast64_t x) -cdef Py_ssize_t binary_search_modn(Py_ssize_t* v, Py_ssize_t n, int_fast64_t x, Py_ssize_t* ins) +cdef void clear_c_vector_modint(c_vector_modint* v) noexcept +cdef Py_ssize_t binary_search0_modn(Py_ssize_t* v, Py_ssize_t n, int_fast64_t x) noexcept +cdef Py_ssize_t binary_search_modn(Py_ssize_t* v, Py_ssize_t n, int_fast64_t x, Py_ssize_t* ins) noexcept cdef int_fast64_t get_entry(c_vector_modint* v, Py_ssize_t n) except -1 -cdef bint is_entry_zero_unsafe(c_vector_modint* v, Py_ssize_t n) -cdef object to_list(c_vector_modint* v) +cdef bint is_entry_zero_unsafe(c_vector_modint* v, Py_ssize_t n) noexcept +cdef object to_list(c_vector_modint* v) noexcept cdef int set_entry(c_vector_modint* v, Py_ssize_t n, int_fast64_t x) except -1 cdef int add_c_vector_modint_init(c_vector_modint* sum, c_vector_modint* v, c_vector_modint* w, int multiple) except -1 cdef int scale_c_vector_modint(c_vector_modint* v, int_fast64_t scalar) except -1 diff --git a/src/sage/modules/vector_modn_sparse.pyx b/src/sage/modules/vector_modn_sparse.pyx index e2dd1d7c1a6..9ea760c31a2 100644 --- a/src/sage/modules/vector_modn_sparse.pyx +++ b/src/sage/modules/vector_modn_sparse.pyx @@ -38,12 +38,12 @@ cdef int init_c_vector_modint(c_vector_modint* v, int p, Py_ssize_t degree, return 0 -cdef void clear_c_vector_modint(c_vector_modint* v): +cdef void clear_c_vector_modint(c_vector_modint* v) noexcept: sig_free(v.entries) sig_free(v.positions) -cdef Py_ssize_t binary_search0_modn(Py_ssize_t* v, Py_ssize_t n, int_fast64_t x): +cdef Py_ssize_t binary_search0_modn(Py_ssize_t* v, Py_ssize_t n, int_fast64_t x) noexcept: """ Find the position of the int x in the array v, which has length n. @@ -70,7 +70,7 @@ cdef Py_ssize_t binary_search0_modn(Py_ssize_t* v, Py_ssize_t n, int_fast64_t x) return -1 -cdef Py_ssize_t binary_search_modn(Py_ssize_t* v, Py_ssize_t n, int_fast64_t x, Py_ssize_t* ins): +cdef Py_ssize_t binary_search_modn(Py_ssize_t* v, Py_ssize_t n, int_fast64_t x, Py_ssize_t* ins) noexcept: """ Find the position of the integer x in the array v, which has length n. @@ -121,7 +121,7 @@ cdef int_fast64_t get_entry(c_vector_modint* v, Py_ssize_t n) except -1: return 0 return v.entries[m] -cdef bint is_entry_zero_unsafe(c_vector_modint* v, Py_ssize_t n): +cdef bint is_entry_zero_unsafe(c_vector_modint* v, Py_ssize_t n) noexcept: """ Return if the ``n``-th entry of the sparse vector ``v`` is zero. @@ -130,7 +130,7 @@ cdef bint is_entry_zero_unsafe(c_vector_modint* v, Py_ssize_t n): """ return binary_search0_modn(v.positions, v.num_nonzero, n) == -1 -cdef object to_list(c_vector_modint* v): +cdef object to_list(c_vector_modint* v) noexcept: """ Return a Python list of 2-tuples (i,x), where x=v[i] runs through the nonzero elements of x, in order. diff --git a/src/sage/modules/vector_numpy_dense.pxd b/src/sage/modules/vector_numpy_dense.pxd index b019bc8ebac..6af57a997c5 100644 --- a/src/sage/modules/vector_numpy_dense.pxd +++ b/src/sage/modules/vector_numpy_dense.pxd @@ -8,5 +8,5 @@ cdef class Vector_numpy_dense(FreeModuleElement): cdef object _sage_dtype cdef object _sage_vector_dtype cdef numpy.ndarray _vector_numpy - cdef Vector_numpy_dense _new(self, numpy.ndarray vector_numpy) - cdef _replace_self_with_numpy(self, numpy.ndarray numpy_array) + cdef Vector_numpy_dense _new(self, numpy.ndarray vector_numpy) noexcept + cdef _replace_self_with_numpy(self, numpy.ndarray numpy_array) noexcept diff --git a/src/sage/modules/vector_numpy_dense.pyx b/src/sage/modules/vector_numpy_dense.pyx index f0e2224b96d..fc14cc4829a 100644 --- a/src/sage/modules/vector_numpy_dense.pyx +++ b/src/sage/modules/vector_numpy_dense.pyx @@ -68,7 +68,7 @@ cdef class Vector_numpy_dense(FreeModuleElement): self._degree = parent.degree() self._parent = parent - cdef Vector_numpy_dense _new(self, numpy.ndarray vector_numpy): + cdef Vector_numpy_dense _new(self, numpy.ndarray vector_numpy) noexcept: """ Return a new vector with same parent as self. """ @@ -101,13 +101,13 @@ cdef class Vector_numpy_dense(FreeModuleElement): self._vector_numpy = numpy.PyArray_SimpleNew(1, dims, self._numpy_dtypeint) return - cdef bint is_dense_c(self): + cdef bint is_dense_c(self) noexcept: """ Return True (i.e., 1) if self is dense. """ return 1 - cdef bint is_sparse_c(self): + cdef bint is_sparse_c(self) noexcept: """ Return True (i.e., 1) if self is sparse. """ @@ -231,7 +231,7 @@ cdef class Vector_numpy_dense(FreeModuleElement): self._python_dtype(value)) #TODO: Throw an error if status == -1 - cdef get_unsafe(self, Py_ssize_t i): + cdef get_unsafe(self, Py_ssize_t i) noexcept: """ EXAMPLES:: @@ -248,7 +248,7 @@ cdef class Vector_numpy_dense(FreeModuleElement): return self._sage_dtype(numpy.PyArray_GETITEM(self._vector_numpy, numpy.PyArray_GETPTR1(self._vector_numpy, i))) - cdef _replace_self_with_numpy(self, numpy.ndarray numpy_array): + cdef _replace_self_with_numpy(self, numpy.ndarray numpy_array) noexcept: """ Replace the underlying numpy array with numpy_array. """ diff --git a/src/sage/modules/vector_rational_dense.pxd b/src/sage/modules/vector_rational_dense.pxd index 34db6f6252b..1bcde479153 100644 --- a/src/sage/modules/vector_rational_dense.pxd +++ b/src/sage/modules/vector_rational_dense.pxd @@ -6,7 +6,7 @@ cdef class Vector_rational_dense(FreeModuleElement): cdef mpq_t* _entries cdef int _init(self, Py_ssize_t degree, Parent parent) except -1 - cdef inline Vector_rational_dense _new_c(self): + cdef inline Vector_rational_dense _new_c(self) noexcept: cdef type t = type(self) cdef Vector_rational_dense x = (t.__new__(t)) x._init(self._degree, self._parent) diff --git a/src/sage/modules/vector_rational_dense.pyx b/src/sage/modules/vector_rational_dense.pyx index 34b23515348..bca39f51f5a 100644 --- a/src/sage/modules/vector_rational_dense.pyx +++ b/src/sage/modules/vector_rational_dense.pyx @@ -67,15 +67,15 @@ cimport sage.modules.free_module_element as free_module_element from sage.libs.gmp.mpq cimport * -cdef inline _Rational_from_mpq(mpq_t e): +cdef inline _Rational_from_mpq(mpq_t e) noexcept: cdef Rational z = Rational.__new__(Rational) mpq_set(z.value, e) return z cdef class Vector_rational_dense(free_module_element.FreeModuleElement): - cdef bint is_dense_c(self): + cdef bint is_dense_c(self) noexcept: return 1 - cdef bint is_sparse_c(self): + cdef bint is_sparse_c(self) noexcept: return 0 def __copy__(self): @@ -162,7 +162,7 @@ cdef class Vector_rational_dense(free_module_element.FreeModuleElement): mpq_clear(self._entries[i]) sig_free(self._entries) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ EXAMPLES:: @@ -192,7 +192,7 @@ cdef class Vector_rational_dense(free_module_element.FreeModuleElement): return rich_to_bool(op, 1) return rich_to_bool(op, 0) - cdef get_unsafe(self, Py_ssize_t i): + cdef get_unsafe(self, Py_ssize_t i) noexcept: """ EXAMPLES:: @@ -253,7 +253,7 @@ cdef class Vector_rational_dense(free_module_element.FreeModuleElement): return (unpickle_v1, (self._parent, self.list(), self._degree, not self._is_immutable)) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: cdef Vector_rational_dense z, r r = right z = self._new_c() @@ -262,7 +262,7 @@ cdef class Vector_rational_dense(free_module_element.FreeModuleElement): mpq_add(z._entries[i], self._entries[i], r._entries[i]) return z - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: cdef Vector_rational_dense z, r r = right z = self._new_c() @@ -271,7 +271,7 @@ cdef class Vector_rational_dense(free_module_element.FreeModuleElement): mpq_sub(z._entries[i], self._entries[i], r._entries[i]) return z - cpdef _dot_product_(self, Vector right): + cpdef _dot_product_(self, Vector right) noexcept: """ Dot product of dense vectors over the rationals. @@ -296,7 +296,7 @@ cdef class Vector_rational_dense(free_module_element.FreeModuleElement): mpq_clear(t) return z - cpdef _pairwise_product_(self, Vector right): + cpdef _pairwise_product_(self, Vector right) noexcept: """ EXAMPLES:: @@ -312,7 +312,7 @@ cdef class Vector_rational_dense(free_module_element.FreeModuleElement): mpq_mul(z._entries[i], self._entries[i], r._entries[i]) return z - cpdef _rmul_(self, Element left): + cpdef _rmul_(self, Element left) noexcept: cdef Vector_rational_dense z cdef Rational a if isinstance(left, Rational): @@ -330,7 +330,7 @@ cdef class Vector_rational_dense(free_module_element.FreeModuleElement): mpq_mul(z._entries[i], self._entries[i], a.value) return z - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: cdef Vector_rational_dense z cdef Rational a if isinstance(right, Rational): @@ -348,7 +348,7 @@ cdef class Vector_rational_dense(free_module_element.FreeModuleElement): mpq_mul(z._entries[i], self._entries[i], a.value) return z - cpdef _neg_(self): + cpdef _neg_(self) noexcept: cdef Vector_rational_dense z z = self._new_c() cdef Py_ssize_t i diff --git a/src/sage/modules/vector_rational_sparse.pxd b/src/sage/modules/vector_rational_sparse.pxd index 0888a8700fe..b738ad18edb 100644 --- a/src/sage/modules/vector_rational_sparse.pxd +++ b/src/sage/modules/vector_rational_sparse.pxd @@ -15,15 +15,15 @@ cdef struct mpq_vector: cdef int reallocate_mpq_vector(mpq_vector* v, Py_ssize_t num_nonzero) except -1 cdef int allocate_mpq_vector(mpq_vector* v, Py_ssize_t num_nonzero) except -1 cdef int mpq_vector_init(mpq_vector* v, Py_ssize_t degree, Py_ssize_t num_nonzero) except -1 -cdef void mpq_vector_clear(mpq_vector* v) -cdef Py_ssize_t mpq_binary_search0(mpq_t* v, Py_ssize_t n, mpq_t x) -cdef Py_ssize_t mpq_binary_search(mpq_t* v, Py_ssize_t n, mpq_t x, Py_ssize_t* ins) +cdef void mpq_vector_clear(mpq_vector* v) noexcept +cdef Py_ssize_t mpq_binary_search0(mpq_t* v, Py_ssize_t n, mpq_t x) noexcept +cdef Py_ssize_t mpq_binary_search(mpq_t* v, Py_ssize_t n, mpq_t x, Py_ssize_t* ins) noexcept cdef int mpq_vector_get_entry(mpq_t ans, mpq_vector* v, Py_ssize_t n) except -1 -cdef bint mpq_vector_is_entry_zero_unsafe(mpq_vector* v, Py_ssize_t n) -cdef object mpq_vector_to_list(mpq_vector* v) +cdef bint mpq_vector_is_entry_zero_unsafe(mpq_vector* v, Py_ssize_t n) noexcept +cdef object mpq_vector_to_list(mpq_vector* v) noexcept cdef int mpq_vector_set_entry(mpq_vector* v, Py_ssize_t n, mpq_t x) except -1 cdef int mpq_vector_set_entry_str(mpq_vector* v, Py_ssize_t n, char *x_str) except -1 cdef int add_mpq_vector_init(mpq_vector* sum, mpq_vector* v, mpq_vector* w, mpq_t multiple) except -1 cdef int mpq_vector_scale(mpq_vector* v, mpq_t scalar) except -1 cdef int mpq_vector_scalar_multiply(mpq_vector* v, mpq_vector* w, mpq_t scalar) except -1 -cdef int mpq_vector_cmp(mpq_vector* v, mpq_vector* w) +cdef int mpq_vector_cmp(mpq_vector* v, mpq_vector* w) noexcept diff --git a/src/sage/modules/vector_rational_sparse.pyx b/src/sage/modules/vector_rational_sparse.pyx index 14d0953b3df..2058d9bef25 100644 --- a/src/sage/modules/vector_rational_sparse.pyx +++ b/src/sage/modules/vector_rational_sparse.pyx @@ -47,7 +47,7 @@ cdef int mpq_vector_init(mpq_vector* v, Py_ssize_t degree, Py_ssize_t num_nonzer v.num_nonzero = num_nonzero v.degree = degree -cdef void mpq_vector_clear(mpq_vector* v): +cdef void mpq_vector_clear(mpq_vector* v) noexcept: cdef Py_ssize_t i if v.entries == NULL: return @@ -61,7 +61,7 @@ cdef void mpq_vector_clear(mpq_vector* v): sig_free(v.entries) sig_free(v.positions) -cdef Py_ssize_t mpq_binary_search0(mpq_t* v, Py_ssize_t n, mpq_t x): +cdef Py_ssize_t mpq_binary_search0(mpq_t* v, Py_ssize_t n, mpq_t x) noexcept: """ Find the position of the rational x in the array v, which has length n. Returns -1 if x is not in the array v. @@ -86,7 +86,7 @@ cdef Py_ssize_t mpq_binary_search0(mpq_t* v, Py_ssize_t n, mpq_t x): return k return -1 -cdef Py_ssize_t mpq_binary_search(mpq_t* v, Py_ssize_t n, mpq_t x, Py_ssize_t* ins): +cdef Py_ssize_t mpq_binary_search(mpq_t* v, Py_ssize_t n, mpq_t x, Py_ssize_t* ins) noexcept: """ Find the position of the integer x in the array v, which has length n. Returns -1 if x is not in the array v, and in this case ins is @@ -149,7 +149,7 @@ cdef int mpq_vector_get_entry(mpq_t ans, mpq_vector* v, Py_ssize_t n) except -1: mpq_set(ans, v.entries[m]) return 0 -cdef bint mpq_vector_is_entry_zero_unsafe(mpq_vector* v, Py_ssize_t n): +cdef bint mpq_vector_is_entry_zero_unsafe(mpq_vector* v, Py_ssize_t n) noexcept: """ Return if the ``n``-th entry of the sparse vector ``v`` is zero. @@ -158,7 +158,7 @@ cdef bint mpq_vector_is_entry_zero_unsafe(mpq_vector* v, Py_ssize_t n): """ return binary_search0(v.positions, v.num_nonzero, n) == -1 -cdef object mpq_vector_to_list(mpq_vector* v): +cdef object mpq_vector_to_list(mpq_vector* v) noexcept: """ Returns a Python list of 2-tuples (i,x), where x=v[i] runs through the nonzero elements of x, in order. @@ -395,7 +395,7 @@ cdef int mpq_vector_scalar_multiply(mpq_vector* v, mpq_vector* w, mpq_t scalar) v.positions[i] = w.positions[i] return 0 -cdef int mpq_vector_cmp(mpq_vector* v, mpq_vector* w): +cdef int mpq_vector_cmp(mpq_vector* v, mpq_vector* w) noexcept: if v.degree < w.degree: return -1 elif v.degree > w.degree: diff --git a/src/sage/modules/with_basis/indexed_element.pxd b/src/sage/modules/with_basis/indexed_element.pxd index ebc785d7ccf..06fec702dcf 100644 --- a/src/sage/modules/with_basis/indexed_element.pxd +++ b/src/sage/modules/with_basis/indexed_element.pxd @@ -5,8 +5,8 @@ cdef class IndexedFreeModuleElement(ModuleElement): cdef long _hash cdef bint _hash_set - cpdef _add_(self, other) - cpdef _sub_(self, other) - cpdef _neg_(self) + cpdef _add_(self, other) noexcept + cpdef _sub_(self, other) noexcept + cpdef _neg_(self) noexcept - cpdef dict monomial_coefficients(self, bint copy=*) + cpdef dict monomial_coefficients(self, bint copy=*) noexcept diff --git a/src/sage/modules/with_basis/indexed_element.pyx b/src/sage/modules/with_basis/indexed_element.pyx index 90f7b8ec580..db2ff9ee4a5 100644 --- a/src/sage/modules/with_basis/indexed_element.pyx +++ b/src/sage/modules/with_basis/indexed_element.pyx @@ -227,7 +227,7 @@ cdef class IndexedFreeModuleElement(ModuleElement): """ return self - cpdef dict monomial_coefficients(self, bint copy=True): + cpdef dict monomial_coefficients(self, bint copy=True) noexcept: """ Return the internal dictionary which has the combinatorial objects indexing the basis as keys and their corresponding coefficients as @@ -540,7 +540,7 @@ cdef class IndexedFreeModuleElement(ModuleElement): repr_monomial = self._parent._latex_term, is_latex=True, strip_one=True) - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ Rich comparison for equal parents. @@ -650,7 +650,7 @@ cdef class IndexedFreeModuleElement(ModuleElement): w = sorted(elt._monomial_coefficients.items()) return richcmp(v, w, op) - cpdef _add_(self, other): + cpdef _add_(self, other) noexcept: """ EXAMPLES:: @@ -673,7 +673,7 @@ cdef class IndexedFreeModuleElement(ModuleElement): add(self._monomial_coefficients, (other)._monomial_coefficients)) - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ EXAMPLES:: @@ -691,7 +691,7 @@ cdef class IndexedFreeModuleElement(ModuleElement): """ return type(self)(self._parent, negate(self._monomial_coefficients)) - cpdef _sub_(self, other): + cpdef _sub_(self, other) noexcept: """ EXAMPLES:: @@ -830,7 +830,7 @@ cdef class IndexedFreeModuleElement(ModuleElement): to_vector = _vector_ - cpdef _acted_upon_(self, scalar, bint self_on_left): + cpdef _acted_upon_(self, scalar, bint self_on_left) noexcept: """ Return the action of ``scalar`` (an element of the base ring) on ``self``. @@ -904,7 +904,7 @@ cdef class IndexedFreeModuleElement(ModuleElement): scal(scalar, self._monomial_coefficients, factor_on_left=not self_on_left)) - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: """ For backward compatibility. @@ -916,7 +916,7 @@ cdef class IndexedFreeModuleElement(ModuleElement): """ return self._acted_upon_(right, True) - cpdef _rmul_(self, Element left): + cpdef _rmul_(self, Element left) noexcept: """ For backward compatibility. diff --git a/src/sage/monoids/free_abelian_monoid_element.pxd b/src/sage/monoids/free_abelian_monoid_element.pxd index 092cd343f05..fe65af79711 100644 --- a/src/sage/monoids/free_abelian_monoid_element.pxd +++ b/src/sage/monoids/free_abelian_monoid_element.pxd @@ -8,7 +8,7 @@ cdef class FreeAbelianMonoidElement(MonoidElement): cdef int _init(self, Py_ssize_t n, Parent parent) except -1 - cdef inline FreeAbelianMonoidElement _new_c(self): + cdef inline FreeAbelianMonoidElement _new_c(self) noexcept: cdef type t = type(self) cdef FreeAbelianMonoidElement x = (t.__new__(t)) x._init(self._n, self._parent) diff --git a/src/sage/monoids/free_abelian_monoid_element.pyx b/src/sage/monoids/free_abelian_monoid_element.pyx index 65df8efe613..66bd3a15ed5 100644 --- a/src/sage/monoids/free_abelian_monoid_element.pyx +++ b/src/sage/monoids/free_abelian_monoid_element.pyx @@ -263,7 +263,7 @@ cdef class FreeAbelianMonoidElement(MonoidElement): s = "1" return s - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Rich comparison. diff --git a/src/sage/numerical/backends/cvxopt_backend.pyx b/src/sage/numerical/backends/cvxopt_backend.pyx index 22bdfd20ea6..4100fb71b76 100644 --- a/src/sage/numerical/backends/cvxopt_backend.pyx +++ b/src/sage/numerical/backends/cvxopt_backend.pyx @@ -92,7 +92,7 @@ cdef class CVXOPTBackend(GenericBackend): else: self.set_sense(-1) - cpdef __copy__(self): + cpdef __copy__(self) noexcept: # Added a second inequality to this doctest, # because otherwise CVXOPT complains: ValueError: Rank(A) < p or Rank([G; A]) < n """ @@ -204,7 +204,7 @@ cdef class CVXOPTBackend(GenericBackend): self.col_name_var.append(name) return len(self.objective_function) - 1 - cpdef set_variable_type(self, int variable, int vtype): + cpdef set_variable_type(self, int variable, int vtype) noexcept: """ Set the type of a variable. @@ -223,7 +223,7 @@ cdef class CVXOPTBackend(GenericBackend): if vtype != -1: raise ValueError('This backend does not handle integer variables ! Read the doc !') - cpdef set_sense(self, int sense): + cpdef set_sense(self, int sense) noexcept: """ Set the direction (maximization/minimization). @@ -249,7 +249,7 @@ cdef class CVXOPTBackend(GenericBackend): else: self.is_maximize = 0 - cpdef objective_coefficient(self, int variable, coeff=None): + cpdef objective_coefficient(self, int variable, coeff=None) noexcept: """ Set or get the coefficient of a variable in the objective function @@ -277,7 +277,7 @@ cdef class CVXOPTBackend(GenericBackend): else: return self.objective_function[variable] - cpdef set_objective(self, list coeff, d = 0.0): + cpdef set_objective(self, list coeff, d = 0.0) noexcept: """ Set the objective function. @@ -302,13 +302,13 @@ cdef class CVXOPTBackend(GenericBackend): self.objective_function[i] = coeff[i] obj_constant_term = d - cpdef set_verbosity(self, int level): + cpdef set_verbosity(self, int level) noexcept: """ Does not apply for the cvxopt solver """ pass - cpdef add_col(self, indices, coeffs): + cpdef add_col(self, indices, coeffs) noexcept: """ Add a column. @@ -356,7 +356,7 @@ cdef class CVXOPTBackend(GenericBackend): self.objective_function.append(0) self.col_name_var.append(None) - cpdef add_linear_constraint(self, coefficients, lower_bound, upper_bound, name=None): + cpdef add_linear_constraint(self, coefficients, lower_bound, upper_bound, name=None) noexcept: """ Add a linear constraint. @@ -554,7 +554,7 @@ cdef class CVXOPTBackend(GenericBackend): return 0 - cpdef get_objective_value(self): + cpdef get_objective_value(self) noexcept: """ Return the value of the objective function. @@ -586,7 +586,7 @@ cdef class CVXOPTBackend(GenericBackend): i+=1 return sum - cpdef get_variable_value(self, int variable): + cpdef get_variable_value(self, int variable) noexcept: """ Return the value of a variable given by the solver. @@ -613,7 +613,7 @@ cdef class CVXOPTBackend(GenericBackend): """ return self.answer['x'][variable] - cpdef int ncols(self): + cpdef int ncols(self) noexcept: """ Return the number of columns/variables. @@ -631,7 +631,7 @@ cdef class CVXOPTBackend(GenericBackend): return len(self.objective_function) - cpdef int nrows(self): + cpdef int nrows(self) noexcept: """ Return the number of rows/constraints. @@ -650,7 +650,7 @@ cdef class CVXOPTBackend(GenericBackend): return len(self.row_upper_bound) - cpdef bint is_maximization(self): + cpdef bint is_maximization(self) noexcept: """ Test whether the problem is a maximization @@ -669,7 +669,7 @@ cdef class CVXOPTBackend(GenericBackend): else: return 0 - cpdef problem_name(self, name=None): + cpdef problem_name(self, name=None) noexcept: """ Return or define the problem's name @@ -693,7 +693,7 @@ cdef class CVXOPTBackend(GenericBackend): self.prob_name = name - cpdef row(self, int i): + cpdef row(self, int i) noexcept: """ Return a row @@ -731,7 +731,7 @@ cdef class CVXOPTBackend(GenericBackend): return (idx, coeff) - cpdef row_bounds(self, int index): + cpdef row_bounds(self, int index) noexcept: """ Return the bounds of a specific constraint. @@ -759,7 +759,7 @@ cdef class CVXOPTBackend(GenericBackend): """ return (self.row_lower_bound[index], self.row_upper_bound[index]) - cpdef col_bounds(self, int index): + cpdef col_bounds(self, int index) noexcept: """ Return the bounds of a specific variable. @@ -787,7 +787,7 @@ cdef class CVXOPTBackend(GenericBackend): """ return (self.col_lower_bound[index], self.col_upper_bound[index]) - cpdef bint is_variable_binary(self, int index): + cpdef bint is_variable_binary(self, int index) noexcept: """ Test whether the given variable is of binary type. CVXOPT does not allow integer variables, so this is a bit moot. @@ -814,7 +814,7 @@ cdef class CVXOPTBackend(GenericBackend): """ return False - cpdef bint is_variable_integer(self, int index): + cpdef bint is_variable_integer(self, int index) noexcept: """ Test whether the given variable is of integer type. CVXOPT does not allow integer variables, so this is a bit moot. @@ -841,7 +841,7 @@ cdef class CVXOPTBackend(GenericBackend): """ return False - cpdef bint is_variable_continuous(self, int index): + cpdef bint is_variable_continuous(self, int index) noexcept: """ Test whether the given variable is of continuous/real type. CVXOPT does not allow integer variables, so this is a bit moot. @@ -870,7 +870,7 @@ cdef class CVXOPTBackend(GenericBackend): """ return True - cpdef row_name(self, int index): + cpdef row_name(self, int index) noexcept: """ Return the ``index`` th row name @@ -890,7 +890,7 @@ cdef class CVXOPTBackend(GenericBackend): return self.row_name_var[index] return "constraint_" + repr(index) - cpdef col_name(self, int index): + cpdef col_name(self, int index) noexcept: """ Return the ``index`` th col name @@ -914,7 +914,7 @@ cdef class CVXOPTBackend(GenericBackend): return self.col_name_var[index] return "x_" + repr(index) - cpdef variable_upper_bound(self, int index, value = False): + cpdef variable_upper_bound(self, int index, value = False) noexcept: """ Return or define the upper bound on a variable @@ -943,7 +943,7 @@ cdef class CVXOPTBackend(GenericBackend): else: return self.col_upper_bound[index] - cpdef variable_lower_bound(self, int index, value = False): + cpdef variable_lower_bound(self, int index, value = False) noexcept: """ Return or define the lower bound on a variable @@ -972,7 +972,7 @@ cdef class CVXOPTBackend(GenericBackend): else: return self.col_lower_bound[index] - cpdef solver_parameter(self, name, value = None): + cpdef solver_parameter(self, name, value = None) noexcept: """ Return or define a solver parameter diff --git a/src/sage/numerical/backends/cvxopt_sdp_backend.pyx b/src/sage/numerical/backends/cvxopt_sdp_backend.pyx index bb999559ee2..aefa91439bf 100644 --- a/src/sage/numerical/backends/cvxopt_sdp_backend.pyx +++ b/src/sage/numerical/backends/cvxopt_sdp_backend.pyx @@ -161,7 +161,7 @@ cdef class CVXOPTSDPBackend(MatrixSDPBackend): return 0 - cpdef get_objective_value(self): + cpdef get_objective_value(self) noexcept: """ Return the value of the objective function. @@ -196,7 +196,7 @@ cdef class CVXOPTSDPBackend(MatrixSDPBackend): i+=1 return sum - cpdef _get_answer(self): + cpdef _get_answer(self) noexcept: """ return the complete output dict of the solver @@ -222,7 +222,7 @@ cdef class CVXOPTSDPBackend(MatrixSDPBackend): """ return self.answer - cpdef get_variable_value(self, int variable): + cpdef get_variable_value(self, int variable) noexcept: """ Return the value of a variable given by the solver. @@ -256,7 +256,7 @@ cdef class CVXOPTSDPBackend(MatrixSDPBackend): """ return self.answer['x'][variable] - cpdef dual_variable(self, int i, sparse=False): + cpdef dual_variable(self, int i, sparse=False) noexcept: """ The `i`-th dual variable @@ -306,7 +306,7 @@ cdef class CVXOPTSDPBackend(MatrixSDPBackend): assert(n == self.answer['zs'][i].size[1]) # must be square matrix return Matrix(n, n, list(self.answer['zs'][i]), sparse=sparse) - cpdef slack(self, int i, sparse=False): + cpdef slack(self, int i, sparse=False) noexcept: """ Slack of the `i`-th constraint @@ -358,7 +358,7 @@ cdef class CVXOPTSDPBackend(MatrixSDPBackend): return Matrix(n, n, list(self.answer['ss'][i]), sparse=sparse) - cpdef solver_parameter(self, name, value = None): + cpdef solver_parameter(self, name, value = None) noexcept: """ Return or define a solver parameter diff --git a/src/sage/numerical/backends/cvxpy_backend.pxd b/src/sage/numerical/backends/cvxpy_backend.pxd index ed4d63ccc63..96dd9c33390 100644 --- a/src/sage/numerical/backends/cvxpy_backend.pxd +++ b/src/sage/numerical/backends/cvxpy_backend.pxd @@ -37,4 +37,4 @@ cdef class CVXPYBackend(GenericBackend): coefficients=*) \ except -1 - cpdef cvxpy_problem(self) + cpdef cvxpy_problem(self) noexcept diff --git a/src/sage/numerical/backends/cvxpy_backend.pyx b/src/sage/numerical/backends/cvxpy_backend.pyx index 4ffae61809a..7cf5ccc8fb6 100644 --- a/src/sage/numerical/backends/cvxpy_backend.pyx +++ b/src/sage/numerical/backends/cvxpy_backend.pyx @@ -142,7 +142,7 @@ cdef class CVXPYBackend: objective = cvxpy.Minimize(0) self.problem = cvxpy.Problem(objective, ()) - cpdef __copy__(self): + cpdef __copy__(self) noexcept: """ Returns a copy of self. @@ -172,7 +172,7 @@ cdef class CVXPYBackend: cp.obj_constant_term = self.obj_constant_term return cp - cpdef cvxpy_problem(self): + cpdef cvxpy_problem(self) noexcept: return self.problem def cvxpy_variables(self): @@ -284,7 +284,7 @@ cdef class CVXPYBackend: return index - cpdef set_verbosity(self, int level): + cpdef set_verbosity(self, int level) noexcept: """ Set the log (verbosity) level @@ -302,7 +302,7 @@ cdef class CVXPYBackend: """ pass - cpdef add_linear_constraint(self, coefficients, lower_bound, upper_bound, name=None): + cpdef add_linear_constraint(self, coefficients, lower_bound, upper_bound, name=None) noexcept: """ Add a linear constraint. @@ -361,7 +361,7 @@ cdef class CVXPYBackend: self.constraint_names.append(name) self.problem = cvxpy.Problem(self.problem.objective, constraints) - cpdef add_col(self, indices, coeffs): + cpdef add_col(self, indices, coeffs) noexcept: """ Add a column. @@ -408,7 +408,7 @@ cdef class CVXPYBackend: #self.objective_coefficients.append(0) goes to "self.add_variable" self.add_variable(coefficients=zip(indices, coeffs)) - cpdef set_objective(self, list coeff, d=0.0): + cpdef set_objective(self, list coeff, d=0.0) noexcept: """ Set the objective function. @@ -440,7 +440,7 @@ cdef class CVXPYBackend: self.problem = cvxpy.Problem(objective, constraints) self.obj_constant_term = d - cpdef set_sense(self, int sense): + cpdef set_sense(self, int sense) noexcept: """ Set the direction (maximization/minimization). @@ -468,7 +468,7 @@ cdef class CVXPYBackend: objective = cvxpy.Minimize(expr) self.problem = cvxpy.Problem(objective, self.problem.constraints) - cpdef objective_coefficient(self, int variable, coeff=None): + cpdef objective_coefficient(self, int variable, coeff=None) noexcept: """ Set or get the coefficient of a variable in the objective function @@ -543,7 +543,7 @@ cdef class CVXPYBackend: raise MIPSolverException(f"cvxpy.Problem.solve: Problem is unbounded") raise MIPSolverException(f"cvxpy.Problem.solve reported an unknown problem status: {status}") - cpdef get_objective_value(self): + cpdef get_objective_value(self) noexcept: """ Return the value of the objective function. @@ -570,7 +570,7 @@ cdef class CVXPYBackend: """ return self.problem.value + self.obj_constant_term - cpdef get_variable_value(self, int variable): + cpdef get_variable_value(self, int variable) noexcept: """ Return the value of a variable given by the solver. @@ -597,7 +597,7 @@ cdef class CVXPYBackend: """ return float(self.variables[variable].value) - cpdef int ncols(self): + cpdef int ncols(self) noexcept: """ Return the number of columns/variables. @@ -614,7 +614,7 @@ cdef class CVXPYBackend: """ return len(self.variables) - cpdef int nrows(self): + cpdef int nrows(self) noexcept: """ Return the number of rows/constraints. @@ -630,7 +630,7 @@ cdef class CVXPYBackend: """ return len(self.problem.constraints) - cpdef bint is_maximization(self): + cpdef bint is_maximization(self) noexcept: """ Test whether the problem is a maximization @@ -646,7 +646,7 @@ cdef class CVXPYBackend: """ return isinstance(self.problem.objective, cvxpy.Maximize) - cpdef problem_name(self, name=None): + cpdef problem_name(self, name=None) noexcept: """ Return or define the problem's name @@ -671,7 +671,7 @@ cdef class CVXPYBackend: else: self.prob_name = str(name) - cpdef row(self, int i): + cpdef row(self, int i) noexcept: """ Return a row @@ -707,7 +707,7 @@ cdef class CVXPYBackend: coef.append(self.Matrix[i][j]) return (idx, coef) - cpdef row_bounds(self, int index): + cpdef row_bounds(self, int index) noexcept: """ Return the bounds of a specific constraint. @@ -736,7 +736,7 @@ cdef class CVXPYBackend: """ return (self.row_lower_bound[index], self.row_upper_bound[index]) - cpdef col_bounds(self, int index): + cpdef col_bounds(self, int index) noexcept: """ Return the bounds of a specific variable. @@ -764,7 +764,7 @@ cdef class CVXPYBackend: """ return (self.col_lower_bound[index], self.col_upper_bound[index]) - cpdef bint is_variable_binary(self, int index): + cpdef bint is_variable_binary(self, int index) noexcept: """ Test whether the given variable is of binary type. @@ -785,7 +785,7 @@ cdef class CVXPYBackend: """ return bool(self.variables[index].boolean_idx) - cpdef bint is_variable_integer(self, int index): + cpdef bint is_variable_integer(self, int index) noexcept: """ Test whether the given variable is of integer type. @@ -806,7 +806,7 @@ cdef class CVXPYBackend: """ return bool(self.variables[index].integer_idx) - cpdef bint is_variable_continuous(self, int index): + cpdef bint is_variable_continuous(self, int index) noexcept: """ Test whether the given variable is of continuous/real type. @@ -827,7 +827,7 @@ cdef class CVXPYBackend: """ return not self.is_variable_binary(index) and not self.is_variable_integer(index) - cpdef row_name(self, int index): + cpdef row_name(self, int index) noexcept: """ Return the ``index`` th row name @@ -845,7 +845,7 @@ cdef class CVXPYBackend: """ return self.constraint_names[index] or ("constraint_" + repr(index)) - cpdef col_name(self, int index): + cpdef col_name(self, int index) noexcept: """ Return the ``index`` th col name @@ -867,7 +867,7 @@ cdef class CVXPYBackend: """ return self.variables[index].name() - cpdef variable_upper_bound(self, int index, value = False): + cpdef variable_upper_bound(self, int index, value = False) noexcept: """ Return or define the upper bound on a variable @@ -899,7 +899,7 @@ cdef class CVXPYBackend: else: return self.col_upper_bound[index] - cpdef variable_lower_bound(self, int index, value = False): + cpdef variable_lower_bound(self, int index, value = False) noexcept: """ Return or define the lower bound on a variable diff --git a/src/sage/numerical/backends/generic_backend.pxd b/src/sage/numerical/backends/generic_backend.pxd index 2d031424d1e..60983afc6f2 100644 --- a/src/sage/numerical/backends/generic_backend.pxd +++ b/src/sage/numerical/backends/generic_backend.pxd @@ -12,49 +12,49 @@ from sage.structure.sage_object cimport SageObject cdef class GenericBackend (SageObject): cpdef int add_variable(self, lower_bound=*, upper_bound=*, binary=*, continuous=*, integer=*, obj=*, name=*) except -1 cpdef int add_variables(self, int, lower_bound=*, upper_bound=*, binary=*, continuous=*, integer=*, obj=*, names=*) except -1 - cpdef set_variable_type(self, int variable, int vtype) - cpdef set_sense(self, int sense) - cpdef objective_coefficient(self, int variable, coeff=*) - cpdef objective_constant_term(self, d=*) - cpdef set_objective(self, list coeff, d=*) - cpdef set_verbosity(self, int level) - cpdef add_linear_constraint(self, coefficients, lower_bound, upper_bound, name=*) - cpdef add_linear_constraint_vector(self, degree, coefficients, lower_bound, upper_bound, name=*) - cpdef remove_constraint(self, int) - cpdef remove_constraints(self, constraints) - cpdef add_col(self, indices, coeffs) - cpdef add_linear_constraints(self, int number, lower_bound, upper_bound, names=*) + cpdef set_variable_type(self, int variable, int vtype) noexcept + cpdef set_sense(self, int sense) noexcept + cpdef objective_coefficient(self, int variable, coeff=*) noexcept + cpdef objective_constant_term(self, d=*) noexcept + cpdef set_objective(self, list coeff, d=*) noexcept + cpdef set_verbosity(self, int level) noexcept + cpdef add_linear_constraint(self, coefficients, lower_bound, upper_bound, name=*) noexcept + cpdef add_linear_constraint_vector(self, degree, coefficients, lower_bound, upper_bound, name=*) noexcept + cpdef remove_constraint(self, int) noexcept + cpdef remove_constraints(self, constraints) noexcept + cpdef add_col(self, indices, coeffs) noexcept + cpdef add_linear_constraints(self, int number, lower_bound, upper_bound, names=*) noexcept cpdef int solve(self) except -1 - cpdef get_objective_value(self) - cpdef best_known_objective_bound(self) - cpdef get_relative_objective_gap(self) - cpdef get_variable_value(self, int variable) - cpdef bint is_maximization(self) - cpdef write_lp(self, name) - cpdef write_mps(self, name, int modern) - cpdef row(self, int i) - cpdef int ncols(self) - cpdef int nrows(self) - cpdef bint is_variable_binary(self, int) - cpdef bint is_variable_integer(self, int) - cpdef bint is_variable_continuous(self, int) - cpdef problem_name(self, name = *) - cpdef row_bounds(self, int index) - cpdef col_bounds(self, int index) - cpdef row_name(self, int index) - cpdef col_name(self, int index) - cpdef variable_upper_bound(self, int index, value = *) - cpdef variable_lower_bound(self, int index, value = *) - cpdef solver_parameter(self, name, value=*) - cpdef zero(self) - cpdef base_ring(self) - cpdef __copy__(self) - cpdef copy(self) - cpdef bint is_variable_basic(self, int index) - cpdef bint is_variable_nonbasic_at_lower_bound(self, int index) - cpdef bint is_slack_variable_basic(self, int index) - cpdef bint is_slack_variable_nonbasic_at_lower_bound(self, int index) + cpdef get_objective_value(self) noexcept + cpdef best_known_objective_bound(self) noexcept + cpdef get_relative_objective_gap(self) noexcept + cpdef get_variable_value(self, int variable) noexcept + cpdef bint is_maximization(self) noexcept + cpdef write_lp(self, name) noexcept + cpdef write_mps(self, name, int modern) noexcept + cpdef row(self, int i) noexcept + cpdef int ncols(self) noexcept + cpdef int nrows(self) noexcept + cpdef bint is_variable_binary(self, int) noexcept + cpdef bint is_variable_integer(self, int) noexcept + cpdef bint is_variable_continuous(self, int) noexcept + cpdef problem_name(self, name = *) noexcept + cpdef row_bounds(self, int index) noexcept + cpdef col_bounds(self, int index) noexcept + cpdef row_name(self, int index) noexcept + cpdef col_name(self, int index) noexcept + cpdef variable_upper_bound(self, int index, value = *) noexcept + cpdef variable_lower_bound(self, int index, value = *) noexcept + cpdef solver_parameter(self, name, value=*) noexcept + cpdef zero(self) noexcept + cpdef base_ring(self) noexcept + cpdef __copy__(self) noexcept + cpdef copy(self) noexcept + cpdef bint is_variable_basic(self, int index) noexcept + cpdef bint is_variable_nonbasic_at_lower_bound(self, int index) noexcept + cpdef bint is_slack_variable_basic(self, int index) noexcept + cpdef bint is_slack_variable_nonbasic_at_lower_bound(self, int index) noexcept cdef object obj_constant_term -cpdef GenericBackend get_solver(constraint_generation = ?, solver = ?, base_ring = ?) +cpdef GenericBackend get_solver(constraint_generation = ?, solver = ?, base_ring = ?) noexcept diff --git a/src/sage/numerical/backends/generic_backend.pyx b/src/sage/numerical/backends/generic_backend.pyx index 74cc99cb9e5..6d43a6ba958 100644 --- a/src/sage/numerical/backends/generic_backend.pyx +++ b/src/sage/numerical/backends/generic_backend.pyx @@ -33,11 +33,11 @@ from copy import copy cdef class GenericBackend: - cpdef base_ring(self): + cpdef base_ring(self) noexcept: from sage.rings.real_double import RDF return RDF - cpdef zero(self): + cpdef zero(self) noexcept: return self.base_ring()(0) cpdef int add_variable(self, lower_bound=0, upper_bound=None, @@ -207,7 +207,7 @@ cdef class GenericBackend: tester.assertEqual(p.col_name(ncols_before), 'a') tester.assertAlmostEqual(p.objective_coefficient(ncols_before), 42.0) - cpdef set_variable_type(self, int variable, int vtype): + cpdef set_variable_type(self, int variable, int vtype) noexcept: """ Set the type of a variable @@ -235,7 +235,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef set_sense(self, int sense): + cpdef set_sense(self, int sense) noexcept: """ Set the direction (maximization/minimization). @@ -280,7 +280,7 @@ cdef class GenericBackend: tester.assertIsNone(p.set_sense(1)) tester.assertEqual(p.is_maximization(), True) - cpdef objective_coefficient(self, int variable, coeff=None): + cpdef objective_coefficient(self, int variable, coeff=None) noexcept: """ Set or get the coefficient of a variable in the objective function @@ -305,7 +305,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef objective_constant_term(self, d=None): + cpdef objective_constant_term(self, d=None) noexcept: """ Set or get the constant term in the objective function @@ -328,7 +328,7 @@ cdef class GenericBackend: else: self.obj_constant_term = d - cpdef set_objective(self, list coeff, d = 0.0): + cpdef set_objective(self, list coeff, d = 0.0) noexcept: """ Set the objective function. @@ -362,7 +362,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef set_verbosity(self, int level): + cpdef set_verbosity(self, int level) noexcept: """ Set the log (verbosity) level @@ -378,7 +378,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef remove_constraint(self, int i): + cpdef remove_constraint(self, int i) noexcept: r""" Remove a constraint. @@ -405,7 +405,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef remove_constraints(self, constraints): + cpdef remove_constraints(self, constraints) noexcept: r""" Remove several constraints. @@ -432,7 +432,7 @@ cdef class GenericBackend: self.remove_constraint(c) last = c - cpdef add_linear_constraint(self, coefficients, lower_bound, upper_bound, name=None): + cpdef add_linear_constraint(self, coefficients, lower_bound, upper_bound, name=None) noexcept: """ Add a linear constraint. @@ -467,7 +467,7 @@ cdef class GenericBackend: """ raise NotImplementedError('add_linear_constraint') - cpdef add_linear_constraint_vector(self, degree, coefficients, lower_bound, upper_bound, name=None): + cpdef add_linear_constraint_vector(self, degree, coefficients, lower_bound, upper_bound, name=None) noexcept: """ Add a vector-valued linear constraint. @@ -546,7 +546,7 @@ cdef class GenericBackend: p.add_linear_constraint_vector(2, coeffs, lower, upper, 'foo') # FIXME: Tests here. Careful what we expect regarding ranged constraints with some solvers. - cpdef add_col(self, indices, coeffs): + cpdef add_col(self, indices, coeffs) noexcept: """ Add a column. @@ -606,7 +606,7 @@ cdef class GenericBackend: for 1 <= i <= 4: tester.assertEqual(p.row(i), ([0], [i])) - cpdef add_linear_constraints(self, int number, lower_bound, upper_bound, names=None): + cpdef add_linear_constraints(self, int number, lower_bound, upper_bound, names=None) noexcept: """ Add ``'number`` linear constraints. @@ -729,7 +729,7 @@ cdef class GenericBackend: with tester.assertRaises(MIPSolverException) as cm: # unbounded p.solve() - cpdef get_objective_value(self): + cpdef get_objective_value(self) noexcept: """ Return the value of the objective function. @@ -757,7 +757,7 @@ cdef class GenericBackend: raise NotImplementedError() - cpdef best_known_objective_bound(self): + cpdef best_known_objective_bound(self) noexcept: r""" Return the value of the currently best known bound. @@ -790,7 +790,7 @@ cdef class GenericBackend: raise NotImplementedError() - cpdef get_relative_objective_gap(self): + cpdef get_relative_objective_gap(self) noexcept: r""" Return the relative objective gap of the best known solution. @@ -825,7 +825,7 @@ cdef class GenericBackend: raise NotImplementedError() - cpdef get_variable_value(self, int variable): + cpdef get_variable_value(self, int variable) noexcept: """ Return the value of a variable given by the solver. @@ -853,7 +853,7 @@ cdef class GenericBackend: raise NotImplementedError() - cpdef int ncols(self): + cpdef int ncols(self) noexcept: """ Return the number of columns/variables. @@ -879,7 +879,7 @@ cdef class GenericBackend: p = self tester.assertGreaterEqual(self.ncols(), 0) - cpdef int nrows(self): + cpdef int nrows(self) noexcept: """ Return the number of rows/constraints. @@ -896,7 +896,7 @@ cdef class GenericBackend: raise NotImplementedError() - cpdef bint is_maximization(self): + cpdef bint is_maximization(self) noexcept: """ Test whether the problem is a maximization @@ -912,7 +912,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef problem_name(self, name=None): + cpdef problem_name(self, name=None) noexcept: """ Return or define the problem's name @@ -932,7 +932,7 @@ cdef class GenericBackend: raise NotImplementedError() - cpdef write_lp(self, name): + cpdef write_lp(self, name) noexcept: """ Write the problem to a ``.lp`` file @@ -954,7 +954,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef write_mps(self, name, int modern): + cpdef write_mps(self, name, int modern) noexcept: """ Write the problem to a ``.mps`` file @@ -977,7 +977,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef copy(self): + cpdef copy(self) noexcept: """ Returns a copy of self. @@ -994,7 +994,7 @@ cdef class GenericBackend: return self.__copy__() # Override this method in backends. - cpdef __copy__(self): + cpdef __copy__(self) noexcept: """ Returns a copy of self. @@ -1032,7 +1032,7 @@ cdef class GenericBackend: """ return self.__copy__() - cpdef row(self, int i): + cpdef row(self, int i) noexcept: """ Return a row @@ -1061,7 +1061,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef row_bounds(self, int index): + cpdef row_bounds(self, int index) noexcept: """ Return the bounds of a specific constraint. @@ -1089,7 +1089,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef col_bounds(self, int index): + cpdef col_bounds(self, int index) noexcept: """ Return the bounds of a specific variable. @@ -1117,7 +1117,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef bint is_variable_binary(self, int index): + cpdef bint is_variable_binary(self, int index) noexcept: """ Test whether the given variable is of binary type. @@ -1140,7 +1140,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef bint is_variable_integer(self, int index): + cpdef bint is_variable_integer(self, int index) noexcept: """ Test whether the given variable is of integer type. @@ -1162,7 +1162,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef bint is_variable_continuous(self, int index): + cpdef bint is_variable_continuous(self, int index) noexcept: """ Test whether the given variable is of continuous/real type. @@ -1187,7 +1187,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef row_name(self, int index): + cpdef row_name(self, int index) noexcept: """ Return the ``index`` th row name @@ -1206,7 +1206,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef col_name(self, int index): + cpdef col_name(self, int index) noexcept: """ Return the ``index``-th column name @@ -1309,7 +1309,7 @@ cdef class GenericBackend: p._test_copy(**options) p._test_copy_does_not_share_data(**options) - cpdef variable_upper_bound(self, int index, value = False): + cpdef variable_upper_bound(self, int index, value = False) noexcept: """ Return or define the upper bound on a variable @@ -1335,7 +1335,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef variable_lower_bound(self, int index, value = False): + cpdef variable_lower_bound(self, int index, value = False) noexcept: """ Return or define the lower bound on a variable @@ -1361,7 +1361,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef solver_parameter(self, name, value = None): + cpdef solver_parameter(self, name, value = None) noexcept: """ Return or define a solver parameter @@ -1387,7 +1387,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef bint is_variable_basic(self, int index): + cpdef bint is_variable_basic(self, int index) noexcept: """ Test whether the given variable is basic. @@ -1417,7 +1417,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef bint is_variable_nonbasic_at_lower_bound(self, int index): + cpdef bint is_variable_nonbasic_at_lower_bound(self, int index) noexcept: """ Test whether the given variable is nonbasic at lower bound. @@ -1447,7 +1447,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef bint is_slack_variable_basic(self, int index): + cpdef bint is_slack_variable_basic(self, int index) noexcept: """ Test whether the slack variable of the given row is basic. @@ -1477,7 +1477,7 @@ cdef class GenericBackend: """ raise NotImplementedError() - cpdef bint is_slack_variable_nonbasic_at_lower_bound(self, int index): + cpdef bint is_slack_variable_nonbasic_at_lower_bound(self, int index) noexcept: """ Test whether the given variable is nonbasic at lower bound. @@ -1677,7 +1677,7 @@ def default_mip_solver(solver=None): else: raise ValueError("'solver' should be set to 'GLPK', 'Coin', 'CPLEX', 'CVXOPT', 'CVXPY', 'Gurobi', 'PPL', 'SCIP', 'InteractiveLP', a callable, or None.") -cpdef GenericBackend get_solver(constraint_generation = False, solver = None, base_ring = None): +cpdef GenericBackend get_solver(constraint_generation = False, solver = None, base_ring = None) noexcept: """ Return a solver according to the given preferences diff --git a/src/sage/numerical/backends/generic_sdp_backend.pxd b/src/sage/numerical/backends/generic_sdp_backend.pxd index 68039c672fd..446b9ce8c25 100644 --- a/src/sage/numerical/backends/generic_sdp_backend.pxd +++ b/src/sage/numerical/backends/generic_sdp_backend.pxd @@ -10,28 +10,28 @@ cdef class GenericSDPBackend: cpdef int add_variable(self, obj=*, name=*) except -1 cpdef int add_variables(self, int, names=*) except -1 - cpdef set_sense(self, int sense) - cpdef objective_coefficient(self, int variable, coeff=*) - cpdef set_objective(self, list coeff, d=*) - cpdef add_linear_constraint(self, constraints, name=*) - cpdef add_linear_constraints(self, int number, names=*) + cpdef set_sense(self, int sense) noexcept + cpdef objective_coefficient(self, int variable, coeff=*) noexcept + cpdef set_objective(self, list coeff, d=*) noexcept + cpdef add_linear_constraint(self, constraints, name=*) noexcept + cpdef add_linear_constraints(self, int number, names=*) noexcept cpdef int solve(self) except -1 - cpdef get_objective_value(self) - cpdef get_variable_value(self, int variable) - cpdef dual_variable(self, int variable, sparse=*) - cpdef slack(self, int variable, sparse=*) - cpdef bint is_maximization(self) - cpdef row(self, int i) - cpdef int ncols(self) - cpdef int nrows(self) - cpdef problem_name(self, name=*) - cpdef row_name(self, int index) - cpdef col_name(self, int index) - cpdef solver_parameter(self, name, value=*) - cpdef zero(self) - cpdef base_ring(self) + cpdef get_objective_value(self) noexcept + cpdef get_variable_value(self, int variable) noexcept + cpdef dual_variable(self, int variable, sparse=*) noexcept + cpdef slack(self, int variable, sparse=*) noexcept + cpdef bint is_maximization(self) noexcept + cpdef row(self, int i) noexcept + cpdef int ncols(self) noexcept + cpdef int nrows(self) noexcept + cpdef problem_name(self, name=*) noexcept + cpdef row_name(self, int index) noexcept + cpdef col_name(self, int index) noexcept + cpdef solver_parameter(self, name, value=*) noexcept + cpdef zero(self) noexcept + cpdef base_ring(self) noexcept cdef obj_constant_term cdef dict matrices_dim -cpdef GenericSDPBackend get_solver(solver=?, base_ring=?) +cpdef GenericSDPBackend get_solver(solver=?, base_ring=?) noexcept diff --git a/src/sage/numerical/backends/generic_sdp_backend.pyx b/src/sage/numerical/backends/generic_sdp_backend.pyx index 45a56b3b6e3..bad0e3511e2 100644 --- a/src/sage/numerical/backends/generic_sdp_backend.pyx +++ b/src/sage/numerical/backends/generic_sdp_backend.pyx @@ -29,7 +29,7 @@ AUTHORS: cdef class GenericSDPBackend: - cpdef base_ring(self): + cpdef base_ring(self) noexcept: """ The base ring @@ -42,7 +42,7 @@ cdef class GenericSDPBackend: from sage.rings.real_double import RDF return RDF - cpdef zero(self): + cpdef zero(self) noexcept: """ Zero of the base ring @@ -120,7 +120,7 @@ cdef class GenericSDPBackend: """ raise NotImplementedError() - cpdef set_sense(self, int sense): + cpdef set_sense(self, int sense) noexcept: """ Set the direction (maximization/minimization). @@ -143,7 +143,7 @@ cdef class GenericSDPBackend: """ raise NotImplementedError() - cpdef objective_coefficient(self, int variable, coeff=None): + cpdef objective_coefficient(self, int variable, coeff=None) noexcept: """ Set or get the coefficient of a variable in the objective function @@ -168,7 +168,7 @@ cdef class GenericSDPBackend: """ raise NotImplementedError() - cpdef set_objective(self, list coeff, d=0.0): + cpdef set_objective(self, list coeff, d=0.0) noexcept: """ Set the objective function. @@ -194,7 +194,7 @@ cdef class GenericSDPBackend: raise NotImplementedError() - cpdef add_linear_constraint(self, coefficients, name=None): + cpdef add_linear_constraint(self, coefficients, name=None) noexcept: """ Add a linear constraint. @@ -228,7 +228,7 @@ cdef class GenericSDPBackend: raise NotImplementedError() - cpdef add_linear_constraints(self, int number, names=None): + cpdef add_linear_constraints(self, int number, names=None) noexcept: """ Add constraints. @@ -282,7 +282,7 @@ cdef class GenericSDPBackend: """ raise NotImplementedError() - cpdef get_objective_value(self): + cpdef get_objective_value(self) noexcept: """ Return the value of the objective function. @@ -310,7 +310,7 @@ cdef class GenericSDPBackend: raise NotImplementedError() - cpdef get_variable_value(self, int variable): + cpdef get_variable_value(self, int variable) noexcept: """ Return the value of a variable given by the solver. @@ -338,7 +338,7 @@ cdef class GenericSDPBackend: raise NotImplementedError() - cpdef int ncols(self): + cpdef int ncols(self) noexcept: """ Return the number of columns/variables. @@ -356,7 +356,7 @@ cdef class GenericSDPBackend: raise NotImplementedError() - cpdef int nrows(self): + cpdef int nrows(self) noexcept: """ Return the number of rows/constraints. @@ -373,7 +373,7 @@ cdef class GenericSDPBackend: raise NotImplementedError() - cpdef bint is_maximization(self): + cpdef bint is_maximization(self) noexcept: """ Test whether the problem is a maximization @@ -389,7 +389,7 @@ cdef class GenericSDPBackend: """ raise NotImplementedError() - cpdef problem_name(self, name=None): + cpdef problem_name(self, name=None) noexcept: """ Return or define the problem's name @@ -409,7 +409,7 @@ cdef class GenericSDPBackend: raise NotImplementedError() - cpdef row(self, int i): + cpdef row(self, int i) noexcept: """ Return a row @@ -440,7 +440,7 @@ cdef class GenericSDPBackend: - cpdef row_name(self, int index): + cpdef row_name(self, int index) noexcept: """ Return the ``index`` th row name @@ -459,7 +459,7 @@ cdef class GenericSDPBackend: """ raise NotImplementedError() - cpdef col_name(self, int index): + cpdef col_name(self, int index) noexcept: """ Return the ``index`` th col name @@ -481,7 +481,7 @@ cdef class GenericSDPBackend: """ raise NotImplementedError() - cpdef dual_variable(self, int i, sparse=False): + cpdef dual_variable(self, int i, sparse=False) noexcept: """ The `i`-th dual variable @@ -527,7 +527,7 @@ cdef class GenericSDPBackend: """ raise NotImplementedError() - cpdef slack(self, int i, sparse=False): + cpdef slack(self, int i, sparse=False) noexcept: """ Slack of the `i`-th constraint @@ -575,7 +575,7 @@ cdef class GenericSDPBackend: """ raise NotImplementedError() - cpdef solver_parameter(self, name, value = None): + cpdef solver_parameter(self, name, value = None) noexcept: """ Return or define a solver parameter @@ -686,7 +686,7 @@ def default_sdp_solver(solver=None): raise ValueError("'solver' should be set to 'CVXOPT', 'Matrix', a class, or None.") -cpdef GenericSDPBackend get_solver(solver=None, base_ring=None): +cpdef GenericSDPBackend get_solver(solver=None, base_ring=None) noexcept: """ Return a solver according to the given preferences. diff --git a/src/sage/numerical/backends/glpk_backend.pxd b/src/sage/numerical/backends/glpk_backend.pxd index 03dbe2c8688..064c69cac18 100644 --- a/src/sage/numerical/backends/glpk_backend.pxd +++ b/src/sage/numerical/backends/glpk_backend.pxd @@ -26,15 +26,15 @@ cdef class GLPKBackend(GenericBackend): cdef glp_smcp * smcp cdef int simplex_or_intopt cdef search_tree_data_t search_tree_data - cpdef __copy__(self) + cpdef __copy__(self) noexcept cpdef int print_ranges(self, filename = *) except -1 - cpdef double get_row_dual(self, int variable) + cpdef double get_row_dual(self, int variable) noexcept cpdef double get_col_dual(self, int variable) except? -1 cpdef int get_row_stat(self, int variable) except? -1 cpdef int get_col_stat(self, int variable) except? -1 - cpdef eval_tab_row(self, int k) - cpdef eval_tab_col(self, int k) - cpdef get_row_prim(self, int i) - cpdef set_row_stat(self, int i, int stat) - cpdef set_col_stat(self, int j, int stat) - cpdef int warm_up(self) + cpdef eval_tab_row(self, int k) noexcept + cpdef eval_tab_col(self, int k) noexcept + cpdef get_row_prim(self, int i) noexcept + cpdef set_row_stat(self, int i, int stat) noexcept + cpdef set_col_stat(self, int j, int stat) noexcept + cpdef int warm_up(self) noexcept diff --git a/src/sage/numerical/backends/glpk_backend.pyx b/src/sage/numerical/backends/glpk_backend.pyx index 4b90438bc8c..0fa5c2d3b98 100644 --- a/src/sage/numerical/backends/glpk_backend.pyx +++ b/src/sage/numerical/backends/glpk_backend.pyx @@ -228,7 +228,7 @@ cdef class GLPKBackend(GenericBackend): return n_var - 1 - cpdef set_variable_type(self, int variable, int vtype): + cpdef set_variable_type(self, int variable, int vtype) noexcept: """ Set the type of a variable @@ -278,7 +278,7 @@ cdef class GLPKBackend(GenericBackend): else: glp_set_col_kind(self.lp, variable+1, GLP_CV) - cpdef set_sense(self, int sense): + cpdef set_sense(self, int sense) noexcept: """ Set the direction (maximization/minimization). @@ -304,7 +304,7 @@ cdef class GLPKBackend(GenericBackend): else: glp_set_obj_dir(self.lp, GLP_MIN) - cpdef objective_coefficient(self, int variable, coeff=None): + cpdef objective_coefficient(self, int variable, coeff=None) noexcept: """ Set or get the coefficient of a variable in the objective function @@ -347,7 +347,7 @@ cdef class GLPKBackend(GenericBackend): else: glp_set_obj_coef(self.lp, variable + 1, coeff) - cpdef problem_name(self, name=None): + cpdef problem_name(self, name=None) noexcept: """ Return or define the problem's name @@ -379,7 +379,7 @@ cdef class GLPKBackend(GenericBackend): raise ValueError("Problem name for GLPK must not be longer than 255 characters.") glp_set_prob_name(self.lp, name) - cpdef set_objective(self, list coeff, d = 0.0): + cpdef set_objective(self, list coeff, d = 0.0) noexcept: """ Set the objective function. @@ -409,7 +409,7 @@ cdef class GLPKBackend(GenericBackend): self.obj_constant_term = d - cpdef set_verbosity(self, int level): + cpdef set_verbosity(self, int level) noexcept: """ Set the verbosity level @@ -471,7 +471,7 @@ cdef class GLPKBackend(GenericBackend): self.iocp.msg_lev = GLP_MSG_ALL self.smcp.msg_lev = GLP_MSG_ALL - cpdef remove_constraint(self, int i): + cpdef remove_constraint(self, int i) noexcept: r""" Remove a constraint from self. @@ -510,7 +510,7 @@ cdef class GLPKBackend(GenericBackend): glp_del_rows(self.lp, 1, rows) glp_std_basis(self.lp) - cpdef remove_constraints(self, constraints): + cpdef remove_constraints(self, constraints) noexcept: r""" Remove several constraints. @@ -562,7 +562,7 @@ cdef class GLPKBackend(GenericBackend): sig_free(rows) glp_std_basis(self.lp) - cpdef add_linear_constraint(self, coefficients, lower_bound, upper_bound, name=None): + cpdef add_linear_constraint(self, coefficients, lower_bound, upper_bound, name=None) noexcept: """ Add a linear constraint. @@ -649,7 +649,7 @@ cdef class GLPKBackend(GenericBackend): if name is not None: glp_set_row_name(self.lp, n, str_to_bytes(name)) - cpdef add_linear_constraints(self, int number, lower_bound, upper_bound, names=None): + cpdef add_linear_constraints(self, int number, lower_bound, upper_bound, names=None) noexcept: """ Add ``'number`` linear constraints. @@ -697,7 +697,7 @@ cdef class GLPKBackend(GenericBackend): glp_set_row_name(self.lp, n-i, str_to_bytes(names[number-i-1])) - cpdef row(self, int index): + cpdef row(self, int index) noexcept: r""" Return a row @@ -754,7 +754,7 @@ cdef class GLPKBackend(GenericBackend): return (indices, values) - cpdef row_bounds(self, int index): + cpdef row_bounds(self, int index) noexcept: """ Return the bounds of a specific constraint. @@ -806,7 +806,7 @@ cdef class GLPKBackend(GenericBackend): (ub if ub != +DBL_MAX else None) ) - cpdef col_bounds(self, int index): + cpdef col_bounds(self, int index) noexcept: """ Return the bounds of a specific variable. @@ -859,7 +859,7 @@ cdef class GLPKBackend(GenericBackend): (ub if ub != +DBL_MAX else None) ) - cpdef add_col(self, indices, coeffs): + cpdef add_col(self, indices, coeffs) noexcept: """ Add a column. @@ -1149,7 +1149,7 @@ cdef class GLPKBackend(GenericBackend): raise MIPSolverException("GLPK: "+solution_status_msg.get(solution_status, "unknown error during call to GLPK : "+str(solution_status))) return 0 - cpdef get_objective_value(self): + cpdef get_objective_value(self) noexcept: """ Returns the value of the objective function. @@ -1180,7 +1180,7 @@ cdef class GLPKBackend(GenericBackend): else: return glp_get_obj_val(self.lp) - cpdef best_known_objective_bound(self): + cpdef best_known_objective_bound(self) noexcept: r""" Return the value of the currently best known bound. @@ -1213,7 +1213,7 @@ cdef class GLPKBackend(GenericBackend): """ return self.search_tree_data.best_bound - cpdef get_relative_objective_gap(self): + cpdef get_relative_objective_gap(self) noexcept: r""" Return the relative objective gap of the best known solution. @@ -1255,7 +1255,7 @@ cdef class GLPKBackend(GenericBackend): """ return self.search_tree_data.mip_gap - cpdef get_variable_value(self, int variable): + cpdef get_variable_value(self, int variable) noexcept: """ Returns the value of a variable given by the solver. @@ -1301,7 +1301,7 @@ cdef class GLPKBackend(GenericBackend): else: return glp_get_col_prim(self.lp, variable + 1) - cpdef get_row_prim(self, int i): + cpdef get_row_prim(self, int i) noexcept: r""" Returns the value of the auxiliary variable associated with i-th row. @@ -1349,7 +1349,7 @@ cdef class GLPKBackend(GenericBackend): return glp_get_row_prim(self.lp, i+1) - cpdef int ncols(self): + cpdef int ncols(self) noexcept: """ Return the number of columns/variables. @@ -1366,7 +1366,7 @@ cdef class GLPKBackend(GenericBackend): """ return glp_get_num_cols(self.lp) - cpdef int nrows(self): + cpdef int nrows(self) noexcept: """ Return the number of rows/constraints. @@ -1383,7 +1383,7 @@ cdef class GLPKBackend(GenericBackend): return glp_get_num_rows(self.lp) - cpdef col_name(self, int index): + cpdef col_name(self, int index) noexcept: """ Return the ``index`` th col name @@ -1425,7 +1425,7 @@ cdef class GLPKBackend(GenericBackend): else: return "" - cpdef row_name(self, int index): + cpdef row_name(self, int index) noexcept: """ Return the ``index`` th row name @@ -1466,7 +1466,7 @@ cdef class GLPKBackend(GenericBackend): else: return "" - cpdef bint is_variable_binary(self, int index): + cpdef bint is_variable_binary(self, int index) noexcept: """ Test whether the given variable is of binary type. @@ -1503,7 +1503,7 @@ cdef class GLPKBackend(GenericBackend): return glp_get_col_kind(self.lp, index + 1) == GLP_BV - cpdef bint is_variable_integer(self, int index): + cpdef bint is_variable_integer(self, int index) noexcept: """ Test whether the given variable is of integer type. @@ -1540,7 +1540,7 @@ cdef class GLPKBackend(GenericBackend): return glp_get_col_kind(self.lp, index + 1) == GLP_IV - cpdef bint is_variable_continuous(self, int index): + cpdef bint is_variable_continuous(self, int index) noexcept: """ Test whether the given variable is of continuous/real type. @@ -1579,7 +1579,7 @@ cdef class GLPKBackend(GenericBackend): return glp_get_col_kind(self.lp, index + 1) == GLP_CV - cpdef bint is_maximization(self): + cpdef bint is_maximization(self) noexcept: """ Test whether the problem is a maximization @@ -1596,7 +1596,7 @@ cdef class GLPKBackend(GenericBackend): return glp_get_obj_dir(self.lp) == GLP_MAX - cpdef variable_upper_bound(self, int index, value = False): + cpdef variable_upper_bound(self, int index, value = False) noexcept: """ Return or define the upper bound on a variable @@ -1695,7 +1695,7 @@ cdef class GLPKBackend(GenericBackend): glp_set_col_bnds(self.lp, index + 1, GLP_DB, min, dvalue) sig_off() - cpdef variable_lower_bound(self, int index, value = False): + cpdef variable_lower_bound(self, int index, value = False) noexcept: """ Return or define the lower bound on a variable @@ -1795,7 +1795,7 @@ cdef class GLPKBackend(GenericBackend): glp_set_col_bnds(self.lp, index + 1, GLP_DB, value, max) sig_off() - cpdef write_lp(self, filename): + cpdef write_lp(self, filename) noexcept: """ Write the problem to a .lp file @@ -1822,7 +1822,7 @@ cdef class GLPKBackend(GenericBackend): filename = str_to_bytes(filename, FS_ENCODING, 'surrogateescape') glp_write_lp(self.lp, NULL, filename) - cpdef write_mps(self, filename, int modern): + cpdef write_mps(self, filename, int modern) noexcept: """ Write the problem to a .mps file @@ -1849,7 +1849,7 @@ cdef class GLPKBackend(GenericBackend): filename = str_to_bytes(filename, FS_ENCODING, 'surrogateescape') glp_write_mps(self.lp, modern, NULL, filename) - cpdef __copy__(self): + cpdef __copy__(self) noexcept: """ Returns a copy of self. @@ -1870,7 +1870,7 @@ cdef class GLPKBackend(GenericBackend): return p - cpdef solver_parameter(self, name, value = None): + cpdef solver_parameter(self, name, value = None) noexcept: """ Return or define a solver parameter @@ -2319,7 +2319,7 @@ cdef class GLPKBackend(GenericBackend): else: raise ValueError("This parameter is not available.") - cpdef bint is_variable_basic(self, int index): + cpdef bint is_variable_basic(self, int index) noexcept: """ Test whether the given variable is basic. @@ -2350,7 +2350,7 @@ cdef class GLPKBackend(GenericBackend): """ return self.get_col_stat(index) == GLP_BS - cpdef bint is_variable_nonbasic_at_lower_bound(self, int index): + cpdef bint is_variable_nonbasic_at_lower_bound(self, int index) noexcept: """ Test whether the given variable is nonbasic at lower bound. This assumes that the problem has been solved with the simplex method @@ -2380,7 +2380,7 @@ cdef class GLPKBackend(GenericBackend): """ return self.get_col_stat(index) == GLP_NL - cpdef bint is_slack_variable_basic(self, int index): + cpdef bint is_slack_variable_basic(self, int index) noexcept: """ Test whether the slack variable of the given row is basic. @@ -2411,7 +2411,7 @@ cdef class GLPKBackend(GenericBackend): """ return self.get_row_stat(index) == GLP_BS - cpdef bint is_slack_variable_nonbasic_at_lower_bound(self, int index): + cpdef bint is_slack_variable_nonbasic_at_lower_bound(self, int index) noexcept: """ Test whether the slack variable of the given row is nonbasic at lower bound. @@ -2525,7 +2525,7 @@ cdef class GLPKBackend(GenericBackend): 'surrogateescape')) return res - cpdef double get_row_dual(self, int variable): + cpdef double get_row_dual(self, int variable) noexcept: r""" Returns the dual value of a constraint. @@ -2721,7 +2721,7 @@ cdef class GLPKBackend(GenericBackend): return glp_get_col_stat(self.lp, j+1) - cpdef set_row_stat(self, int i, int stat): + cpdef set_row_stat(self, int i, int stat) noexcept: r""" Set the status of a constraint. @@ -2756,7 +2756,7 @@ cdef class GLPKBackend(GenericBackend): glp_set_row_stat(self.lp, i+1, stat) - cpdef set_col_stat(self, int j, int stat): + cpdef set_col_stat(self, int j, int stat) noexcept: r""" Set the status of a variable. @@ -2791,7 +2791,7 @@ cdef class GLPKBackend(GenericBackend): glp_set_col_stat(self.lp, j+1, stat) - cpdef int warm_up(self): + cpdef int warm_up(self) noexcept: r""" Warm up the basis using current statuses assigned to rows and cols. @@ -2827,7 +2827,7 @@ cdef class GLPKBackend(GenericBackend): """ return glp_warm_up(self.lp) - cpdef eval_tab_row(self, int k): + cpdef eval_tab_row(self, int k) noexcept: r""" Computes a row of the current simplex tableau. @@ -2926,7 +2926,7 @@ cdef class GLPKBackend(GenericBackend): values = [c_values[j+1] for j in range(i)] return (indices, values) - cpdef eval_tab_col(self, int k): + cpdef eval_tab_col(self, int k) noexcept: r""" Computes a column of the current simplex tableau. @@ -3033,7 +3033,7 @@ cdef class GLPKBackend(GenericBackend): sig_free(self.iocp) sig_free(self.smcp) -cdef void glp_callback(glp_tree* tree, void* info): +cdef void glp_callback(glp_tree* tree, void* info) noexcept: r""" A callback routine called by glp_intopt diff --git a/src/sage/numerical/backends/glpk_exact_backend.pxd b/src/sage/numerical/backends/glpk_exact_backend.pxd index ed55d9bce3e..40489d2ac94 100644 --- a/src/sage/numerical/backends/glpk_exact_backend.pxd +++ b/src/sage/numerical/backends/glpk_exact_backend.pxd @@ -13,4 +13,4 @@ from .glpk_backend cimport GLPKBackend cdef class GLPKExactBackend(GLPKBackend): cpdef int add_variable(self, lower_bound=*, upper_bound=*, binary=*, continuous=*, integer=*, obj=*, name=*) except -1 cpdef int add_variables(self, int, lower_bound=*, upper_bound=*, binary=*, continuous=*, integer=*, obj=*, names=*) except -1 - cpdef set_variable_type(self, int variable, int vtype) + cpdef set_variable_type(self, int variable, int vtype) noexcept diff --git a/src/sage/numerical/backends/glpk_exact_backend.pyx b/src/sage/numerical/backends/glpk_exact_backend.pyx index 3031748eb42..3508942f5e4 100644 --- a/src/sage/numerical/backends/glpk_exact_backend.pyx +++ b/src/sage/numerical/backends/glpk_exact_backend.pyx @@ -156,7 +156,7 @@ cdef class GLPKExactBackend(GLPKBackend): return GLPKBackend.add_variables(self, number, lower_bound, upper_bound, binary, continuous, integer, obj, names) - cpdef set_variable_type(self, int variable, int vtype): + cpdef set_variable_type(self, int variable, int vtype) noexcept: """ Set the type of a variable. diff --git a/src/sage/numerical/backends/glpk_graph_backend.pxd b/src/sage/numerical/backends/glpk_graph_backend.pxd index 1b63765de7f..926c60134dc 100644 --- a/src/sage/numerical/backends/glpk_graph_backend.pxd +++ b/src/sage/numerical/backends/glpk_graph_backend.pxd @@ -27,29 +27,29 @@ ctypedef struct c_a_data: cdef class GLPKGraphBackend(): cdef glp_graph * graph - cpdef add_vertex(self, name = ?) - cpdef list add_vertices(self, vertices) - cpdef __add_vertices_sage(self, g) - cpdef dict get_vertex(self, vertex) - cpdef dict get_vertices(self, verts) - cpdef set_vertex_demand(self, vertex, param) - cpdef set_vertices_demand(self, list pairs) - cpdef list vertices(self) - cpdef add_edge(self, u, v, dict params = ?) - cpdef __add_edges_sage(self, g) - cpdef list add_edges(self, edges) - cpdef delete_edge(self, u, v, dict params = ?) - cpdef tuple get_edge(self, u, v) - cpdef list edges(self) - cpdef delete_vertex(self, vert) - cpdef delete_vertices(self, list verts) - cpdef int _find_vertex(self, vert) - cpdef int write_graph(self, fname) - cpdef int write_ccdata(self, fname) - cpdef int write_mincost(self, fname) + cpdef add_vertex(self, name = ?) noexcept + cpdef list add_vertices(self, vertices) noexcept + cpdef __add_vertices_sage(self, g) noexcept + cpdef dict get_vertex(self, vertex) noexcept + cpdef dict get_vertices(self, verts) noexcept + cpdef set_vertex_demand(self, vertex, param) noexcept + cpdef set_vertices_demand(self, list pairs) noexcept + cpdef list vertices(self) noexcept + cpdef add_edge(self, u, v, dict params = ?) noexcept + cpdef __add_edges_sage(self, g) noexcept + cpdef list add_edges(self, edges) noexcept + cpdef delete_edge(self, u, v, dict params = ?) noexcept + cpdef tuple get_edge(self, u, v) noexcept + cpdef list edges(self) noexcept + cpdef delete_vertex(self, vert) noexcept + cpdef delete_vertices(self, list verts) noexcept + cpdef int _find_vertex(self, vert) noexcept + cpdef int write_graph(self, fname) noexcept + cpdef int write_ccdata(self, fname) noexcept + cpdef int write_mincost(self, fname) noexcept cpdef double mincost_okalg(self) except -1 cdef int s cdef int t cpdef int write_maxflow(self, fname) except -1 cpdef double maxflow_ffalg(self, u = ?, v = ?) except -1 - cpdef double cpp(self) + cpdef double cpp(self) noexcept diff --git a/src/sage/numerical/backends/glpk_graph_backend.pyx b/src/sage/numerical/backends/glpk_graph_backend.pyx index 1c0dc2974df..dcc6425d8de 100644 --- a/src/sage/numerical/backends/glpk_graph_backend.pyx +++ b/src/sage/numerical/backends/glpk_graph_backend.pyx @@ -230,7 +230,7 @@ cdef class GLPKGraphBackend(): else: ValueError("Input data is not supported") - cpdef add_vertex(self, name=None): + cpdef add_vertex(self, name=None) noexcept: """ Adds an isolated vertex to the graph. @@ -284,7 +284,7 @@ cdef class GLPKGraphBackend(): glp_set_vertex_name(self.graph, vn, str_to_bytes(s)) return s - cpdef __add_vertices_sage(self, g): + cpdef __add_vertices_sage(self, g) noexcept: """ Adds vertices to the GLPK Graph. @@ -326,7 +326,7 @@ cdef class GLPKGraphBackend(): glp_create_v_index(self.graph) - cpdef list add_vertices(self, vertices): + cpdef list add_vertices(self, vertices) noexcept: """ Adds vertices from an iterable container of vertices. @@ -378,7 +378,7 @@ cdef class GLPKGraphBackend(): else: return None - cpdef set_vertex_demand(self, vertex, demand): + cpdef set_vertex_demand(self, vertex, demand) noexcept: """ Sets the demand of the vertex in a mincost flow algorithm. @@ -415,7 +415,7 @@ cdef class GLPKGraphBackend(): cdef double val = demand (vert.data).rhs = val - cpdef set_vertices_demand(self, list pairs): + cpdef set_vertices_demand(self, list pairs) noexcept: """ Sets the parameters of selected vertices. @@ -443,7 +443,7 @@ cdef class GLPKGraphBackend(): except KeyError: pass - cpdef dict get_vertex(self, vertex): + cpdef dict get_vertex(self, vertex) noexcept: """ Returns a specific vertex as a ``dict`` Object. @@ -490,7 +490,7 @@ cdef class GLPKGraphBackend(): "ls" : vdata.ls } - cpdef dict get_vertices(self, verts): + cpdef dict get_vertices(self, verts) noexcept: """ Returns a dictionary of the dictionaries associated to each vertex. @@ -519,7 +519,7 @@ cdef class GLPKGraphBackend(): vl = [(v, self.get_vertex(v)) for v in verts] return dict([(v, p) for v, p in vl if p is not None]) - cpdef list vertices(self): + cpdef list vertices(self) noexcept: """ Returns the list of all vertices @@ -551,7 +551,7 @@ cdef class GLPKGraphBackend(): if self.graph.v[i+1].name is not NULL else None for i in range(self.graph.nv)] - cpdef add_edge(self, u, v, dict params=None): + cpdef add_edge(self, u, v, dict params=None) noexcept: """ Adds an edge between vertices ``u`` and ``v``. @@ -615,7 +615,7 @@ cdef class GLPKGraphBackend(): glp_del_arc(self.graph, a) raise TypeError("Invalid edge parameter.") - cpdef list add_edges(self, edges): + cpdef list add_edges(self, edges) noexcept: """ Adds edges to the graph. @@ -653,7 +653,7 @@ cdef class GLPKGraphBackend(): for ed in edges: self.add_edge(*ed) - cpdef __add_edges_sage(self, g): + cpdef __add_edges_sage(self, g) noexcept: """ Adds edges to the Graph. @@ -708,7 +708,7 @@ cdef class GLPKGraphBackend(): if "low" in label: (a.data).low = low - cpdef tuple get_edge(self, u, v): + cpdef tuple get_edge(self, u, v) noexcept: """ Returns an edge connecting two vertices. @@ -764,7 +764,7 @@ cdef class GLPKGraphBackend(): return None - cpdef list edges(self): + cpdef list edges(self) noexcept: """ Returns a ``list`` of all edges in the graph @@ -813,7 +813,7 @@ cdef class GLPKGraphBackend(): i += 1 return edge_list - cpdef delete_vertex(self, vert): + cpdef delete_vertex(self, vert) noexcept: r""" Removes a vertex from the graph. @@ -849,7 +849,7 @@ cdef class GLPKGraphBackend(): glp_del_vertices(self.graph, ndel, num) - cpdef delete_vertices(self, list verts): + cpdef delete_vertices(self, list verts) noexcept: r""" Removes vertices from the graph. @@ -893,7 +893,7 @@ cdef class GLPKGraphBackend(): sig_free(num) - cpdef delete_edge(self, u, v, dict params=None): + cpdef delete_edge(self, u, v, dict params=None) noexcept: """ Deletes an edge from the graph. @@ -1005,7 +1005,7 @@ cdef class GLPKGraphBackend(): for edge in edges: self.delete_edge(*edge) - cpdef int _find_vertex(self, name): + cpdef int _find_vertex(self, name) noexcept: """ Returns the index of a vertex specified by a name @@ -1032,7 +1032,7 @@ cdef class GLPKGraphBackend(): glp_create_v_index(self.graph) return glp_find_vertex(self.graph, str_to_bytes(name)) - 1 - cpdef int write_graph(self, fname): + cpdef int write_graph(self, fname) noexcept: r""" Writes the graph to a plain text file @@ -1060,7 +1060,7 @@ cdef class GLPKGraphBackend(): fname = str_to_bytes(fname, FS_ENCODING, 'surrogateescape') return glp_write_graph(self.graph, fname) - cpdef int write_ccdata(self, fname): + cpdef int write_ccdata(self, fname) noexcept: r""" Writes the graph to a text file in DIMACS format. @@ -1092,7 +1092,7 @@ cdef class GLPKGraphBackend(): fname = str_to_bytes(fname, FS_ENCODING, 'surrogateescape') return glp_write_ccdata(self.graph, 0, fname) - cpdef int write_mincost(self, fname): + cpdef int write_mincost(self, fname) noexcept: """ Writes the mincost flow problem data to a text file in DIMACS format @@ -1321,7 +1321,7 @@ cdef class GLPKGraphBackend(): return graph_sol - cpdef double cpp(self): + cpdef double cpp(self) noexcept: r""" Solves the critical path problem of a project network. diff --git a/src/sage/numerical/backends/interactivelp_backend.pxd b/src/sage/numerical/backends/interactivelp_backend.pxd index 07e63a7bb44..f29187632fc 100644 --- a/src/sage/numerical/backends/interactivelp_backend.pxd +++ b/src/sage/numerical/backends/interactivelp_backend.pxd @@ -30,6 +30,6 @@ cdef class InteractiveLPBackend(GenericBackend): coefficients=*) \ except -1 - cpdef dictionary(self) + cpdef dictionary(self) noexcept - cpdef interactive_lp_problem(self) + cpdef interactive_lp_problem(self) noexcept diff --git a/src/sage/numerical/backends/interactivelp_backend.pyx b/src/sage/numerical/backends/interactivelp_backend.pyx index 773c13b781c..665631f19de 100644 --- a/src/sage/numerical/backends/interactivelp_backend.pyx +++ b/src/sage/numerical/backends/interactivelp_backend.pyx @@ -81,7 +81,7 @@ cdef class InteractiveLPBackend: self.row_names = [] - cpdef __copy__(self): + cpdef __copy__(self) noexcept: """ Returns a copy of self. @@ -104,7 +104,7 @@ cdef class InteractiveLPBackend: cp.prob_name = self.prob_name return cp - cpdef base_ring(self): + cpdef base_ring(self) noexcept: """ Return the base ring. @@ -252,7 +252,7 @@ cdef class InteractiveLPBackend: problem_type, ring, objective_constant_term=d) return self.ncols() - 1 - cpdef set_variable_type(self, int variable, int vtype): + cpdef set_variable_type(self, int variable, int vtype) noexcept: """ Set the type of a variable. @@ -306,7 +306,7 @@ cdef class InteractiveLPBackend: d = self.lp.objective_constant_term() return A, b, c, x, constraint_types, variable_types, problem_type, base_ring, d - cpdef set_sense(self, int sense): + cpdef set_sense(self, int sense) noexcept: """ Set the direction (maximization/minimization). @@ -336,7 +336,7 @@ cdef class InteractiveLPBackend: constraint_types, variable_types, problem_type, ring, objective_constant_term=d) - cpdef objective_coefficient(self, int variable, coeff=None): + cpdef objective_coefficient(self, int variable, coeff=None) noexcept: """ Set or get the coefficient of a variable in the objective function @@ -369,7 +369,7 @@ cdef class InteractiveLPBackend: constraint_types, variable_types, problem_type, ring, objective_constant_term=d) - cpdef objective_constant_term(self, d=None): + cpdef objective_constant_term(self, d=None) noexcept: """ Set or get the constant term in the objective function @@ -395,7 +395,7 @@ cdef class InteractiveLPBackend: constraint_types, variable_types, problem_type, ring, objective_constant_term=d) - cpdef set_objective(self, list coeff, d = 0): + cpdef set_objective(self, list coeff, d = 0) noexcept: """ Set the objective function. @@ -445,7 +445,7 @@ cdef class InteractiveLPBackend: constraint_types, variable_types, problem_type, ring, objective_constant_term=d) - cpdef set_verbosity(self, int level): + cpdef set_verbosity(self, int level) noexcept: """ Set the log (verbosity) level @@ -461,7 +461,7 @@ cdef class InteractiveLPBackend: """ self.verbosity = level - cpdef remove_constraint(self, int i): + cpdef remove_constraint(self, int i) noexcept: r""" Remove a constraint. @@ -495,7 +495,7 @@ cdef class InteractiveLPBackend: constraint_types, variable_types, problem_type, ring, objective_constant_term=d) - cpdef add_linear_constraint(self, coefficients, lower_bound, upper_bound, name=None): + cpdef add_linear_constraint(self, coefficients, lower_bound, upper_bound, name=None) noexcept: """ Add a linear constraint. @@ -557,7 +557,7 @@ cdef class InteractiveLPBackend: problem_type, ring, objective_constant_term=d) - cpdef add_col(self, indices, coeffs): + cpdef add_col(self, indices, coeffs) noexcept: """ Add a column. @@ -632,7 +632,7 @@ cdef class InteractiveLPBackend: else: raise MIPSolverException("InteractiveLP: Problem is unbounded") - cpdef get_objective_value(self): + cpdef get_objective_value(self) noexcept: """ Return the value of the objective function. @@ -663,7 +663,7 @@ cdef class InteractiveLPBackend: v = - v return v - cpdef get_variable_value(self, int variable): + cpdef get_variable_value(self, int variable) noexcept: """ Return the value of a variable given by the solver. @@ -691,7 +691,7 @@ cdef class InteractiveLPBackend: solution = self.std_form_transformation(self.final_dictionary.basic_solution()) return solution[variable] - cpdef int ncols(self): + cpdef int ncols(self) noexcept: """ Return the number of columns/variables. @@ -708,7 +708,7 @@ cdef class InteractiveLPBackend: """ return self.lp.n_variables() - cpdef int nrows(self): + cpdef int nrows(self) noexcept: """ Return the number of rows/constraints. @@ -724,7 +724,7 @@ cdef class InteractiveLPBackend: """ return self.lp.n_constraints() - cpdef bint is_maximization(self): + cpdef bint is_maximization(self) noexcept: """ Test whether the problem is a maximization @@ -740,7 +740,7 @@ cdef class InteractiveLPBackend: """ return self.lp.problem_type() == "max" - cpdef problem_name(self, name=None): + cpdef problem_name(self, name=None) noexcept: """ Return or define the problem's name @@ -765,7 +765,7 @@ cdef class InteractiveLPBackend: else: self.prob_name = str(name) - cpdef row(self, int i): + cpdef row(self, int i) noexcept: """ Return a row @@ -799,7 +799,7 @@ cdef class InteractiveLPBackend: coeffs.append(A[i][j]) return (indices, coeffs) - cpdef row_bounds(self, int index): + cpdef row_bounds(self, int index) noexcept: """ Return the bounds of a specific constraint. @@ -834,7 +834,7 @@ cdef class InteractiveLPBackend: else: raise ValueError("Bad constraint_type") - cpdef col_bounds(self, int index): + cpdef col_bounds(self, int index) noexcept: """ Return the bounds of a specific variable. @@ -870,7 +870,7 @@ cdef class InteractiveLPBackend: else: raise ValueError("Bad _variable_types") - cpdef bint is_variable_binary(self, int index): + cpdef bint is_variable_binary(self, int index) noexcept: """ Test whether the given variable is of binary type. @@ -892,7 +892,7 @@ cdef class InteractiveLPBackend: """ return False - cpdef bint is_variable_integer(self, int index): + cpdef bint is_variable_integer(self, int index) noexcept: """ Test whether the given variable is of integer type. @@ -913,7 +913,7 @@ cdef class InteractiveLPBackend: """ return False - cpdef bint is_variable_continuous(self, int index): + cpdef bint is_variable_continuous(self, int index) noexcept: """ Test whether the given variable is of continuous/real type. @@ -935,7 +935,7 @@ cdef class InteractiveLPBackend: """ return True - cpdef row_name(self, int index): + cpdef row_name(self, int index) noexcept: """ Return the ``index`` th row name @@ -954,7 +954,7 @@ cdef class InteractiveLPBackend: """ return self.row_names[index] - cpdef col_name(self, int index): + cpdef col_name(self, int index) noexcept: """ Return the ``index``-th column name @@ -976,7 +976,7 @@ cdef class InteractiveLPBackend: """ return str(self.lp.decision_variables()[index]) - cpdef variable_upper_bound(self, int index, value = False): + cpdef variable_upper_bound(self, int index, value = False) noexcept: """ Return or define the upper bound on a variable @@ -1020,7 +1020,7 @@ cdef class InteractiveLPBackend: constraint_types, variable_types, problem_type, ring, objective_constant_term=d) - cpdef variable_lower_bound(self, int index, value = False): + cpdef variable_lower_bound(self, int index, value = False) noexcept: """ Return or define the lower bound on a variable @@ -1064,7 +1064,7 @@ cdef class InteractiveLPBackend: constraint_types, variable_types, problem_type, ring, objective_constant_term=d) - cpdef bint is_variable_basic(self, int index): + cpdef bint is_variable_basic(self, int index) noexcept: """ Test whether the given variable is basic. @@ -1094,7 +1094,7 @@ cdef class InteractiveLPBackend: """ return self.lp_std_form.decision_variables()[index] in self.final_dictionary.basic_variables() - cpdef bint is_variable_nonbasic_at_lower_bound(self, int index): + cpdef bint is_variable_nonbasic_at_lower_bound(self, int index) noexcept: """ Test whether the given variable is nonbasic at lower bound. @@ -1124,7 +1124,7 @@ cdef class InteractiveLPBackend: """ return self.lp_std_form.decision_variables()[index] in self.final_dictionary.nonbasic_variables() - cpdef bint is_slack_variable_basic(self, int index): + cpdef bint is_slack_variable_basic(self, int index) noexcept: """ Test whether the slack variable of the given row is basic. @@ -1154,7 +1154,7 @@ cdef class InteractiveLPBackend: """ return self.lp_std_form.slack_variables()[index] in self.final_dictionary.basic_variables() - cpdef bint is_slack_variable_nonbasic_at_lower_bound(self, int index): + cpdef bint is_slack_variable_nonbasic_at_lower_bound(self, int index) noexcept: """ Test whether the given variable is nonbasic at lower bound. @@ -1184,7 +1184,7 @@ cdef class InteractiveLPBackend: """ return self.lp_std_form.slack_variables()[index] in self.final_dictionary.nonbasic_variables() - cpdef dictionary(self): + cpdef dictionary(self) noexcept: # Proposed addition to the general interface, # which would for other solvers return backend dictionaries (#18804) """ @@ -1220,7 +1220,7 @@ cdef class InteractiveLPBackend: """ return self.final_dictionary - cpdef interactive_lp_problem(self): + cpdef interactive_lp_problem(self) noexcept: """ Return the :class:`InteractiveLPProblem` object associated with this backend. diff --git a/src/sage/numerical/backends/matrix_sdp_backend.pyx b/src/sage/numerical/backends/matrix_sdp_backend.pyx index 7668c64ecc1..7704ff91c90 100644 --- a/src/sage/numerical/backends/matrix_sdp_backend.pyx +++ b/src/sage/numerical/backends/matrix_sdp_backend.pyx @@ -55,7 +55,7 @@ cdef class MatrixSDPBackend(GenericSDPBackend): base_ring = QQ self._base_ring = base_ring - cpdef base_ring(self): + cpdef base_ring(self) noexcept: """ The base ring @@ -166,7 +166,7 @@ cdef class MatrixSDPBackend(GenericSDPBackend): self.add_variable() return len(self.objective_function) - 1 - cpdef set_sense(self, int sense): + cpdef set_sense(self, int sense) noexcept: """ Set the direction (maximization/minimization). @@ -192,7 +192,7 @@ cdef class MatrixSDPBackend(GenericSDPBackend): else: self.is_maximize = 0 - cpdef objective_coefficient(self, int variable, coeff=None): + cpdef objective_coefficient(self, int variable, coeff=None) noexcept: """ Set or get the coefficient of a variable in the objective function @@ -220,7 +220,7 @@ cdef class MatrixSDPBackend(GenericSDPBackend): else: return self.objective_function[variable] - cpdef set_objective(self, list coeff, d=0.0): + cpdef set_objective(self, list coeff, d=0.0) noexcept: """ Set the objective function. @@ -245,7 +245,7 @@ cdef class MatrixSDPBackend(GenericSDPBackend): self.objective_function[i] = coeff[i] obj_constant_term = d - cpdef add_linear_constraint(self, coefficients, name=None): + cpdef add_linear_constraint(self, coefficients, name=None) noexcept: """ Add a linear constraint. @@ -292,7 +292,7 @@ cdef class MatrixSDPBackend(GenericSDPBackend): self.matrices_dim[self.nrows()] = m.dimensions()[0] # self.row_name_var.append(name) - cpdef add_linear_constraints(self, int number, names=None): + cpdef add_linear_constraints(self, int number, names=None) noexcept: """ Add constraints. @@ -317,7 +317,7 @@ cdef class MatrixSDPBackend(GenericSDPBackend): name=None if names is None else names[i]) - cpdef int ncols(self): + cpdef int ncols(self) noexcept: """ Return the number of columns/variables. @@ -335,7 +335,7 @@ cdef class MatrixSDPBackend(GenericSDPBackend): return len(self.objective_function) - cpdef int nrows(self): + cpdef int nrows(self) noexcept: """ Return the number of rows/constraints. @@ -354,7 +354,7 @@ cdef class MatrixSDPBackend(GenericSDPBackend): return len(self.matrices_dim) - cpdef bint is_maximization(self): + cpdef bint is_maximization(self) noexcept: """ Test whether the problem is a maximization @@ -373,7 +373,7 @@ cdef class MatrixSDPBackend(GenericSDPBackend): else: return 0 - cpdef problem_name(self, name=None): + cpdef problem_name(self, name=None) noexcept: """ Return or define the problem's name @@ -396,7 +396,7 @@ cdef class MatrixSDPBackend(GenericSDPBackend): self.name = name - cpdef row(self, int i): + cpdef row(self, int i) noexcept: """ Return a row @@ -436,7 +436,7 @@ cdef class MatrixSDPBackend(GenericSDPBackend): matrices.append(m) return (indices, matrices) - cpdef row_name(self, int index): + cpdef row_name(self, int index) noexcept: """ Return the ``index`` th row name @@ -457,7 +457,7 @@ cdef class MatrixSDPBackend(GenericSDPBackend): return self.row_name_var[index] return "constraint_" + repr(index) - cpdef col_name(self, int index): + cpdef col_name(self, int index) noexcept: """ Return the ``index`` th col name diff --git a/src/sage/numerical/backends/ppl_backend.pyx b/src/sage/numerical/backends/ppl_backend.pyx index 03b54b34359..f437527e42c 100644 --- a/src/sage/numerical/backends/ppl_backend.pyx +++ b/src/sage/numerical/backends/ppl_backend.pyx @@ -90,14 +90,14 @@ cdef class PPLBackend(GenericBackend): else: self.set_sense(-1) - cpdef base_ring(self): + cpdef base_ring(self) noexcept: from sage.rings.rational_field import QQ return QQ - cpdef zero(self): + cpdef zero(self) noexcept: return self.base_ring()(0) - cpdef __copy__(self): + cpdef __copy__(self) noexcept: """ Returns a copy of self. @@ -377,7 +377,7 @@ cdef class PPLBackend(GenericBackend): self.col_name_var.append(None) return len(self.objective_function) - 1 - cpdef set_variable_type(self, int variable, int vtype): + cpdef set_variable_type(self, int variable, int vtype) noexcept: """ Set the type of a variable. @@ -430,7 +430,7 @@ cdef class PPLBackend(GenericBackend): else: raise ValueError("Invalid variable type: {}".format(vtype)) - cpdef set_sense(self, int sense): + cpdef set_sense(self, int sense) noexcept: """ Set the direction (maximization/minimization). @@ -456,7 +456,7 @@ cdef class PPLBackend(GenericBackend): else: self.is_maximize = 0 - cpdef objective_coefficient(self, int variable, coeff=None): + cpdef objective_coefficient(self, int variable, coeff=None) noexcept: """ Set or get the coefficient of a variable in the objective function @@ -484,7 +484,7 @@ cdef class PPLBackend(GenericBackend): else: return self.objective_function[variable] - cpdef set_objective(self, list coeff, d=0): + cpdef set_objective(self, list coeff, d=0) noexcept: """ Set the objective function. @@ -526,7 +526,7 @@ cdef class PPLBackend(GenericBackend): self.objective_function[i] = coeff[i] self.obj_constant_term = Rational(d) - cpdef set_verbosity(self, int level): + cpdef set_verbosity(self, int level) noexcept: """ Set the log (verbosity) level. Not Implemented. @@ -537,7 +537,7 @@ cdef class PPLBackend(GenericBackend): sage: p.set_verbosity(0) """ - cpdef add_linear_constraint(self, coefficients, lower_bound, upper_bound, name=None): + cpdef add_linear_constraint(self, coefficients, lower_bound, upper_bound, name=None) noexcept: """ Add a linear constraint. @@ -593,7 +593,7 @@ cdef class PPLBackend(GenericBackend): self.row_upper_bound.append(upper_bound) self.row_name_var.append(name) - cpdef add_col(self, indices, coeffs): + cpdef add_col(self, indices, coeffs) noexcept: """ Add a column. @@ -637,7 +637,7 @@ cdef class PPLBackend(GenericBackend): self.objective_function.append(0) self.col_name_var.append(None) - cpdef add_linear_constraints(self, int number, lower_bound, upper_bound, names=None): + cpdef add_linear_constraints(self, int number, lower_bound, upper_bound, names=None) noexcept: """ Add constraints. @@ -727,7 +727,7 @@ cdef class PPLBackend(GenericBackend): return 0 - cpdef get_objective_value(self): + cpdef get_objective_value(self) noexcept: """ Return the exact value of the objective function. @@ -762,7 +762,7 @@ cdef class PPLBackend(GenericBackend): ans = Rational(self.mip.optimal_value()) return ans / self.obj_denominator + self.obj_constant_term - cpdef get_variable_value(self, int variable): + cpdef get_variable_value(self, int variable) noexcept: """ Return the value of a variable given by the solver. @@ -790,7 +790,7 @@ cdef class PPLBackend(GenericBackend): g = self.mip.optimizing_point() return Integer(g.coefficient(Variable(variable))) / Integer(g.divisor()) - cpdef int ncols(self): + cpdef int ncols(self) noexcept: """ Return the number of columns/variables. @@ -807,7 +807,7 @@ cdef class PPLBackend(GenericBackend): """ return len(self.objective_function) - cpdef int nrows(self): + cpdef int nrows(self) noexcept: """ Return the number of rows/constraints. @@ -823,7 +823,7 @@ cdef class PPLBackend(GenericBackend): """ return len(self.Matrix) - cpdef bint is_maximization(self): + cpdef bint is_maximization(self) noexcept: """ Test whether the problem is a maximization @@ -842,7 +842,7 @@ cdef class PPLBackend(GenericBackend): else: return 0 - cpdef problem_name(self, name=None): + cpdef problem_name(self, name=None) noexcept: """ Return or define the problem's name @@ -863,7 +863,7 @@ cdef class PPLBackend(GenericBackend): return self.name self.name = name - cpdef row(self, int i): + cpdef row(self, int i) noexcept: """ Return a row @@ -898,7 +898,7 @@ cdef class PPLBackend(GenericBackend): coef.append(self.Matrix[i][j]) return (idx, coef) - cpdef row_bounds(self, int index): + cpdef row_bounds(self, int index) noexcept: """ Return the bounds of a specific constraint. @@ -926,7 +926,7 @@ cdef class PPLBackend(GenericBackend): """ return (self.row_lower_bound[index], self.row_upper_bound[index]) - cpdef col_bounds(self, int index): + cpdef col_bounds(self, int index) noexcept: """ Return the bounds of a specific variable. @@ -955,7 +955,7 @@ cdef class PPLBackend(GenericBackend): return (self.col_lower_bound[index], self.col_upper_bound[index]) - cpdef bint is_variable_binary(self, int index): + cpdef bint is_variable_binary(self, int index) noexcept: """ Test whether the given variable is of binary type. @@ -976,7 +976,7 @@ cdef class PPLBackend(GenericBackend): """ return index in self.integer_variables and self.col_bounds(index) == (0, 1) - cpdef bint is_variable_integer(self, int index): + cpdef bint is_variable_integer(self, int index) noexcept: """ Test whether the given variable is of integer type. @@ -997,7 +997,7 @@ cdef class PPLBackend(GenericBackend): """ return index in self.integer_variables and self.col_bounds(index) != (0, 1) - cpdef bint is_variable_continuous(self, int index): + cpdef bint is_variable_continuous(self, int index) noexcept: """ Test whether the given variable is of continuous/real type. @@ -1018,7 +1018,7 @@ cdef class PPLBackend(GenericBackend): """ return index not in self.integer_variables - cpdef row_name(self, int index): + cpdef row_name(self, int index) noexcept: """ Return the ``index`` th row name @@ -1038,7 +1038,7 @@ cdef class PPLBackend(GenericBackend): return self.row_name_var[index] return "constraint_" + repr(index) - cpdef col_name(self, int index): + cpdef col_name(self, int index) noexcept: """ Return the ``index`` th col name @@ -1062,7 +1062,7 @@ cdef class PPLBackend(GenericBackend): return self.col_name_var[index] return "x_" + repr(index) - cpdef variable_upper_bound(self, int index, value = False): + cpdef variable_upper_bound(self, int index, value = False) noexcept: """ Return or define the upper bound on a variable @@ -1094,7 +1094,7 @@ cdef class PPLBackend(GenericBackend): else: return self.col_upper_bound[index] - cpdef variable_lower_bound(self, int index, value = False): + cpdef variable_lower_bound(self, int index, value = False) noexcept: """ Return or define the lower bound on a variable diff --git a/src/sage/numerical/backends/scip_backend.pxd b/src/sage/numerical/backends/scip_backend.pxd index dc4981a89c3..c7a7c4d780c 100644 --- a/src/sage/numerical/backends/scip_backend.pxd +++ b/src/sage/numerical/backends/scip_backend.pxd @@ -16,6 +16,6 @@ cdef class SCIPBackend(GenericBackend): cdef object variables cdef object constraints - cpdef _get_model(self) - cpdef get_row_prim(self, int i) - cpdef write_cip(self, filename) + cpdef _get_model(self) noexcept + cpdef get_row_prim(self, int i) noexcept + cpdef write_cip(self, filename) noexcept diff --git a/src/sage/numerical/backends/scip_backend.pyx b/src/sage/numerical/backends/scip_backend.pyx index fbec62ebcbf..606b16190a8 100644 --- a/src/sage/numerical/backends/scip_backend.pyx +++ b/src/sage/numerical/backends/scip_backend.pyx @@ -66,7 +66,7 @@ cdef class SCIPBackend(GenericBackend): self.constraints = self.model.getConss() return self.constraints - cpdef _get_model(self): + cpdef _get_model(self) noexcept: """ Get the model as a pyscipopt Model. @@ -161,7 +161,7 @@ cdef class SCIPBackend(GenericBackend): return index - cpdef set_variable_type(self, int variable, int vtype): + cpdef set_variable_type(self, int variable, int vtype) noexcept: """ Set the type of a variable @@ -192,7 +192,7 @@ cdef class SCIPBackend(GenericBackend): vtypenames = {1: 'I', 0: 'B', -1: 'C'} self.model.chgVarType(var=self.variables[variable], vtype=vtypenames[vtype]) - cpdef set_sense(self, int sense): + cpdef set_sense(self, int sense) noexcept: """ Set the direction (maximization/minimization). @@ -222,7 +222,7 @@ cdef class SCIPBackend(GenericBackend): else: raise AssertionError("sense must be either 1 or -1") - cpdef objective_coefficient(self, int variable, coeff=None): + cpdef objective_coefficient(self, int variable, coeff=None) noexcept: """ Set or get the coefficient of a variable in the objective function @@ -255,7 +255,7 @@ cdef class SCIPBackend(GenericBackend): linfun = sum([e * c for e, c in objexpr.terms.iteritems() if e != var]) + var * coeff self.model.setObjective(linfun, sense=self.model.getObjectiveSense()) - cpdef problem_name(self, name=None): + cpdef problem_name(self, name=None) noexcept: """ Return or define the problem's name @@ -277,7 +277,7 @@ cdef class SCIPBackend(GenericBackend): else: self.model.setProbName(name) - cpdef set_objective(self, list coeff, d=0.0): + cpdef set_objective(self, list coeff, d=0.0) noexcept: """ Set the objective function. @@ -303,7 +303,7 @@ cdef class SCIPBackend(GenericBackend): linfun = sum([c * x for c, x in zip(coeff, self.variables)]) + d self.model.setObjective(linfun, sense=self.model.getObjectiveSense()) - cpdef set_verbosity(self, int level): + cpdef set_verbosity(self, int level) noexcept: """ Set the verbosity level @@ -331,7 +331,7 @@ cdef class SCIPBackend(GenericBackend): else: raise AssertionError('level must be "0" or "1"') - cpdef remove_constraint(self, int i): + cpdef remove_constraint(self, int i) noexcept: r""" Remove a constraint from self. @@ -369,7 +369,7 @@ cdef class SCIPBackend(GenericBackend): self.model.delCons(self.get_constraints()[i]) self.constraints = None - cpdef add_linear_constraint(self, coefficients, lower_bound, upper_bound, name=None): + cpdef add_linear_constraint(self, coefficients, lower_bound, upper_bound, name=None) noexcept: """ Add a linear constraint. @@ -417,7 +417,7 @@ cdef class SCIPBackend(GenericBackend): self.model.addCons(cons, name=name) self.constraints = None - cpdef row(self, int index): + cpdef row(self, int index) noexcept: r""" Return a row @@ -454,7 +454,7 @@ cdef class SCIPBackend(GenericBackend): values.append(coeff) return (indices, values) - cpdef row_bounds(self, int index): + cpdef row_bounds(self, int index) noexcept: """ Return the bounds of a specific constraint. @@ -487,7 +487,7 @@ cdef class SCIPBackend(GenericBackend): rhs = None return (lhs, rhs) - cpdef col_bounds(self, int index): + cpdef col_bounds(self, int index) noexcept: """ Return the bounds of a specific variable. @@ -522,7 +522,7 @@ cdef class SCIPBackend(GenericBackend): ub = None return (lb, ub) - cpdef add_col(self, indices, coeffs): + cpdef add_col(self, indices, coeffs) noexcept: """ Add a column. @@ -648,7 +648,7 @@ cdef class SCIPBackend(GenericBackend): # raise MIPSolverException("SCIP: Time limit reached") return 0 - cpdef get_objective_value(self): + cpdef get_objective_value(self) noexcept: """ Return the value of the objective function. @@ -675,7 +675,7 @@ cdef class SCIPBackend(GenericBackend): """ return self.model.getObjVal() - cpdef best_known_objective_bound(self): + cpdef best_known_objective_bound(self) noexcept: r""" Return the value of the currently best known bound. @@ -695,7 +695,7 @@ cdef class SCIPBackend(GenericBackend): """ return self.model.getPrimalbound() - cpdef get_relative_objective_gap(self): + cpdef get_relative_objective_gap(self) noexcept: r""" Return the relative objective gap of the best known solution. @@ -722,7 +722,7 @@ cdef class SCIPBackend(GenericBackend): """ return self.model.getGap() - cpdef get_variable_value(self, int variable): + cpdef get_variable_value(self, int variable) noexcept: """ Return the value of a variable given by the solver. @@ -749,7 +749,7 @@ cdef class SCIPBackend(GenericBackend): """ return self.model.getVal(self.variables[variable]) - cpdef get_row_prim(self, int i): + cpdef get_row_prim(self, int i) noexcept: r""" Return the value of the auxiliary variable associated with i-th row. @@ -781,7 +781,7 @@ cdef class SCIPBackend(GenericBackend): """ return self.model.getActivity(self.get_constraints()[i]) - cpdef int ncols(self): + cpdef int ncols(self) noexcept: """ Return the number of columns/variables. @@ -798,7 +798,7 @@ cdef class SCIPBackend(GenericBackend): """ return len(self.variables) - cpdef int nrows(self): + cpdef int nrows(self) noexcept: """ Return the number of rows/constraints. @@ -814,7 +814,7 @@ cdef class SCIPBackend(GenericBackend): """ return len(self.get_constraints()) - cpdef col_name(self, int index): + cpdef col_name(self, int index) noexcept: """ Return the ``index``th col name @@ -833,7 +833,7 @@ cdef class SCIPBackend(GenericBackend): """ return self.variables[index].name - cpdef row_name(self, int index): + cpdef row_name(self, int index) noexcept: """ Return the ``index`` th row name @@ -851,7 +851,7 @@ cdef class SCIPBackend(GenericBackend): """ return self.get_constraints()[index].name - cpdef bint is_variable_binary(self, int index): + cpdef bint is_variable_binary(self, int index) noexcept: """ Test whether the given variable is of binary type. @@ -874,7 +874,7 @@ cdef class SCIPBackend(GenericBackend): """ return self.variables[index].vtype() == 'BINARY' - cpdef bint is_variable_integer(self, int index): + cpdef bint is_variable_integer(self, int index) noexcept: """ Test whether the given variable is of integer type. @@ -896,7 +896,7 @@ cdef class SCIPBackend(GenericBackend): """ return self.variables[index].vtype() == 'INTEGER' - cpdef bint is_variable_continuous(self, int index): + cpdef bint is_variable_continuous(self, int index) noexcept: """ Test whether the given variable is of continuous/real type. @@ -920,7 +920,7 @@ cdef class SCIPBackend(GenericBackend): """ return self.variables[index].vtype() == 'CONTINUOUS' - cpdef bint is_maximization(self): + cpdef bint is_maximization(self) noexcept: """ Test whether the problem is a maximization @@ -936,7 +936,7 @@ cdef class SCIPBackend(GenericBackend): """ return self.model.getObjectiveSense() != 'minimize' - cpdef variable_upper_bound(self, int index, value=False): + cpdef variable_upper_bound(self, int index, value=False) noexcept: """ Return or define the upper bound on a variable @@ -997,7 +997,7 @@ cdef class SCIPBackend(GenericBackend): else: self.model.chgVarUb(var=var, ub=value) - cpdef variable_lower_bound(self, int index, value=False): + cpdef variable_lower_bound(self, int index, value=False) noexcept: """ Return or define the lower bound on a variable @@ -1059,7 +1059,7 @@ cdef class SCIPBackend(GenericBackend): else: self.model.chgVarLb(var=var, lb=value) - cpdef write_cip(self, filename): + cpdef write_cip(self, filename) noexcept: """ Write the problem to a .cip file @@ -1082,7 +1082,7 @@ cdef class SCIPBackend(GenericBackend): """ self.model.writeProblem(filename) - cpdef write_lp(self, filename): + cpdef write_lp(self, filename) noexcept: """ Write the problem to a .lp file @@ -1111,7 +1111,7 @@ cdef class SCIPBackend(GenericBackend): self.model.writeProblem(filenamestr) - cpdef write_mps(self, filename, int modern): + cpdef write_mps(self, filename, int modern) noexcept: """ Write the problem to a .mps file @@ -1140,7 +1140,7 @@ cdef class SCIPBackend(GenericBackend): self.model.writeProblem(filenamestr) - cpdef __copy__(self): + cpdef __copy__(self) noexcept: """ Return a copy of self. @@ -1178,7 +1178,7 @@ cdef class SCIPBackend(GenericBackend): assert self.nrows() == cp.nrows() return cp - cpdef solver_parameter(self, name, value=None): + cpdef solver_parameter(self, name, value=None) noexcept: """ Return or define a solver parameter diff --git a/src/sage/numerical/linear_functions.pxd b/src/sage/numerical/linear_functions.pxd index 568f04b75af..4ad836d8d6d 100644 --- a/src/sage/numerical/linear_functions.pxd +++ b/src/sage/numerical/linear_functions.pxd @@ -1,30 +1,30 @@ from sage.structure.parent cimport Parent, Parent_richcmp_element_without_coercion from sage.structure.element cimport ModuleElement, RingElement, Element -cpdef is_LinearFunction(x) +cpdef is_LinearFunction(x) noexcept cdef class LinearFunctionOrConstraint(ModuleElement): pass cdef class LinearFunctionsParent_class(Parent): - cpdef _element_constructor_(self, x) - cpdef _coerce_map_from_(self, R) + cpdef _element_constructor_(self, x) noexcept + cpdef _coerce_map_from_(self, R) noexcept cdef public _multiplication_symbol cdef class LinearFunction(LinearFunctionOrConstraint): cdef dict _f - cpdef _add_(self, other) - cpdef iteritems(self) - cpdef _acted_upon_(self, x, bint self_on_left) - cpdef is_zero(self) - cpdef equals(LinearFunction left, LinearFunction right) + cpdef _add_(self, other) noexcept + cpdef iteritems(self) noexcept + cpdef _acted_upon_(self, x, bint self_on_left) noexcept + cpdef is_zero(self) noexcept + cpdef equals(LinearFunction left, LinearFunction right) noexcept cdef class LinearConstraintsParent_class(Parent): cdef LinearFunctionsParent_class _LF - cpdef _element_constructor_(self, left, right=?, equality=?) - cpdef _coerce_map_from_(self, R) + cpdef _element_constructor_(self, left, right=?, equality=?) noexcept + cpdef _coerce_map_from_(self, R) noexcept cdef class LinearConstraint(LinearFunctionOrConstraint): cdef bint equality cdef list constraints - cpdef equals(LinearConstraint left, LinearConstraint right) + cpdef equals(LinearConstraint left, LinearConstraint right) noexcept diff --git a/src/sage/numerical/linear_functions.pyx b/src/sage/numerical/linear_functions.pyx index f3fc6fe419c..edeed1dfef7 100644 --- a/src/sage/numerical/linear_functions.pyx +++ b/src/sage/numerical/linear_functions.pyx @@ -114,7 +114,7 @@ from sage.misc.cachefunc import cached_function # #***************************************************************************** -cpdef is_LinearFunction(x): +cpdef is_LinearFunction(x) noexcept: """ Test whether ``x`` is a linear function @@ -663,7 +663,7 @@ cdef class LinearFunctionsParent_class(Parent): """ return 'Linear functions over ' + str(self.base_ring()) - cpdef _element_constructor_(self, x): + cpdef _element_constructor_(self, x) noexcept: """ Construct a :class:`LinearFunction` from ``x``. @@ -693,7 +693,7 @@ cdef class LinearFunctionsParent_class(Parent): return LinearFunction(self, (x)._f) return LinearFunction(self, x) - cpdef _coerce_map_from_(self, R): + cpdef _coerce_map_from_(self, R) noexcept: """ Allow coercion of scalars into linear functions. @@ -802,7 +802,7 @@ cdef class LinearFunction(LinearFunctionOrConstraint): else: self._f = {-1: R(f)} - cpdef iteritems(self): + cpdef iteritems(self) noexcept: """ Iterate over the index, coefficient pairs. @@ -905,7 +905,7 @@ cdef class LinearFunction(LinearFunctionOrConstraint): except KeyError: return self.parent().base_ring().zero() - cpdef _add_(self, b): + cpdef _add_(self, b) noexcept: r""" Defining the + operator @@ -922,7 +922,7 @@ cdef class LinearFunction(LinearFunctionOrConstraint): P = self.parent() return P(e) - cpdef _neg_(self): + cpdef _neg_(self) noexcept: r""" Defining the - operator (opposite). @@ -936,7 +936,7 @@ cdef class LinearFunction(LinearFunctionOrConstraint): P = self.parent() return P({id: -coeff for id, coeff in self._f.iteritems()}) - cpdef _sub_(self, b): + cpdef _sub_(self, b) noexcept: r""" Defining the - operator (subtraction). @@ -955,7 +955,7 @@ cdef class LinearFunction(LinearFunctionOrConstraint): P = self.parent() return P(e) - cpdef _lmul_(self, Element b): + cpdef _lmul_(self, Element b) noexcept: r""" Multiplication by scalars @@ -971,7 +971,7 @@ cdef class LinearFunction(LinearFunctionOrConstraint): P = self.parent() return P(dict([(id,b*coeff) for (id, coeff) in self._f.iteritems()])) - cpdef _acted_upon_(self, x, bint self_on_left): + cpdef _acted_upon_(self, x, bint self_on_left) noexcept: """ Act with scalars that do not have a natural coercion into ``self.base_ring()`` @@ -1130,7 +1130,7 @@ cdef class LinearFunction(LinearFunctionOrConstraint): else: return t - cpdef is_zero(self): + cpdef is_zero(self) noexcept: """ Test whether ``self`` is zero. @@ -1150,7 +1150,7 @@ cdef class LinearFunction(LinearFunctionOrConstraint): return False return True - cpdef equals(LinearFunction left, LinearFunction right): + cpdef equals(LinearFunction left, LinearFunction right) noexcept: """ Logically compare ``left`` and ``right``. @@ -1267,7 +1267,7 @@ cdef class LinearConstraintsParent_class(Parent): """ return 'Linear constraints over ' + str(self.linear_functions_parent().base_ring()) - cpdef _element_constructor_(self, left, right=None, equality=False): + cpdef _element_constructor_(self, left, right=None, equality=False) noexcept: """ Construct a :class:`LinearConstraint`. @@ -1332,7 +1332,7 @@ cdef class LinearConstraintsParent_class(Parent): else: return LinearConstraint(self, [left, right], equality=equality) - cpdef _coerce_map_from_(self, R): + cpdef _coerce_map_from_(self, R) noexcept: """ Allow coercion of scalars into linear functions. @@ -1432,7 +1432,7 @@ cdef class LinearConstraint(LinearFunctionOrConstraint): LF = parent.linear_functions_parent() self.constraints = [ LF(term) for term in terms ] - cpdef equals(LinearConstraint left, LinearConstraint right): + cpdef equals(LinearConstraint left, LinearConstraint right) noexcept: """ Compare ``left`` and ``right``. diff --git a/src/sage/numerical/linear_tensor_element.pxd b/src/sage/numerical/linear_tensor_element.pxd index 1cd84d3e33f..528f58b991c 100644 --- a/src/sage/numerical/linear_tensor_element.pxd +++ b/src/sage/numerical/linear_tensor_element.pxd @@ -2,4 +2,4 @@ from sage.structure.element cimport Element, ModuleElement cdef class LinearTensor(ModuleElement): cdef dict _f - cpdef _add_(self, other) + cpdef _add_(self, other) noexcept diff --git a/src/sage/numerical/linear_tensor_element.pyx b/src/sage/numerical/linear_tensor_element.pyx index c77aa290e21..e2c88619469 100644 --- a/src/sage/numerical/linear_tensor_element.pyx +++ b/src/sage/numerical/linear_tensor_element.pyx @@ -261,7 +261,7 @@ cdef class LinearTensor(ModuleElement): s += ']' return s - cpdef _add_(self, b): + cpdef _add_(self, b) noexcept: r""" Return sum. @@ -285,7 +285,7 @@ cdef class LinearTensor(ModuleElement): result[key] = self._f.get(key, 0) + coeff return self.parent()(result) - cpdef _neg_(self): + cpdef _neg_(self) noexcept: r""" Return the negative. @@ -305,7 +305,7 @@ cdef class LinearTensor(ModuleElement): result[key] = -coeff return self.parent()(result) - cpdef _sub_(self, b): + cpdef _sub_(self, b) noexcept: r""" Return difference. @@ -331,7 +331,7 @@ cdef class LinearTensor(ModuleElement): result[key] = self._f.get(key, 0) - coeff return self.parent()(result) - cpdef _lmul_(self, Element b): + cpdef _lmul_(self, Element b) noexcept: r""" Return multiplication by scalar. diff --git a/src/sage/numerical/mip.pxd b/src/sage/numerical/mip.pxd index 3046d8b4886..612324a5424 100644 --- a/src/sage/numerical/mip.pxd +++ b/src/sage/numerical/mip.pxd @@ -19,11 +19,11 @@ cdef class MixedIntegerLinearProgram(SageObject): cdef int __INTEGER cdef object _linear_functions_parent cdef object _linear_constraints_parent - cpdef int number_of_constraints(self) - cpdef int number_of_variables(self) + cpdef int number_of_constraints(self) noexcept + cpdef int number_of_variables(self) noexcept cdef int _check_redundant cdef list _constraints - cpdef sum(self, L) + cpdef sum(self, L) noexcept cdef class MIPVariable(SageObject): @@ -34,5 +34,5 @@ cdef class MIPVariable(SageObject): cdef str _name cdef object _lower_bound cdef object _upper_bound - cdef _matrix_rmul_impl(self, m) - cdef _matrix_lmul_impl(self, m) + cdef _matrix_rmul_impl(self, m) noexcept + cdef _matrix_lmul_impl(self, m) noexcept diff --git a/src/sage/numerical/mip.pyx b/src/sage/numerical/mip.pyx index 3711d9562cf..71dc66360da 100644 --- a/src/sage/numerical/mip.pyx +++ b/src/sage/numerical/mip.pyx @@ -869,7 +869,7 @@ cdef class MixedIntegerLinearProgram(SageObject): """ return tuple(self.new_variable() for i in range(n)) - cpdef int number_of_constraints(self): + cpdef int number_of_constraints(self) noexcept: r""" Return the number of constraints assigned so far. @@ -883,7 +883,7 @@ cdef class MixedIntegerLinearProgram(SageObject): """ return self._backend.nrows() - cpdef int number_of_variables(self): + cpdef int number_of_variables(self) noexcept: r""" Returns the number of variables used so far. @@ -2878,7 +2878,7 @@ cdef class MixedIntegerLinearProgram(SageObject): else: self._backend.solver_parameter(name, value) - cpdef sum(self, L): + cpdef sum(self, L) noexcept: r""" Efficiently computes the sum of a sequence of :class:`~sage.numerical.linear_functions.LinearFunction` elements @@ -3658,7 +3658,7 @@ cdef class MIPVariable(SageObject): return NotImplemented return ( right)._matrix_lmul_impl(left) - cdef _matrix_rmul_impl(self, m): + cdef _matrix_rmul_impl(self, m) noexcept: """ Implement the action of a matrix multiplying from the right. """ @@ -3672,7 +3672,7 @@ cdef class MIPVariable(SageObject): T = self._p.linear_functions_parent().tensor(V) return T(result) - cdef _matrix_lmul_impl(self, m): + cdef _matrix_lmul_impl(self, m) noexcept: """ Implement the action of a matrix multiplying from the left. """ diff --git a/src/sage/numerical/sdp.pxd b/src/sage/numerical/sdp.pxd index e0351dde4f3..47964ef1789 100644 --- a/src/sage/numerical/sdp.pxd +++ b/src/sage/numerical/sdp.pxd @@ -13,12 +13,12 @@ cdef class SemidefiniteProgram(SageObject): cdef dict _variables cdef object _linear_functions_parent cdef object _linear_constraints_parent - cpdef int number_of_constraints(self) - cpdef int number_of_variables(self) + cpdef int number_of_constraints(self) noexcept + cpdef int number_of_variables(self) noexcept cdef list _constraints - cpdef sum(self, L) - cpdef dual_variable(self, int i, sparse=*) - cpdef slack(self, int i, sparse=*) + cpdef sum(self, L) noexcept + cpdef dual_variable(self, int i, sparse=*) noexcept + cpdef slack(self, int i, sparse=*) noexcept cdef class SDPVariable(Element): @@ -26,9 +26,9 @@ cdef class SDPVariable(Element): cdef dict _dict cdef str _name cdef bint _hasname - cdef _matrix_rmul_impl(self, m) - cdef _matrix_lmul_impl(self, m) - cpdef _acted_upon_(self, mat, bint self_on_left) + cdef _matrix_rmul_impl(self, m) noexcept + cdef _matrix_lmul_impl(self, m) noexcept + cpdef _acted_upon_(self, mat, bint self_on_left) noexcept cdef class SDPVariableParent(Parent): diff --git a/src/sage/numerical/sdp.pyx b/src/sage/numerical/sdp.pyx index 77f7fa5254c..e7b96a2abef 100644 --- a/src/sage/numerical/sdp.pyx +++ b/src/sage/numerical/sdp.pyx @@ -565,7 +565,7 @@ cdef class SemidefiniteProgram(SageObject): """ return self.linear_functions_parent().gen(i) - cpdef int number_of_constraints(self): + cpdef int number_of_constraints(self) noexcept: r""" Returns the number of constraints assigned so far. @@ -587,7 +587,7 @@ cdef class SemidefiniteProgram(SageObject): """ return self._backend.nrows() - cpdef int number_of_variables(self): + cpdef int number_of_variables(self) noexcept: r""" Returns the number of variables used so far. @@ -959,7 +959,7 @@ cdef class SemidefiniteProgram(SageObject): return self._backend.get_objective_value() - cpdef dual_variable(self, int i, sparse=False): + cpdef dual_variable(self, int i, sparse=False) noexcept: """ The `i`-th dual variable. @@ -1008,7 +1008,7 @@ cdef class SemidefiniteProgram(SageObject): """ return self._backend.dual_variable(i, sparse=sparse) - cpdef slack(self, int i, sparse=False): + cpdef slack(self, int i, sparse=False) noexcept: """ Slack of the `i`-th constraint @@ -1101,7 +1101,7 @@ cdef class SemidefiniteProgram(SageObject): else: self._backend.solver_parameter(name, value) - cpdef sum(self, L): + cpdef sum(self, L) noexcept: r""" Efficiently computes the sum of a sequence of :class:`~sage.numerical.linear_functions.LinearFunction` elements. @@ -1324,7 +1324,7 @@ cdef class SDPVariable(Element): """ return self._dict.values() - cdef _matrix_rmul_impl(self, m): + cdef _matrix_rmul_impl(self, m) noexcept: """ Implement the action of a matrix multiplying from the right. """ @@ -1338,7 +1338,7 @@ cdef class SDPVariable(Element): T = self._p.linear_functions_parent().tensor(V) return T(result) - cdef _matrix_lmul_impl(self, m): + cdef _matrix_lmul_impl(self, m) noexcept: """ Implement the action of a matrix multiplying from the left. """ @@ -1352,7 +1352,7 @@ cdef class SDPVariable(Element): T = self._p.linear_functions_parent().tensor(V) return T(result) - cpdef _acted_upon_(self, mat, bint self_on_left): + cpdef _acted_upon_(self, mat, bint self_on_left) noexcept: """ Act with matrices on SDPVariables. diff --git a/src/sage/plot/complex_plot.pyx b/src/sage/plot/complex_plot.pyx index cb6a9cf8ca0..01d8060ea01 100644 --- a/src/sage/plot/complex_plot.pyx +++ b/src/sage/plot/complex_plot.pyx @@ -44,13 +44,13 @@ DEFAULT_LOGARITHMIC_CONTOUR_BASE = 2 DEFAULT_LINEAR_CONTOUR_BASE = 10 -cdef inline ComplexDoubleElement new_CDF_element(double x, double y): +cdef inline ComplexDoubleElement new_CDF_element(double x, double y) noexcept: z = ComplexDoubleElement.__new__(ComplexDoubleElement) GSL_SET_COMPLEX(&z._complex, x, y) return z -cdef inline double mag_to_lightness(double r, double rate=0.5): +cdef inline double mag_to_lightness(double r, double rate=0.5) noexcept: """ Return a lightness for the given magnitude. @@ -101,7 +101,7 @@ cdef inline double mag_to_lightness(double r, double rate=0.5): return atan(log(pow(r, rate)+1)) * (4/PI) - 1 -cdef inline double cyclic_logarithmic_mag_to_lightness(double r, double base=2): +cdef inline double cyclic_logarithmic_mag_to_lightness(double r, double base=2) noexcept: r""" Return a lightness for the given magnitude. @@ -152,7 +152,7 @@ cdef inline double cyclic_logarithmic_mag_to_lightness(double r, double base=2): return .15 - rem/2. -cdef inline double cyclic_linear_mag_to_lightness(double r, double base=10): +cdef inline double cyclic_linear_mag_to_lightness(double r, double base=10) noexcept: r""" Return a lightness for the given magnitude. @@ -205,7 +205,7 @@ cdef inline double cyclic_linear_mag_to_lightness(double r, double base=10): cdef inline double mag_and_arg_to_lightness(double r, double arg, - double base=2, int nphases=10): + double base=2, int nphases=10) noexcept: r""" Return a lightness for the given magnitude and argument. diff --git a/src/sage/plot/plot3d/implicit_surface.pyx b/src/sage/plot/plot3d/implicit_surface.pyx index db8a3f226f3..f5773a63d08 100644 --- a/src/sage/plot/plot3d/implicit_surface.pyx +++ b/src/sage/plot/plot3d/implicit_surface.pyx @@ -97,7 +97,7 @@ DEFAULT_PLOT_POINTS = 40 cdef double nan = float(RDF('NaN')) -cdef inline bint marching_has_edge(double a, double b, double contour, double *f, bint *has_nan): +cdef inline bint marching_has_edge(double a, double b, double contour, double *f, bint *has_nan) noexcept: if isnan(a) or isnan(b): has_nan[0] = True return False @@ -111,10 +111,10 @@ cdef inline bint marching_has_edge(double a, double b, double contour, double *f return True # Returns 0 or 1 -cdef inline int marching_is_inside(double v, double contour): +cdef inline int marching_is_inside(double v, double contour) noexcept: return isnan(v) or v < contour -cdef void interpolate_point_c(point_c *result, double frac, point_c *inputs): +cdef void interpolate_point_c(point_c *result, double frac, point_c *inputs) noexcept: result[0].x = inputs[0].x + frac*(inputs[1].x - inputs[0].x) result[0].y = inputs[0].y + frac*(inputs[1].y - inputs[0].y) result[0].z = inputs[0].z + frac*(inputs[1].z - inputs[0].z) @@ -133,7 +133,7 @@ cdef class VertexInfo: # This point in "evaluation space" cdef point_c eval_pt - cdef void update_eval_pt(self, point_c *eval_min, point_c *eval_scale): + cdef void update_eval_pt(self, point_c *eval_min, point_c *eval_scale) noexcept: """ Use eval_min and eval_scale to transform self.pt into evaluation space and store the result in self.eval_pt. @@ -153,7 +153,7 @@ cdef class VertexInfo: return '<{}, {}, {}>'.format(self.pt.x, self.pt.y, self.pt.z) -cdef mk_VertexInfo(double x, double y, double z, point_c *eval_min, point_c *eval_scale): +cdef mk_VertexInfo(double x, double y, double z, point_c *eval_min, point_c *eval_scale) noexcept: cdef VertexInfo v v = VertexInfo.__new__(VertexInfo) v.pt.x = x @@ -452,7 +452,7 @@ cdef class MarchingCubesTriangles(MarchingCubes): self.process_cubes(self.slices[0], self.slices[1]) - cpdef _update_yz_vertices(self, int x, np.ndarray _prev, np.ndarray _cur, np.ndarray _next): + cpdef _update_yz_vertices(self, int x, np.ndarray _prev, np.ndarray _cur, np.ndarray _next) noexcept: """ TESTS:: @@ -560,7 +560,7 @@ cdef class MarchingCubesTriangles(MarchingCubes): else: z_vertices[y,z] = None - cpdef _update_x_vertices(self, int x, np.ndarray _prev, np.ndarray _left, np.ndarray _right, np.ndarray _next): + cpdef _update_x_vertices(self, int x, np.ndarray _prev, np.ndarray _left, np.ndarray _right, np.ndarray _next) noexcept: """ TESTS:: @@ -635,10 +635,10 @@ cdef class MarchingCubesTriangles(MarchingCubes): else: x_vertices[y,z] = None - cdef bint in_region(self, VertexInfo v): + cdef bint in_region(self, VertexInfo v) noexcept: return (self.region(v.eval_pt.x, v.eval_pt.y, v.eval_pt.z) > 0) - cdef apply_point_func(self, point_c *pt, fn, VertexInfo v): + cdef apply_point_func(self, point_c *pt, fn, VertexInfo v) noexcept: if isinstance(fn, tuple): pt[0].x = fn[0](v.eval_pt.x, v.eval_pt.y, v.eval_pt.z) pt[0].y = fn[1](v.eval_pt.x, v.eval_pt.y, v.eval_pt.z) @@ -649,7 +649,7 @@ cdef class MarchingCubesTriangles(MarchingCubes): pt[0].y = t[1] pt[0].z = t[2] - cdef apply_color_func(self, color_c *pt, fn, cm, VertexInfo v): + cdef apply_color_func(self, color_c *pt, fn, cm, VertexInfo v) noexcept: t = fn(v.eval_pt.x, v.eval_pt.y, v.eval_pt.z) pt[0].r, pt[0].g, pt[0].b, _ = cm(t) @@ -659,7 +659,7 @@ cdef class MarchingCubesTriangles(MarchingCubes): double center, double lx, double ux, double ly, double uy, - double lz, double uz): + double lz, double uz) noexcept: # What a mess! It would be much nicer-looking code to pass slices # in here and do the subscripting in here. Unfortunately, # that would also be much slower, because we'd have to re-initialize @@ -684,7 +684,7 @@ cdef class MarchingCubesTriangles(MarchingCubes): g[0].y = gy g[0].z = gz - cpdef process_cubes(self, np.ndarray _left, np.ndarray _right): + cpdef process_cubes(self, np.ndarray _left, np.ndarray _right) noexcept: """ TESTS:: @@ -788,7 +788,7 @@ cdef class MarchingCubesTriangles(MarchingCubes): all_vertex_info[my_triangles[i+1]], all_vertex_info[my_triangles[i+2]]) - cpdef add_triangle(self, VertexInfo v1, VertexInfo v2, VertexInfo v3): + cpdef add_triangle(self, VertexInfo v1, VertexInfo v2, VertexInfo v3) noexcept: """ Called when a new triangle is generated by the marching cubes algorithm to update the results array. @@ -845,7 +845,7 @@ cdef class MarchingCubesTriangles(MarchingCubes): self.results.append(face) -cpdef render_implicit(f, xrange, yrange, zrange, plot_points, cube_marchers): +cpdef render_implicit(f, xrange, yrange, zrange, plot_points, cube_marchers) noexcept: """ INPUT: diff --git a/src/sage/plot/plot3d/index_face_set.pyx b/src/sage/plot/plot3d/index_face_set.pyx index 3968db3ab51..af5a9cfd32b 100644 --- a/src/sage/plot/plot3d/index_face_set.pyx +++ b/src/sage/plot/plot3d/index_face_set.pyx @@ -69,7 +69,7 @@ from .transform cimport Transformation # Fast routines for generating string representations of the polygons. # -------------------------------------------------------------------- -cdef inline format_tachyon_texture(color_c rgb): +cdef inline format_tachyon_texture(color_c rgb) noexcept: cdef char rs[200] cdef Py_ssize_t cr = sprintf_3d(rs, "TEXTURE\n AMBIENT 0.3 DIFFUSE 0.7 SPECULAR 0 OPACITY 1.0\n COLOR %g %g %g \n TEXFUNC 0", @@ -77,7 +77,7 @@ cdef inline format_tachyon_texture(color_c rgb): return bytes_to_str(PyBytes_FromStringAndSize(rs, cr)) -cdef inline format_tachyon_triangle(point_c P, point_c Q, point_c R): +cdef inline format_tachyon_triangle(point_c P, point_c Q, point_c R) noexcept: cdef char ss[250] # PyBytes_FromFormat doesn't do floats? cdef Py_ssize_t r = sprintf_9d(ss, @@ -88,22 +88,22 @@ cdef inline format_tachyon_triangle(point_c P, point_c Q, point_c R): return bytes_to_str(PyBytes_FromStringAndSize(ss, r)) -cdef inline format_json_vertex(point_c P): +cdef inline format_json_vertex(point_c P) noexcept: cdef char ss[100] cdef Py_ssize_t r = sprintf_3d(ss, '{"x":%g,"y":%g,"z":%g}', P.x, P.y, P.z) return bytes_to_str(PyBytes_FromStringAndSize(ss, r)) -cdef inline format_json_face(face_c face): +cdef inline format_json_face(face_c face) noexcept: s = "[{}]".format(",".join(str(face.vertices[i]) for i in range(face.n))) return s -cdef inline format_obj_vertex(point_c P): +cdef inline format_obj_vertex(point_c P) noexcept: cdef char ss[100] # PyBytes_FromFormat doesn't do floats? cdef Py_ssize_t r = sprintf_3d(ss, "v %g %g %g", P.x, P.y, P.z) return bytes_to_str(PyBytes_FromStringAndSize(ss, r)) -cdef inline format_obj_face(face_c face, int off): +cdef inline format_obj_face(face_c face, int off) noexcept: cdef char ss[100] cdef Py_ssize_t r, i if face.n == 3: @@ -115,7 +115,7 @@ cdef inline format_obj_face(face_c face, int off): # PyBytes_FromFormat is almost twice as slow return bytes_to_str(PyBytes_FromStringAndSize(ss, r)) -cdef inline format_obj_face_back(face_c face, int off): +cdef inline format_obj_face_back(face_c face, int off) noexcept: cdef char ss[100] cdef Py_ssize_t r, i if face.n == 3: @@ -126,13 +126,13 @@ cdef inline format_obj_face_back(face_c face, int off): return "f " + " ".join(str(face.vertices[i] + off) for i from face.n > i >= 0) return bytes_to_str(PyBytes_FromStringAndSize(ss, r)) -cdef inline format_pmesh_vertex(point_c P): +cdef inline format_pmesh_vertex(point_c P) noexcept: cdef char ss[100] # PyBytes_FromFormat doesn't do floats? cdef Py_ssize_t r = sprintf_3d(ss, "%g %g %g", P.x, P.y, P.z) return bytes_to_str(PyBytes_FromStringAndSize(ss, r)) -cdef inline format_pmesh_face(face_c face, int has_color): +cdef inline format_pmesh_face(face_c face, int has_color) noexcept: cdef char ss[100] cdef Py_ssize_t r, i cdef int color diff --git a/src/sage/plot/plot3d/parametric_surface.pyx b/src/sage/plot/plot3d/parametric_surface.pyx index 11676df7dfe..f62bc08b1a7 100644 --- a/src/sage/plot/plot3d/parametric_surface.pyx +++ b/src/sage/plot/plot3d/parametric_surface.pyx @@ -129,7 +129,7 @@ from sage.ext.interpreters.wrapper_rdf cimport Wrapper_rdf include "point_c.pxi" -cdef inline bint smash_edge(point_c* vs, face_c* f, int a, int b): +cdef inline bint smash_edge(point_c* vs, face_c* f, int a, int b) noexcept: if point_c_eq(vs[f.vertices[a]], vs[f.vertices[b]]): f.vertices[b] = f.vertices[a] f.n -= 1 diff --git a/src/sage/plot/plot3d/plot3d.py b/src/sage/plot/plot3d/plot3d.py index 5687c6f9c8c..fe8d4896426 100644 --- a/src/sage/plot/plot3d/plot3d.py +++ b/src/sage/plot/plot3d/plot3d.py @@ -10,17 +10,6 @@ sage: S = sphere((0, 0, 0), size=0.3, color='red', aspect_ratio=[1,1,1]) sage: show(W + S, figsize=8) -.. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - x, y = var('x y') - W = plot3d(sin(pi*((x)^2 + (y)^2))/2, (x, -1, 1), (y, -1, 1), frame=False, color='purple', opacity=0.8) - S = sphere((0, 0, 0), size=0.3, color='red', aspect_ratio=[1,1,1]) - show(W + S, figsize=8) - .. PLOT:: x, y = var('x y') @@ -36,17 +25,6 @@ ....: color=rainbow(60, 'rgbtuple'), max_bend=.1, max_depth=15) sage: P.show() -.. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - def f(x,y): - return math.sin(y^2 + x^2)/math.sqrt(x^2 + y^2 + 0.0001) - P = plot3d(f, (-3, 3), (-3, 3), adaptive=True, color=rainbow(60, 'rgbtuple'), max_bend=.1, max_depth=15) - P.show() - .. PLOT:: def f(x,y): return math.sin(y**2 + x**2)/math.sqrt(x**2 + y**2 + 0.0001) @@ -63,20 +41,6 @@ def f(x,y): return math.sin(y**2 + x**2)/math.sqrt(x**2 + y**2 + 0.0001) sage: S = P + axes(6, color='black') sage: S.show() -.. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - def f(x,y): - return math.exp(x/5)*math.sin(y) - - P = plot3d(f, (-5, 5), (-5, 5), adaptive=True, color=['red', 'yellow']) - from sage.plot.plot3d.plot3d import axes - S = P + axes(6, color='black') - S.show() - .. PLOT:: def f(x,y): return math.exp(x/5)*math.sin(y) @@ -93,17 +57,6 @@ def f(x,y): return math.exp(x/5)*math.sin(y) sage: plot3d(x*x + y*y, (x, -4, 4), (y, -4, 4), color=(c, cm)) Graphics3d Object -.. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - x, y = var('x y') - cm = colormaps.hsv - def c(x, y): return float((x + y + x*y)/15) % 1 - plot3d(x*x + y*y, (x, -4, 4), (y, -4, 4), color=(c, cm)) - .. PLOT:: x, y = var('x y') @@ -135,23 +88,6 @@ def c(x, y): return float((x + y + x*y)/15) % 1 sage: cape_man = P.scale(.2) + S.translate(1, 0, 0) sage: cape_man.show(aspect_ratio=[1, 1, 1]) -.. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - S = sphere(size=.5, color='yellow') - from sage.plot.plot3d.shapes import Cone - S += Cone(.5, .5, color='red').translate(0,0,.3) - S += sphere((.45, -.1, .15), size=.1, color='white') + sphere((.51,-.1,.17), size=.05, color='black') - S += sphere((.45, .1, .15), size=.1, color='white') + sphere((.51, .1,.17), size=.05, color='black') - S += sphere((.5, 0, -.2), size=.1, color='yellow') - def f(x,y): return math.exp(x/5)*math.cos(y) - P = plot3d(f, (-5, 5), (-5, 5), adaptive=True, color=['red','yellow'], max_depth=10) - cape_man = P.scale(.2) + S.translate(1, 0, 0) - cape_man.show(aspect_ratio=[1, 1, 1]) - .. PLOT:: S = sphere(size=.5, color='yellow') @@ -171,14 +107,6 @@ def f(x,y): return math.exp(x/5)*math.cos(y) sage: plot3d(pi, (-1,1), (-1,1)) Graphics3d Object -.. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - plot3d(pi, (-1,1), (-1,1)) - .. PLOT:: sphinx_plot(plot3d(pi, (-1,1), (-1,1))) @@ -577,16 +505,6 @@ class Spherical(_Coordinates): sage: plot3d(phi * theta, (theta, 0, pi), (phi, 0, 1), transformation=T) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - r, phi, theta = var('r phi theta') - T = Spherical('radius', ['azimuth', 'inclination']) - plot3d(phi * theta, (theta, 0, pi), (phi, 0, 1), transformation=T) - .. PLOT:: r, phi, theta = var('r phi theta') @@ -600,16 +518,6 @@ class Spherical(_Coordinates): sage: plot3d(3, (r,0,3), (theta, 0, 2*pi), transformation=S) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - S = Spherical('inclination', ['radius', 'azimuth']) - r, theta = var('r,theta') - plot3d(r-r+3, (r,0,3), (theta, 0, 2*pi), transformation=S) - .. PLOT:: S = Spherical('inclination', ['radius', 'azimuth']) @@ -666,16 +574,6 @@ class SphericalElevation(_Coordinates): sage: plot3d(phi * theta, (theta, 0, pi), (phi, 0, 1), transformation=T) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - T = SphericalElevation('radius', ['azimuth', 'elevation']) - r, theta, phi = var('r theta phi') - plot3d(phi * theta, (theta, 0, pi), (phi, 0, 1), transformation=T) - .. PLOT:: T = SphericalElevation('radius', ['azimuth', 'elevation']) @@ -688,24 +586,14 @@ class SphericalElevation(_Coordinates): sage: SE = SphericalElevation('elevation', ['radius', 'azimuth']) sage: r, theta = var('r,theta') - sage: plot3d(3, (r,0,3), (theta, 0, 2*pi), transformation=SE) + sage: plot3d(3, (r, 0, 3), (theta, 0, 2*pi), transformation=SE) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - SE = SphericalElevation('elevation', ['radius', 'azimuth']) - r, theta = var('r,theta') - plot3d(3+r-r, (r,0,3), (theta, 0, 2*pi), transformation=SE) - .. PLOT:: SE = SphericalElevation('elevation', ['radius', 'azimuth']) r, theta = var('r,theta') - sphinx_plot(plot3d(3+r-r, (r,0,3), (theta, 0, 2*pi), transformation=SE)) + sphinx_plot(plot3d(3 + r - r, (r,0,3), (theta, 0, 2*pi), transformation=SE)) Plot a sin curve wrapped around the equator:: @@ -715,24 +603,12 @@ class SphericalElevation(_Coordinates): sage: P1 + P2 Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - r, theta = var('r,theta') - SE = SphericalElevation('elevation', ['radius', 'azimuth']) - P1 = plot3d( (pi/12)*sin(8*theta), (r,0.99,1), (theta, 0, 2*pi), transformation=SE, plot_points=(10,200)) - P2 = sphere(center=(0,0,0), size=1, color='red', opacity=0.3) - P1 + P2 - .. PLOT:: r, theta = var('r,theta') SE = SphericalElevation('elevation', ['radius', 'azimuth']) - P1 = plot3d( (pi/12)*sin(8*theta), (r,0.99,1), (theta, 0, 2*pi), transformation=SE, plot_points=(10,200)) - P2 = sphere(center=(0,0,0), size=1, color='red', opacity=0.3) + P1 = plot3d( (pi/12)*sin(8*theta), (r, 0.99, 1), (theta, 0, 2*pi), transformation=SE, plot_points=(10,200)) + P2 = sphere(center=(0, 0, 0), size=1, color='red', opacity=0.3) sphinx_plot(P1 + P2) Now we graph several constant elevation functions alongside several constant @@ -753,23 +629,6 @@ class SphericalElevation(_Coordinates): ....: for a in angles] sage: show(sum(P1+P2), aspect_ratio=1) - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - r, phi, theta = var('r phi theta') - SE = SphericalElevation('elevation', ['radius', 'azimuth']) - S = Spherical('inclination', ['radius', 'azimuth']) - angles = [pi/18, pi/12, pi/6] - P1=Graphics() - P2=Graphics() - for a in angles: - P1 += plot3d( a, (r,0,3), (theta, 0, 2*pi), transformation=SE, opacity=0.85, color='blue') - P2 += plot3d( a, (r,0,3), (theta, 0, 2*pi), transformation=S, opacity=0.85, color='red') - P1+P2 - .. PLOT:: r, phi, theta = var('r phi theta') @@ -834,16 +693,6 @@ class Cylindrical(_Coordinates): sage: plot3d(9-r^2, (r, 0, 3), (theta, 0, pi), transformation=T) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - T = Cylindrical('height', ['radius', 'azimuth']) - r, theta, z = var('r theta z') - plot3d(9-r**2, (r, 0, 3), (theta, 0, pi), transformation=T) - .. PLOT:: T = Cylindrical('height', ['radius', 'azimuth']) @@ -857,21 +706,11 @@ class Cylindrical(_Coordinates): sage: plot3d(3, (theta, 0, 2*pi), (z, -2, 2), transformation=S) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - S = Cylindrical('radius', ['azimuth', 'height']) - theta, z = var('theta, z') - plot3d(3, (theta, 0, 2*pi), (z, -2, 2), transformation=S) - .. PLOT:: S = Cylindrical('radius', ['azimuth', 'height']) theta, z = var('theta, z') - sphinx_plot(plot3d(3+z-z, (theta, 0, 2*pi), (z, -2, 2), transformation=S)) + sphinx_plot(plot3d(3 + z - z, (theta, 0, 2*pi), (z, -2, 2), transformation=S)) See also :func:`cylindrical_plot3d` for more examples of plotting in cylindrical coordinates. @@ -1006,14 +845,6 @@ def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): sage: plot3d(lambda x, y: x^2 + y^2, (-2,2), (-2,2)) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - plot3d(lambda x, y: x**2 + y**2, (-2,2), (-2,2)) - .. PLOT:: sphinx_plot(plot3d(lambda x, y: x**2 + y**2, (-2,2), (-2,2))) @@ -1023,14 +854,6 @@ def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): sage: plot3d(lambda x, y: x^2 + y^2, (-2,2), (-2,2), adaptive=True) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - plot3d(lambda x, y: x**2 + y**2, (-2,2), (-2,2), adaptive=True) - .. PLOT:: sphinx_plot(plot3d(lambda x, y: x**2 + y**2, (-2,2), (-2,2), adaptive=True)) @@ -1040,14 +863,6 @@ def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): sage: plot3d(lambda x, y: x^2 + y^2, (-2,2), (-2,2), adaptive=True, initial_depth=5) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - plot3d(lambda x, y: x**2 + y**2, (-2,2), (-2,2), adaptive=True, initial_depth=5) - .. PLOT:: sphinx_plot(plot3d(lambda x, y: x**2 + y**2, (-2,2), (-2,2), adaptive=True, initial_depth=5)) @@ -1059,15 +874,6 @@ def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): sage: plot3d(x^2 + y^2, (x,-2,2), (y,-2,2)) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - var('x y') - plot3d(x**2 + y**2, (x,-2,2), (y,-2,2)) - .. PLOT:: var('x y') @@ -1078,15 +884,6 @@ def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): sage: plot3d(sin(x*y), (x, -pi, pi), (y, -pi, pi)) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - var('x y') - plot3d(sin(x*y), (x, -pi, pi), (y, -pi, pi)) - .. PLOT:: var('x y') @@ -1099,15 +896,6 @@ def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): sage: plot3d(sin(x^2 + y^2), (x,-5,5), (y,-5,5), plot_points=200) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - var('x y') - plot3d(sin(x^2 + y^2),(x,-5,5),(y,-5,5), plot_points=200) - .. PLOT:: var('x y') @@ -1118,15 +906,6 @@ def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): sage: plot3d(sin(x^2 + y^2), (x, -5, 5), (y, -5, 5), plot_points=[10, 100]) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - var('x y') - plot3d(sin(x^2 + y^2), (x, -5, 5), (y, -5, 5), plot_points=[10, 100]) - .. PLOT:: var('x y') @@ -1139,15 +918,6 @@ def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): sage: plot3d(sin(x - y)*y*cos(x), (x, -3, 3), (y, -3, 3), mesh=True) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - var('x,y') - plot3d(sin(x - y)*y*cos(x), (x, -3, 3), (y, -3, 3), mesh=True) - .. PLOT:: var('x y') @@ -1171,17 +941,6 @@ def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): sage: P + Q Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - x,y = var('x,y') - P = plot3d(x + y + sin(x*y), (x, -10, 10), (y, -10, 10), opacity=0.87, color='blue') - Q = plot3d(x - 2*y - cos(x*y),(x, -10, 10), (y, -10, 10), opacity=0.3, color='red') - P + Q - .. PLOT:: x,y = var('x,y') @@ -1197,17 +956,6 @@ def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): sage: L + P + Q Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - L = plot3d(lambda x,y: 0, (-5,5), (-5,5), color="lightblue", opacity=0.8) - P = plot3d(lambda x,y: 4 - x^3 - y^2, (-2,2), (-2,2), color='green') - Q = plot3d(lambda x,y: x^3 + y^2 - 4, (-2,2), (-2,2), color='orange') - L + P + Q - .. PLOT:: L = plot3d(lambda x,y: 0, (-5,5), (-5,5), color="lightblue", opacity=0.8) @@ -1221,15 +969,6 @@ def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): sage: plot3d(sin(pi*(x^2 + y^2))/2, (x, -1, 1), (y, -1, 1)) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - x, y = var('x y') - plot3d(sin(pi*(x^2 + y^2))/2, (x, -1, 1), (y, -1, 1)) - .. PLOT:: x, y = var('x y') @@ -1241,15 +980,6 @@ def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): sage: plot3d(4*x*exp(-x^2 - y^2), (x, -2, 2), (y, -2, 2)) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - x, y = var('x y') - plot3d(4*x*exp(-x^2 - y^2), (x, -2, 2), (y, -2, 2)) - .. PLOT:: x, y = var('x y') @@ -1261,16 +991,6 @@ def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): sage: trans = (r*cos(phi), r*sin(phi), z) sage: plot3d(cos(r), (r, 0, 17*pi/2), (phi, 0, 2*pi), transformation=trans, opacity=0.87).show(aspect_ratio=(1,1,2), frame=False) - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - r, phi, z = var('r phi z') - trans = (r*cos(phi), r*sin(phi), z) - plot3d(cos(r), (r, 0, 17*pi/2), (phi, 0, 2*pi), transformation=trans, opacity=0.87).show(aspect_ratio=(1,1,2), frame=False) - .. PLOT:: r, phi, z = var('r phi z') @@ -1285,16 +1005,6 @@ def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): sage: plot3d(3, (theta, 0, pi/2), (z, 0, pi/2), transformation=cylindrical) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - r, theta, z = var('r theta z') - cylindrical(r, theta, z) = [r*cos(theta), r*sin(theta), z] - plot3d(3, (theta, 0, pi/2), (z, 0, pi/2), transformation=cylindrical) - .. PLOT:: r, theta, z = var('r theta z') @@ -1420,30 +1130,28 @@ def plot3d_adaptive(f, x_range, y_range, color="automatic", INPUT: - - ``f`` -- a symbolic function or a Python function of - 3 variables. + - ``f`` -- a symbolic function or a Python function of 3 variables - - ``x_range`` -- x range of values: 2-tuple (xmin, + - ``x_range`` -- x range of values: 2-tuple (xmin, xmax) or 3-tuple (x,xmin,xmax) - - ``y_range`` -- y range of values: 2-tuple (ymin, - ymax) or 3-tuple (y,ymin,ymax) + - ``y_range`` -- y range of values: 2-tuple (ymin, ymax) or 3-tuple + (y,ymin,ymax) - - ``grad_f`` -- gradient of f as a Python function + - ``grad_f`` -- gradient of f as a Python function - - ``color`` -- "automatic" - a rainbow of num_colors - colors + - ``color`` -- "automatic" - a rainbow of num_colors colors - - ``num_colors`` -- (default: 128) number of colors to - use with default color + - ``num_colors`` -- (default: 128) number of colors to use with default + color - - ``max_bend`` -- (default: 0.5) + - ``max_bend`` -- (default: 0.5) - - ``max_depth`` -- (default: 5) + - ``max_depth`` -- (default: 5) - - ``initial_depth`` -- (default: 4) + - ``initial_depth`` -- (default: 4) - - ``**kwds`` -- standard graphics parameters + - ``**kwds`` -- standard graphics parameters EXAMPLES: @@ -1454,16 +1162,6 @@ def plot3d_adaptive(f, x_range, y_range, color="automatic", sage: plot3d_adaptive(sin(x*y), (x, -pi, pi), (y, -pi, pi), initial_depth=5) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - from sage.plot.plot3d.plot3d import plot3d_adaptive - x, y = var('x,y') - plot3d_adaptive(sin(x*y), (x, -pi, pi), (y, -pi, pi), initial_depth=5) - .. PLOT:: from sage.plot.plot3d.plot3d import plot3d_adaptive @@ -1559,15 +1257,6 @@ def spherical_plot3d(f, urange, vrange, **kwds): sage: spherical_plot3d(2, (x, 0, 2*pi), (y, 0, pi)) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - x,y = var('x,y') - spherical_plot3d(2, (x, 0, 2*pi), (y, 0, pi)) - .. PLOT:: x, y = var('x,y') @@ -1581,18 +1270,6 @@ def spherical_plot3d(f, urange, vrange, **kwds): sage: ima = spherical_plot3d(abs(imag(Y)), (phi, 0, 2*pi), (theta, 0, pi), color='red', opacity=0.6) sage: (rea + ima).show(aspect_ratio=1) # long time (4s on sage.math, 2011) - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - phi, theta = var('phi, theta') - Y = spherical_harmonic(2, 1, theta, phi) - rea = spherical_plot3d(abs(real(Y)), (phi, 0, 2*pi), (theta, 0, pi), color='blue', opacity=0.6) - ima = spherical_plot3d(abs(imag(Y)), (phi, 0, 2*pi), (theta, 0, pi), color='red', opacity=0.6) - (rea + ima).show(aspect_ratio=1) # long time (4s on sage.math, 2011) - .. PLOT:: phi, theta = var('phi, theta') @@ -1606,15 +1283,6 @@ def spherical_plot3d(f, urange, vrange, **kwds): sage: x,y = var('x,y') sage: spherical_plot3d(e^-y, (x, 0, 2*pi), (y, 0, pi), opacity=0.5).show(frame=False) - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - x,y = var('x,y') - spherical_plot3d(e^-y, (x, 0, 2*pi), (y, 0, pi), opacity=0.5).show(frame=False) - .. PLOT:: x, y = var('x,y') @@ -1626,15 +1294,6 @@ def spherical_plot3d(f, urange, vrange, **kwds): sage: spherical_plot3d((2 + cos(2*x))*(y + 1), (x, 0, 2*pi), (y, 0, pi), rgbcolor=(1, .1, .1)) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - x,y = var('x,y') - spherical_plot3d((2 + cos(2*x))*(y + 1), (x, 0, 2*pi), (y, 0, pi), rgbcolor=(1, .1, .1)) - .. PLOT:: x, y = var('x,y') @@ -1646,15 +1305,6 @@ def spherical_plot3d(f, urange, vrange, **kwds): sage: spherical_plot3d(1 + sin(5*x)/5, (x, 0, 2*pi), (y, 0, pi), rgbcolor=(1, 0.5, 0), plot_points=(80, 80), opacity=0.7) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - x,y = var('x,y') - spherical_plot3d(1 + sin(5*x)/5, (x, 0, 2*pi), (y, 0, pi), rgbcolor=(1, 0.5, 0), plot_points=(80, 80), opacity=0.7) - .. PLOT:: x,y = var('x,y') @@ -1665,15 +1315,6 @@ def spherical_plot3d(f, urange, vrange, **kwds): sage: x, y = var('x,y') sage: spherical_plot3d(1 + 2*cos(2*y), (x, 0, 3*pi/2), (y, 0, pi)).show(aspect_ratio=(1, 1, 1)) - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - x, y = var('x,y') - spherical_plot3d(1 + 2*cos(2*y), (x, 0, 3*pi/2), (y, 0, pi)).show(aspect_ratio=(1, 1, 1)) - .. PLOT:: x, y = var('x,y') @@ -1693,17 +1334,6 @@ def cylindrical_plot3d(f, urange, vrange, **kwds): sage: plot3d(f, urange, vrange, transformation=T) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - r, u, v = var('r,u,v') - f = u*v; urange = (u, 0, pi); vrange = (v, 0, pi) - T = (r*cos(u), r*sin(u), v, [u, v]) - plot3d(f, urange, vrange, transformation=T) - .. PLOT:: r, u, v = var('r,u,v') @@ -1737,15 +1367,6 @@ def cylindrical_plot3d(f, urange, vrange, **kwds): sage: cylindrical_plot3d(2, (theta, 0, 3*pi/2), (z, -2, 2)) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - theta, z = var('theta,z') - cylindrical_plot3d(2, (theta, 0, 3*pi/2), (z, -2, 2)) - .. PLOT:: theta, z = var('theta,z') @@ -1758,16 +1379,7 @@ def cylindrical_plot3d(f, urange, vrange, **kwds): sage: cylindrical_plot3d(cosh(z), (theta, 0, 2*pi), (z, -2, 2)) Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - theta, z = var('theta,z') - cylindrical_plot3d(cosh(z), (theta, 0, 2*pi), (z, -2, 2)) - - .. PLOT:: + .. PLOT:: theta, z = var('theta,z') sphinx_plot(cylindrical_plot3d(cosh(z), (theta, 0, 2*pi), (z, -2, 2))) @@ -1776,22 +1388,12 @@ def cylindrical_plot3d(f, urange, vrange, **kwds): sage: cylindrical_plot3d(e^(-z^2)*(cos(4*theta) + 2) + 1, (theta, 0, 2*pi), (z, -2, 2), plot_points=[80, 80]).show(aspect_ratio=(1, 1, 1)) - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - theta, z = var('theta,z') - cylindrical_plot3d(e^(-z^2)*(cos(4*theta) + 2) + 1, (theta, 0, 2*pi), (z, -2, 2), plot_points=[80, 80]).show(aspect_ratio=(1, 1, 1)) - - .. PLOT:: + .. PLOT:: theta, z = var('theta,z') P = cylindrical_plot3d(e**(-z**2)*(cos(4*theta) + 2) + 1, (theta, 0, 2*pi), (z, -2, 2), plot_points=[80, 80]) P.aspect_ratio([1, 1, 1]) sphinx_plot(P) - """ return plot3d(f, urange, vrange, transformation=Cylindrical('radius', ['azimuth', 'height']), **kwds) @@ -1802,9 +1404,10 @@ def axes(scale=1, radius=None, **kwds): INPUT: - - ``scale`` -- (default: 1) The length of the axes (all three - will be the same). - - ``radius`` -- (default: .01) The radius of the axes as arrows. + - ``scale`` -- (default: 1) the length of the axes (all three will be the + same) + + - ``radius`` -- (default: .01) the radius of the axes as arrows EXAMPLES:: @@ -1812,16 +1415,7 @@ def axes(scale=1, radius=None, **kwds): sage: S = axes(6, color='black'); S Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - from sage.plot.plot3d.plot3d import axes - S = axes(6, color='black'); S - - .. PLOT:: + .. PLOT:: from sage.plot.plot3d.plot3d import axes S = axes(6, color='black') @@ -1832,16 +1426,7 @@ def axes(scale=1, radius=None, **kwds): sage: T = axes(2, .5); T Graphics3d Object - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - from sage.plot.plot3d.plot3d import axes - T = axes(2, .5); T - - .. PLOT:: + .. PLOT:: from sage.plot.plot3d.plot3d import axes T = axes(2, .5) diff --git a/src/sage/plot/plot3d/point_c.pxi b/src/sage/plot/plot3d/point_c.pxi index aa6699d368e..ba9561ab18c 100644 --- a/src/sage/plot/plot3d/point_c.pxi +++ b/src/sage/plot/plot3d/point_c.pxi @@ -21,13 +21,13 @@ from libc cimport math cdef inline bint point_c_set(point_c* res, P) except -2: res.x, res.y, res.z = P[0], P[1], P[2] -cdef inline bint point_c_eq(point_c P, point_c Q): +cdef inline bint point_c_eq(point_c P, point_c Q) noexcept: return P.x == Q.x and P.y == Q.y and P.z == Q.z -cdef inline bint point_c_isfinite(point_c P): +cdef inline bint point_c_isfinite(point_c P) noexcept: return math.isfinite(P.x) and math.isfinite(P.y) and math.isfinite(P.z) -cdef inline int point_c_cmp(point_c P, point_c Q): +cdef inline int point_c_cmp(point_c P, point_c Q) noexcept: """ Lexographic order """ @@ -48,7 +48,7 @@ cdef inline int point_c_cmp(point_c P, point_c Q): else: return 1 -cdef inline void point_c_update_finite_lower_bound(point_c* res, point_c P): +cdef inline void point_c_update_finite_lower_bound(point_c* res, point_c P) noexcept: # We use the condition "not P.x > res.x" so that the condition returns True if res.x is NaN if math.isfinite(P.x) and not P.x > res.x: res.x = P.x @@ -57,7 +57,7 @@ cdef inline void point_c_update_finite_lower_bound(point_c* res, point_c P): if math.isfinite(P.z) and not P.z > res.z: res.z = P.z -cdef inline void point_c_update_finite_upper_bound(point_c* res, point_c P): +cdef inline void point_c_update_finite_upper_bound(point_c* res, point_c P) noexcept: # We use the condition "not P.x < res.x" so that the condition returns True if res.x is NaN if math.isfinite(P.x) and not P.x < res.x: res.x = P.x @@ -66,49 +66,49 @@ cdef inline void point_c_update_finite_upper_bound(point_c* res, point_c P): if math.isfinite(P.z) and not P.z < res.z: res.z = P.z -cdef inline void point_c_lower_bound(point_c* res, point_c P, point_c Q): +cdef inline void point_c_lower_bound(point_c* res, point_c P, point_c Q) noexcept: res.x = P.x if P.x < Q.x else Q.x res.y = P.y if P.y < Q.y else Q.y res.z = P.z if P.z < Q.z else Q.z -cdef inline void point_c_upper_bound(point_c* res, point_c P, point_c Q): +cdef inline void point_c_upper_bound(point_c* res, point_c P, point_c Q) noexcept: res.x = P.x if P.x > Q.x else Q.x res.y = P.y if P.y > Q.y else Q.y res.z = P.z if P.z > Q.z else Q.z -cdef inline void point_c_add(point_c* res, point_c P, point_c Q): +cdef inline void point_c_add(point_c* res, point_c P, point_c Q) noexcept: res.x = P.x + Q.x res.y = P.y + Q.y res.z = P.z + Q.z -cdef inline void point_c_sub(point_c* res, point_c P, point_c Q): +cdef inline void point_c_sub(point_c* res, point_c P, point_c Q) noexcept: res.x = P.x - Q.x res.y = P.y - Q.y res.z = P.z - Q.z -cdef inline void point_c_mul(point_c* res, point_c P, double a): +cdef inline void point_c_mul(point_c* res, point_c P, double a) noexcept: res.x = a * P.x res.y = a * P.y res.z = a * P.z -cdef inline double point_c_dot(point_c P, point_c Q): +cdef inline double point_c_dot(point_c P, point_c Q) noexcept: return P.x*Q.x + P.y*Q.y + P.z*Q.z -cdef inline void point_c_cross(point_c* res, point_c P, point_c Q): +cdef inline void point_c_cross(point_c* res, point_c P, point_c Q) noexcept: res.x = P.y * Q.z - P.z * Q.y res.y = P.z * Q.x - P.x * Q.z res.z = P.x * Q.y - P.y * Q.x -cdef inline double point_c_len(point_c P): +cdef inline double point_c_len(point_c P) noexcept: return math.sqrt(point_c_dot(P, P)) -cdef inline void point_c_middle(point_c* res, point_c P, point_c Q, double a): +cdef inline void point_c_middle(point_c* res, point_c P, point_c Q, double a) noexcept: cdef double b = 1 - a res.x = b * P.x + a * Q.x res.y = b * P.y + a * Q.y res.z = b * P.z + a * Q.z -cdef inline void point_c_transform(point_c* res, double* M, point_c P): +cdef inline void point_c_transform(point_c* res, double* M, point_c P) noexcept: """ M is a flattened 4x4 matrix, row major, representing an Euclidean Transformation. Operate on P as a point. @@ -117,7 +117,7 @@ cdef inline void point_c_transform(point_c* res, double* M, point_c P): res.y = M[4]*P.x + M[5]*P.y + M[6]*P.z + M[7] res.z = M[8]*P.x + M[9]*P.y + M[10]*P.z + M[11] -cdef inline void point_c_stretch(point_c* res, double* M, point_c P): +cdef inline void point_c_stretch(point_c* res, double* M, point_c P) noexcept: """ M is a flattened 4x4 matrix, row major, representing an Euclidean Transformation. Operate on P as a vector (i.e. ignore the translation component) @@ -126,20 +126,20 @@ cdef inline void point_c_stretch(point_c* res, double* M, point_c P): res.y = M[4]*P.x + M[5]*P.y + M[6]*P.z res.z = M[8]*P.x + M[9]*P.y + M[10]*P.z -cdef inline void face_c_normal(point_c* res, face_c face, point_c* vlist): +cdef inline void face_c_normal(point_c* res, face_c face, point_c* vlist) noexcept: cdef point_c e1, e2 point_c_sub(&e1, vlist[face.vertices[0]], vlist[face.vertices[1]]) point_c_sub(&e2, vlist[face.vertices[2]], vlist[face.vertices[1]]) point_c_cross(res, e1, e2) -cdef inline double cos_face_angle(face_c F, face_c E, point_c* vlist): +cdef inline double cos_face_angle(face_c F, face_c E, point_c* vlist) noexcept: cdef point_c nF, nE face_c_normal(&nF, F, vlist) face_c_normal(&nE, E, vlist) cdef double dot = point_c_dot(nF, nE) return dot / math.sqrt(point_c_dot(nF, nF)*point_c_dot(nE, nE)) -cdef inline double sin_face_angle(face_c F, face_c E, point_c* vlist): +cdef inline double sin_face_angle(face_c F, face_c E, point_c* vlist) noexcept: cdef point_c nF, nE face_c_normal(&nF, F, vlist) face_c_normal(&nE, E, vlist) diff --git a/src/sage/plot/plot3d/transform.pxd b/src/sage/plot/plot3d/transform.pxd index 1ae51ca9967..87695fc3d87 100644 --- a/src/sage/plot/plot3d/transform.pxd +++ b/src/sage/plot/plot3d/transform.pxd @@ -13,8 +13,8 @@ cdef class Transformation: cdef matrix cdef double _matrix_data[12] cdef object _svd - cpdef transform_point(self, x) - cpdef transform_vector(self, v) - cpdef transform_bounding_box(self, box) - cdef void transform_point_c(self, point_c* res, point_c P) - cdef void transform_vector_c(self, point_c* res, point_c P) + cpdef transform_point(self, x) noexcept + cpdef transform_vector(self, v) noexcept + cpdef transform_bounding_box(self, box) noexcept + cdef void transform_point_c(self, point_c* res, point_c P) noexcept + cdef void transform_vector_c(self, point_c* res, point_c P) noexcept diff --git a/src/sage/plot/plot3d/transform.pyx b/src/sage/plot/plot3d/transform.pyx index 5bff0d71ddc..fefbb26dede 100644 --- a/src/sage/plot/plot3d/transform.pyx +++ b/src/sage/plot/plot3d/transform.pyx @@ -75,19 +75,19 @@ cdef class Transformation: len_a = a.dot_product(a) return max([abs(len_a - b.dot_product(b)) for b in basis]) < eps - cpdef transform_point(self, x): + cpdef transform_point(self, x) noexcept: cdef point_c res, P P.x, P.y, P.z = x point_c_transform(&res, self._matrix_data, P) return res.x, res.y, res.z - cpdef transform_vector(self, v): + cpdef transform_vector(self, v) noexcept: cdef point_c res, P P.x, P.y, P.z = v point_c_stretch(&res, self._matrix_data, P) return res.x, res.y, res.z - cpdef transform_bounding_box(self, box): + cpdef transform_bounding_box(self, box) noexcept: cdef point_c lower, upper, res, temp cdef point_c bounds[2] bounds[0].x, bounds[0].y, bounds[0].z = box[0] @@ -105,10 +105,10 @@ cdef class Transformation: return (lower.x, lower.y, lower.z), (upper.x, upper.y, upper.z) - cdef void transform_point_c(self, point_c* res, point_c P): + cdef void transform_point_c(self, point_c* res, point_c P) noexcept: point_c_transform(res, self._matrix_data, P) - cdef void transform_vector_c(self, point_c* res, point_c P): + cdef void transform_vector_c(self, point_c* res, point_c P) noexcept: point_c_stretch(res, self._matrix_data, P) def __mul__(Transformation self, Transformation other): diff --git a/src/sage/quadratic_forms/binary_qf.py b/src/sage/quadratic_forms/binary_qf.py index c82a343a04e..6516888e3ac 100755 --- a/src/sage/quadratic_forms/binary_qf.py +++ b/src/sage/quadratic_forms/binary_qf.py @@ -910,7 +910,8 @@ def reduced_form(self, transformation=False, algorithm="default"): if algorithm == 'sage': if self.discriminant() <= 0: raise NotImplementedError('reduction of definite binary ' - 'quadratic forms is not implemented in Sage') + 'quadratic forms is not implemented ' + 'in Sage') return self._reduce_indef(transformation) elif algorithm == 'pari': @@ -1154,14 +1155,15 @@ def cycle(self, proper=False): if self.discriminant().is_square(): # Buchmann/Vollmer assume the discriminant to be non-square raise NotImplementedError('computation of cycles is only ' - 'implemented for non-square discriminants') + 'implemented for non-square ' + 'discriminants') if proper: # Prop 6.10.5 in Buchmann Vollmer C = list(self.cycle(proper=False)) # make a copy that we can modify if len(C) % 2: C += C - for i in range(len(C)//2): - C[2*i+1] = C[2*i+1]._Tau() + for i in range(len(C) // 2): + C[2 * i + 1] = C[2 * i + 1]._Tau() return C if not hasattr(self, '_cycle_list'): C = [self] diff --git a/src/sage/quadratic_forms/count_local_2.pyx b/src/sage/quadratic_forms/count_local_2.pyx index 3ce05a3a413..9b7d3e15178 100644 --- a/src/sage/quadratic_forms/count_local_2.pyx +++ b/src/sage/quadratic_forms/count_local_2.pyx @@ -87,7 +87,7 @@ def count_modp__by_gauss_sum(n, p, m, Qdet): return count -cdef CountAllLocalTypesNaive_cdef(Q, p, k, m, zvec, nzvec): +cdef CountAllLocalTypesNaive_cdef(Q, p, k, m, zvec, nzvec) noexcept: """ This Cython routine is documented in its Python wrapper method QuadraticForm.count_congruence_solutions_by_type(). @@ -181,7 +181,7 @@ def CountAllLocalTypesNaive(Q, p, k, m, zvec, nzvec): return CountAllLocalTypesNaive_cdef(Q, p, k, m, zvec, nzvec) -cdef local_solution_type_cdef(Q, p, w, zvec, nzvec): +cdef local_solution_type_cdef(Q, p, w, zvec, nzvec) noexcept: """ Internal routine to check if a given solution vector `w` (of `Q(w) = m` mod `p^k`) is of a certain local type and satisfies certain diff --git a/src/sage/quadratic_forms/genera/all.py b/src/sage/quadratic_forms/genera/all.py index 0b1889ba520..b1f48b5b8f6 100644 --- a/src/sage/quadratic_forms/genera/all.py +++ b/src/sage/quadratic_forms/genera/all.py @@ -1,9 +1,8 @@ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2007 David Kohel # # Distributed under the terms of the GNU General Public License (GPL) # -# http://www.gnu.org/licenses/ -#***************************************************************************** - +# https://www.gnu.org/licenses/ +# **************************************************************************** from .genus import Genus, LocalGenusSymbol, is_GlobalGenus diff --git a/src/sage/quadratic_forms/quadratic_form__automorphisms.py b/src/sage/quadratic_forms/quadratic_form__automorphisms.py index d0bf38f71a5..89b2c079478 100644 --- a/src/sage/quadratic_forms/quadratic_form__automorphisms.py +++ b/src/sage/quadratic_forms/quadratic_form__automorphisms.py @@ -115,7 +115,6 @@ def short_vector_list_up_to_length(self, len_bound, up_to_sign_flag=False): A list of lists of vectors such that entry `[i]` contains all vectors of length `i`. - EXAMPLES:: sage: Q = DiagonalQuadraticForm(ZZ, [1,3,5,7]) @@ -143,13 +142,13 @@ def short_vector_list_up_to_length(self, len_bound, up_to_sign_flag=False): [], [(0, 1, 0, 0)], [(1, 1, 0, 0), (1, -1, 0, 0), (2, 0, 0, 0)]] - sage: Q = QuadraticForm(matrix(6, [2, 1, 1, 1, -1, -1, 1, 2, 1, 1, -1, -1, 1, 1, 2, 0, -1, -1, 1, 1, 0, 2, 0, -1, -1, -1, -1, 0, 2, 1, -1, -1, -1, -1, 1, 2])) + sage: m6 = matrix(6, [2, 1, 1, 1, -1, -1, 1, 2, 1, 1, -1, -1, + ....: 1, 1, 2, 0, -1, -1, 1, 1, 0, 2, 0, -1, + ....: -1, -1, -1, 0, 2, 1, -1, -1, -1, -1, 1, 2]) + sage: Q = QuadraticForm(m6) sage: vs = Q.short_vector_list_up_to_length(8) sage: [len(vs[i]) for i in range(len(vs))] [1, 72, 270, 720, 936, 2160, 2214, 3600] - sage: vs = Q.short_vector_list_up_to_length(30) # long time (28s on sage.math, 2014) - sage: [len(vs[i]) for i in range(len(vs))] # long time - [1, 72, 270, 720, 936, 2160, 2214, 3600, 4590, 6552, 5184, 10800, 9360, 12240, 13500, 17712, 14760, 25920, 19710, 26064, 28080, 36000, 25920, 47520, 37638, 43272, 45900, 59040, 46800, 75600] The cases of ``len_bound < 2`` led to exception or infinite runtime before. diff --git a/src/sage/quadratic_forms/quadratic_form__count_local_2.py b/src/sage/quadratic_forms/quadratic_form__count_local_2.py index 999da6428de..b125d8d6840 100644 --- a/src/sage/quadratic_forms/quadratic_form__count_local_2.py +++ b/src/sage/quadratic_forms/quadratic_form__count_local_2.py @@ -68,9 +68,9 @@ def count_congruence_solutions_as_vector(self, p, k, m, zvec, nzvec): return CountAllLocalTypesNaive(self, p, k, m, zvec, nzvec) -##/////////////////////////////////////////// -##/// Front-ends for our counting routines // -##/////////////////////////////////////////// +# ////////////////////////////////////////// +# // Front-ends for our counting routines // +# ////////////////////////////////////////// def count_congruence_solutions(self, p, k, m, zvec, nzvec): r""" diff --git a/src/sage/quadratic_forms/quadratic_form__equivalence_testing.py b/src/sage/quadratic_forms/quadratic_form__equivalence_testing.py index 7b109b3dc01..148fcbd21f2 100644 --- a/src/sage/quadratic_forms/quadratic_form__equivalence_testing.py +++ b/src/sage/quadratic_forms/quadratic_form__equivalence_testing.py @@ -289,7 +289,7 @@ def has_equivalent_Jordan_decomposition_at_prime(self, other, p): # Check O'Meara's condition (ii) when appropriate if norm_list[i + 1] % (4 * norm_list[i]) == 0: if self_hasse_chain_list[i] * hilbert_symbol(norm_list[i] * other_chain_det_list[i], -self_chain_det_list[i], 2) \ - != other_hasse_chain_list[i] * hilbert_symbol(norm_list[i], -other_chain_det_list[i], 2): # Nipp conditions + != other_hasse_chain_list[i] * hilbert_symbol(norm_list[i], -other_chain_det_list[i], 2): # Nipp conditions return False # All tests passed for the prime 2. diff --git a/src/sage/quadratic_forms/quadratic_form__evaluate.pyx b/src/sage/quadratic_forms/quadratic_form__evaluate.pyx index 95e82e669dc..8a5aeafd831 100644 --- a/src/sage/quadratic_forms/quadratic_form__evaluate.pyx +++ b/src/sage/quadratic_forms/quadratic_form__evaluate.pyx @@ -44,7 +44,7 @@ def QFEvaluateVector(Q, v): return QFEvaluateVector_cdef(Q, v) -cdef QFEvaluateVector_cdef(Q, v): +cdef QFEvaluateVector_cdef(Q, v) noexcept: r""" Routine to quickly evaluate a quadratic form `Q` on a vector `v`. See the Python wrapper function :meth:`QFEvaluate` above for details. @@ -111,7 +111,7 @@ def QFEvaluateMatrix(Q, M, Q2): return QFEvaluateMatrix_cdef(Q, M, Q2) -cdef QFEvaluateMatrix_cdef(Q, M, Q2): +cdef QFEvaluateMatrix_cdef(Q, M, Q2) noexcept: r""" Routine to quickly evaluate a quadratic form `Q` on a matrix `M`. See the Python wrapper function :func:`QFEvaluateMatrix` above for details. diff --git a/src/sage/quadratic_forms/quadratic_form__local_field_invariants.py b/src/sage/quadratic_forms/quadratic_form__local_field_invariants.py index 35f64198113..aff8dad2d62 100644 --- a/src/sage/quadratic_forms/quadratic_form__local_field_invariants.py +++ b/src/sage/quadratic_forms/quadratic_form__local_field_invariants.py @@ -5,7 +5,7 @@ quadratic forms over the rationals. """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2007 William Stein and Jonathan Hanke # Copyright (C) 2015 Jeroen Demeyer # @@ -13,8 +13,8 @@ # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. -# http://www.gnu.org/licenses/ -#***************************************************************************** +# https://www.gnu.org/licenses/ +# **************************************************************************** ########################################################################### # TO DO: Add routines for hasse invariants at all places, anisotropic diff --git a/src/sage/quadratic_forms/quadratic_form__mass.py b/src/sage/quadratic_forms/quadratic_form__mass.py index 11b581b1dd7..67bf06d888a 100644 --- a/src/sage/quadratic_forms/quadratic_form__mass.py +++ b/src/sage/quadratic_forms/quadratic_form__mass.py @@ -7,27 +7,27 @@ # Import all general mass finding routines from sage.quadratic_forms.quadratic_form__mass__Siegel_densities import \ - mass__by_Siegel_densities, \ - Pall_mass_density_at_odd_prime, \ - Watson_mass_at_2, \ - Kitaoka_mass_at_2, \ - mass_at_two_by_counting_mod_power + mass__by_Siegel_densities, \ + Pall_mass_density_at_odd_prime, \ + Watson_mass_at_2, \ + Kitaoka_mass_at_2, \ + mass_at_two_by_counting_mod_power from sage.quadratic_forms.quadratic_form__mass__Conway_Sloane_masses import \ - parity, \ - is_even, \ - is_odd, \ - conway_species_list_at_odd_prime, \ - conway_species_list_at_2, \ - conway_octane_of_this_unimodular_Jordan_block_at_2, \ - conway_diagonal_factor, \ - conway_cross_product_doubled_power, \ - conway_type_factor, \ - conway_p_mass, \ - conway_standard_p_mass, \ - conway_standard_mass, \ - conway_mass -# conway_generic_mass, \ -# conway_p_mass_adjustment + parity, \ + is_even, \ + is_odd, \ + conway_species_list_at_odd_prime, \ + conway_species_list_at_2, \ + conway_octane_of_this_unimodular_Jordan_block_at_2, \ + conway_diagonal_factor, \ + conway_cross_product_doubled_power, \ + conway_type_factor, \ + conway_p_mass, \ + conway_standard_p_mass, \ + conway_standard_mass, \ + conway_mass +# conway_generic_mass, \ +# conway_p_mass_adjustment ################################################### diff --git a/src/sage/quadratic_forms/quadratic_form__neighbors.py b/src/sage/quadratic_forms/quadratic_form__neighbors.py index 94f6559d51a..fb781e20122 100644 --- a/src/sage/quadratic_forms/quadratic_form__neighbors.py +++ b/src/sage/quadratic_forms/quadratic_form__neighbors.py @@ -389,8 +389,7 @@ def orbits_lines_mod_p(self, p): # but in gap we act from the right!! --> transpose gens = self.automorphism_group().gens() gens = [g.matrix().transpose().change_ring(GF(p)) for g in gens] - orbs = libgap.function_factory( - """function(gens, p) + orbs = libgap.function_factory("""function(gens, p) local one, G, reps, V, n, orb; one:= One(GF(p)); G:=Group(List(gens, g -> g*one)); diff --git a/src/sage/quadratic_forms/quadratic_form__siegel_product.py b/src/sage/quadratic_forms/quadratic_form__siegel_product.py index c439a93f33b..b481f5ad073 100644 --- a/src/sage/quadratic_forms/quadratic_form__siegel_product.py +++ b/src/sage/quadratic_forms/quadratic_form__siegel_product.py @@ -97,12 +97,13 @@ def siegel_product(self, u): verbose(" u = " + str(u) + "\n") # Make the odd generic factors - if ((n % 2) == 1): - m = (n-1) // 2 + if n % 2: + m = (n - 1) // 2 d1 = fundamental_discriminant(((-1)**m) * 2*d * u) # Replaced d by 2d here to compensate for the determinant - f = abs(d1) # gaining an odd power of 2 by using the matrix of 2Q instead - # of the matrix of Q. - # --> Old d1 = CoreDiscriminant((mpz_class(-1)^m) * d * u); + f = abs(d1) + # gaining an odd power of 2 by using the matrix of 2Q instead + # of the matrix of Q. + # --> Old d1 = CoreDiscriminant((mpz_class(-1)^m) * d * u); # Make the ratio of factorials factor: [(2m)! / m!] * prod_{i=1}^m (2*i-1) factor1 = 1 diff --git a/src/sage/quadratic_forms/quadratic_form__split_local_covering.py b/src/sage/quadratic_forms/quadratic_form__split_local_covering.py index 61f8c1a027f..4db788e5e44 100644 --- a/src/sage/quadratic_forms/quadratic_form__split_local_covering.py +++ b/src/sage/quadratic_forms/quadratic_form__split_local_covering.py @@ -14,8 +14,6 @@ from sage.rings.real_double import RDF from sage.matrix.matrix_space import MatrixSpace from sage.matrix.constructor import matrix -from sage.misc.lazy_import import lazy_import -lazy_import("sage.functions.all", "floor") from sage.rings.integer_ring import ZZ from sage.arith.misc import GCD @@ -94,19 +92,19 @@ def cholesky_decomposition(self, bit_prec=53): # 2. Loop on i for i in range(n): - for j in range(i+1, n): - Q[j,i] = Q[i,j] # Is this line redundant? - Q[i,j] = Q[i,j] / Q[i,i] + for j in range(i + 1, n): + Q[j, i] = Q[i, j] # Is this line redundant? + Q[i, j] = Q[i, j] / Q[i, i] # 3. Main Loop - for k in range(i+1, n): + for k in range(i + 1, n): for l in range(k, n): - Q[k,l] = Q[k,l] - Q[k,i] * Q[i,l] + Q[k, l] = Q[k, l] - Q[k, i] * Q[i, l] # 4. Zero out the strictly lower-triangular entries for i in range(n): for j in range(i): - Q[i,j] = 0 + Q[i, j] = 0 return Q @@ -178,7 +176,7 @@ def vectors_by_length(self, bound): # but if eps is too small, roundoff errors may knock off some # vectors of norm = bound (see #7100) eps = RDF(1e-6) - bound = ZZ(floor(max(bound, 0))) + bound = ZZ(max(bound, 0)) # bound is an integer Theta_Precision = bound + eps n = self.dim() @@ -192,7 +190,7 @@ def vectors_by_length(self, bound): # 1. Initialize T = n * [RDF(0)] # Note: We index the entries as 0 --> n-1 U = n * [RDF(0)] - i = n-1 + i = n - 1 T[i] = RDF(Theta_Precision) U[i] = RDF(0) @@ -201,27 +199,27 @@ def vectors_by_length(self, bound): # 2. Compute bounds Z = (T[i] / Q[i][i]).sqrt(extend=False) - L[i] = ( Z - U[i]).floor() + L[i] = (Z - U[i]).floor() x[i] = (-Z - U[i]).ceil() done_flag = False - Q_val = 0 # WARNING: Still need a good way of checking overflow for this value... + Q_val = 0 # WARNING: Still need a good way of checking overflow for this value... # Big loop which runs through all vectors while not done_flag: # 3b. Main loop -- try to generate a complete vector x (when i=0) while (i > 0): - T[i-1] = T[i] - Q[i][i] * (x[i] + U[i]) * (x[i] + U[i]) + T[i - 1] = T[i] - Q[i][i] * (x[i] + U[i]) * (x[i] + U[i]) i = i - 1 U[i] = 0 - for j in range(i+1, n): + for j in range(i + 1, n): U[i] = U[i] + Q[i][j] * x[j] # Now go back and compute the bounds... # 2. Compute bounds Z = (T[i] / Q[i][i]).sqrt(extend=False) - L[i] = ( Z - U[i]).floor() + L[i] = (Z - U[i]).floor() x[i] = (-Z - U[i]).ceil() # carry if we go out of bounds -- when Z is so small that @@ -241,20 +239,20 @@ def vectors_by_length(self, bound): print(" Float = ", Q_val_double, " Long = ", Q_val) raise RuntimeError("The roundoff error is bigger than 0.001, so we should use more precision somewhere...") - if (Q_val <= bound): + if Q_val <= bound: theta_vec[Q_val].append(deepcopy(x)) # 5. Check if x = 0, for exit condition. =) j = 0 done_flag = True - while (j < n): - if (x[j] != 0): + while j < n: + if x[j] != 0: done_flag = False j += 1 # 3a. Increment (and carry if we go out of bounds) x[i] += 1 - while (x[i] > L[i]) and (i < n-1): + while i < n - 1 and x[i] > L[i]: i += 1 x[i] += 1 @@ -284,7 +282,6 @@ def complementary_subform_to_vector(self, v): OUTPUT: a :class:`QuadraticForm` over `\ZZ` - EXAMPLES:: sage: Q1 = DiagonalQuadraticForm(ZZ, [1,3,5,7]) @@ -317,7 +314,7 @@ def complementary_subform_to_vector(self, v): # Find the first non-zero component of v, and call it nz (Note: 0 <= nz < n) nz = 0 - while (nz < n) and (v[nz] == 0): + while nz < n and v[nz] == 0: nz += 1 # Abort if v is the zero vector @@ -334,27 +331,27 @@ def complementary_subform_to_vector(self, v): d = Q1[0, 0] # For each row/column, perform elementary operations to cancel them out. - for i in range(1,n): + for i in range(1, n): # Check if the (i,0)-entry is divisible by d, # and stretch its row/column if not. - if Q1[i,0] % d != 0: - Q1 = Q1.multiply_variable(d / GCD(d, Q1[i, 0]//2), i) + if Q1[i, 0] % d: + Q1 = Q1.multiply_variable(d / GCD(d, Q1[i, 0] // 2), i) # Now perform the (symmetric) elementary operations to cancel out the (i,0) entries/ - Q1 = Q1.add_symmetric(-(Q1[i,0]/2) / (GCD(d, Q1[i,0]//2)), i, 0) + Q1 = Q1.add_symmetric(-(Q1[i, 0] // 2) / (GCD(d, Q1[i, 0] // 2)), i, 0) # Check that we're done! done_flag = True for i in range(1, n): - if Q1[0,i] != 0: + if Q1[0, i] != 0: done_flag = False if not done_flag: raise RuntimeError("There is a problem cancelling out the matrix entries! =O") # Return the complementary matrix - return Q1.extract_variables(range(1,n)) + return Q1.extract_variables(range(1, n)) def split_local_cover(self): diff --git a/src/sage/quadratic_forms/quadratic_form__ternary_Tornaria.py b/src/sage/quadratic_forms/quadratic_form__ternary_Tornaria.py index 6ec8bd8022f..cc7a6549312 100644 --- a/src/sage/quadratic_forms/quadratic_form__ternary_Tornaria.py +++ b/src/sage/quadratic_forms/quadratic_form__ternary_Tornaria.py @@ -89,23 +89,23 @@ def content(self): # in quadratic_form.py -#def is_primitive(self): -# """ -# Checks if the form is a multiple of another form... only over ZZ for now. -# """ -# return self.content() == 1 +# def is_primitive(self): +# """ +# Checks if the form is a multiple of another form... only over ZZ for now. +# """ +# return self.content() == 1 # in quadratic_form.py -#def primitive(self): -# """ -# Return a primitive quadratic forms in the similarity class of the given form. +# def primitive(self): +# """ +# Return a primitive quadratic forms in the similarity class of the given form. # -# This only works when we have GCDs... so over ZZ. -# """ -# c=self.content() -# new_coeffs = [self.base_ring()(a/c) for a in self.__coeffs] -# return QuadraticForm(self.base_ring(), self.dim(), new_coeffs) +# This only works when we have GCDs... so over ZZ. +# """ +# c = self.content() +# new_coeffs = [self.base_ring()(a/c) for a in self.__coeffs] +# return QuadraticForm(self.base_ring(), self.dim(), new_coeffs) def adjoint(self): @@ -155,14 +155,14 @@ def antiadjoint(self): ... ValueError: not an adjoint """ + n = self.dim() + R = self.base_ring() try: - n = self.dim() - R = self.base_ring() - d = R(self.disc()**(ZZ(1)/(n-1))) + d = R(self.disc()**(ZZ.one() / (n - 1))) if is_odd(n): - return self.adjoint().scale_by_factor( R(1) / 4 / d**(n-2) ) + return self.adjoint().scale_by_factor(R.one() / 4 / d**(n - 2)) else: - return self.adjoint().scale_by_factor( R(1) / d**(n-2) ) + return self.adjoint().scale_by_factor(R.one() / d**(n - 2)) except TypeError: raise ValueError("not an adjoint") @@ -189,6 +189,7 @@ def is_adjoint(self) -> bool: def reciprocal(self): r""" This gives the reciprocal quadratic form associated to the given form. + This is defined as the multiple of the primitive adjoint with the same content as the given form. @@ -207,14 +208,13 @@ def reciprocal(self): [ * * 37 ] sage: Q.reciprocal().reciprocal() == Q True - """ - return self.adjoint().primitive() . scale_by_factor( self.content() ) + return self.adjoint().primitive() . scale_by_factor(self.content()) def omega(self): r""" - This is the content of the adjoint of the primitive associated quadratic form. + Return the content of the adjoint of the primitive associated quadratic form. Ref: See Dickson's "Studies in Number Theory". @@ -223,15 +223,15 @@ def omega(self): sage: Q = DiagonalQuadraticForm(ZZ, [1,1,37]) sage: Q.omega() 4 - """ return self.primitive().adjoint().content() def delta(self): r""" - This is the omega of the adjoint form, - which is the same as the omega of the reciprocal form. + Return the omega of the adjoint form. + + This is the same as the omega of the reciprocal form. EXAMPLES:: @@ -244,15 +244,16 @@ def delta(self): def level__Tornaria(self): r""" - Return the level of the quadratic form, - defined as + Return the level of the quadratic form. + + This is defined as - level(`B`) for even dimension, - level(`B`)/4 for odd dimension, where `2Q(x) = x^t\cdot B\cdot x`. - This agrees with the usual level for even dimension... + This agrees with the usual level for even dimension. EXAMPLES:: @@ -265,7 +266,7 @@ def level__Tornaria(self): sage: DiagonalQuadraticForm(ZZ, [1,1,1,1]).level__Tornaria() 4 """ - return self.base_ring()(abs(self.disc())/self.omega()/self.content()**self.dim()) + return self.base_ring()(abs(self.disc()) / self.omega() / self.content()**self.dim()) def discrec(self): @@ -289,7 +290,9 @@ def discrec(self): def hasse_conductor(self): """ - This is the product of all primes where the Hasse invariant equals `-1` + Return the Hasse conductor. + + This is the product of all primes where the Hasse invariant equals `-1`. EXAMPLES:: @@ -307,14 +310,16 @@ def hasse_conductor(self): sage: QuadraticForm(ZZ, 3, [2, -2, 0, 2, 0, 5]).hasse_conductor() # needs sage.libs.pari 10 """ - return prod([x[0] for x in factor(2 * self.level()) - if self.hasse_invariant(x[0]) == -1]) + return prod([x for x, _ in factor(2 * self.level()) + if self.hasse_invariant(x) == -1]) def clifford_invariant(self, p): """ - This is the Clifford invariant, i.e. the class in the Brauer group of the - Clifford algebra for even dimension, of the even Clifford Algebra for odd dimension. + Return the Clifford invariant. + + This is the class in the Brauer group of the Clifford algebra for + even dimension, of the even Clifford Algebra for odd dimension. See Lam (AMS GSM 67) p. 117 for the definition, and p. 119 for the formula relating it to the Hasse invariant. @@ -348,7 +353,7 @@ def clifford_invariant(self, p): def clifford_conductor(self): """ - This is the product of all primes where the Clifford invariant is `-1` + Return the product of all primes where the Clifford invariant is `-1`. .. NOTE:: @@ -385,15 +390,15 @@ def clifford_conductor(self): sage: (H + H + H + H).clifford_conductor() 1 """ - return prod([x[0] for x in factor(2 * self.level()) - if self.clifford_invariant(x[0]) == -1]) + return prod([x for x, _ in factor(2 * self.level()) + if self.clifford_invariant(x) == -1]) # Genus theory def basiclemma(self, M): """ - Find a number represented by self and coprime to `M`. + Find a number represented by ``self`` and coprime to `M`. EXAMPLES:: @@ -423,24 +428,24 @@ def basiclemmavec(self, M): mod = [] M0 = abs(M) if M0 == 1: - return V(0) + return V.zero() for i in range(self.dim()): - M1 = prime_to_m_part(M0, self[i,i]) + M1 = prime_to_m_part(M0, self[i, i]) if M1 != 1: vec.append(V.gen(i)) mod.append(M1) - M0 = M0/M1 + M0 = M0 / M1 if M0 == 1: return tuple(CRT_vectors(vec, mod)) for i in range(self.dim()): for j in range(i): - M1 = prime_to_m_part(M0, self[i,j]) + M1 = prime_to_m_part(M0, self[i, j]) if M1 != 1: vec.append(V.i + V.j) mod.append(M1) - M0 = M0/M1 + M0 = M0 / M1 if M0 == 1: return tuple(CRT_vectors(vec, mod)) @@ -479,7 +484,7 @@ def xi(self, p): return kronecker_symbol(self.basiclemma(p), p) -def xi_rec(self,p): +def xi_rec(self, p): """ Return Xi(`p`) for the reciprocal form. diff --git a/src/sage/quadratic_forms/quadratic_form__theta.py b/src/sage/quadratic_forms/quadratic_form__theta.py index 7aa257d5e71..c4f0606df4c 100644 --- a/src/sage/quadratic_forms/quadratic_form__theta.py +++ b/src/sage/quadratic_forms/quadratic_form__theta.py @@ -28,8 +28,8 @@ def theta_series(self, Max=10, var_str='q', safe_flag=True): The ``safe_flag`` allows us to select whether we want a copy of the output, or the original output. It is only meaningful when a vector is returned, otherwise a copy is automatically made in - creating the power series. By default ``safe_flag`` = True, so we - return a copy of the cached information. If this is set to False, + creating the power series. By default ``safe_flag`` = ``True``, so we + return a copy of the cached information. If this is set to ``False``, then the routine is much faster but the return values are vulnerable to being corrupted by the user. @@ -58,17 +58,17 @@ def theta_series(self, Max=10, var_str='q', safe_flag=True): except TypeError: M = -1 - if (Max not in ['mod_form']) and (not M >= 0): + if Max not in ['mod_form'] and not M >= 0: raise TypeError("Max = {Max} is not an integer >= 0 or an allowed string") if Max == 'mod_form': raise NotImplementedError("we have to figure out the correct number of Fourier coefficients to use") - #return self.theta_by_pari(sturm_bound(self.level(), self.dim() / ZZ(2)) + 1, var_str, safe_flag) + # return self.theta_by_pari(sturm_bound(self.level(), self.dim() / ZZ(2)) + 1, var_str, safe_flag) else: return self.theta_by_pari(M, var_str, safe_flag) -# ------------- Compute the theta function by using the PARI/GP routine qfrep ------------ +# ---- Compute the theta function by using the PARI/GP routine qfrep ---- def theta_by_pari(self, Max, var_str='q', safe_flag=True): r""" @@ -169,22 +169,21 @@ def theta_by_cholesky(self, q_prec): sage: Theta_list = Theta.list() sage: [m for m in range(len(Theta_list)) if Theta_list[m] == 0] [2, 22] - """ # RAISE AN ERROR -- This routine is deprecated! - #raise NotImplementedError, "This routine is deprecated. Try theta_series(), which uses theta_by_pari()." + # raise NotImplementedError("This routine is deprecated. Try theta_series(), which uses theta_by_pari().") from sage.arith.misc import integer_ceil as ceil, integer_floor as floor from sage.misc.functional import sqrt from sage.rings.real_mpfr import RealField n = self.dim() - theta = [0 for i in range(q_prec+1)] + theta = [0 for i in range(q_prec + 1)] PS = PowerSeriesRing(ZZ, 'q') bit_prec = 53 # TO DO: Set this precision to reflect the appropriate roundoff Cholesky = self.cholesky_decomposition(bit_prec) # error estimate, to be confident through our desired q-precision. - Q = Cholesky # <---- REDUNDANT!!! + Q = Cholesky # <---- REDUNDANT!!! R = RealField(bit_prec) half = R(0.5) @@ -198,17 +197,14 @@ def theta_by_cholesky(self, q_prec): x = [0] * n # 2. Compute bounds - #Z = sqrt(T[i] / Q[i,i]) # IMPORTANT NOTE: sqrt preserves the precision of the real number it's given... which is not so good... =| - #L[i] = floor(Z - U[i]) # Note: This is a Sage Integer - #x[i] = ceil(-Z - U[i]) - 1 # Note: This is a Sage Integer too + # Z = sqrt(T[i] / Q[i,i]) # IMPORTANT NOTE: sqrt preserves the precision of the real number it's given... which is not so good... =| + # L[i] = floor(Z - U[i]) # Note: This is a Sage Integer + # x[i] = ceil(-Z - U[i]) - 1 # Note: This is a Sage Integer too done_flag = False from_step4_flag = False from_step3_flag = True # We start by pretending this, since then we get to run through 2 and 3a once. =) - #double Q_val_double; - #unsigned long Q_val; // WARNING: Still need a good way of checking overflow for this value... - # Big loop which runs through all vectors while not done_flag: @@ -221,18 +217,18 @@ def theta_by_cholesky(self, q_prec): else: # 2. Compute bounds from_step3_flag = False - Z = sqrt(T[i] / Q[i,i]) + Z = sqrt(T[i] / Q[i, i]) L[i] = floor(Z - U[i]) x[i] = ceil(-Z - U[i]) - 1 # 3a. Main loop x[i] += 1 - while (x[i] > L[i]): + while x[i] > L[i]: i += 1 x[i] += 1 # 3b. Main loop - if (i > 0): + if i > 0: from_step3_flag = True T[i - 1] = T[i] - Q[i, i] * (x[i] + U[i]) * (x[i] + U[i]) i += -1 @@ -249,9 +245,9 @@ def theta_by_cholesky(self, q_prec): eps = 0.000000001 if abs(Q_val_double - Q_val) > eps: raise RuntimeError("Oh No! We have a problem with the floating point precision... \n" - + " Q_val_double = " + str(Q_val_double) + "\n" - + " Q_val = " + str(Q_val) + "\n" - + " x = " + str(x) + "\n") + + " Q_val_double = " + str(Q_val_double) + "\n" + + " Q_val = " + str(Q_val) + "\n" + + " x = " + str(x) + "\n") if Q_val <= q_prec: theta[Q_val] += 2 @@ -333,18 +329,18 @@ def theta_series_degree_2(Q, prec): max = (X + 1) // 4 v_list = (Q.vectors_by_length(max)) # assume a>0 v_list = [[V(_) for _ in vs] for vs in v_list] # coerce vectors into V - verbose("Computed vectors_by_length" , t) + verbose("Computed vectors_by_length", t) # Deal with the singular part - coeffs = {(0,0,0):ZZ(1)} - for i in range(1,max+1): - coeffs[(0,0,i)] = ZZ(2) * len(v_list[i]) + coeffs = {(0, 0, 0): ZZ.one()} + for i in range(1, max + 1): + coeffs[(0, 0, i)] = ZZ(2) * len(v_list[i]) # Now deal with the non-singular part - a_max = int(floor(sqrt(X/3))) + a_max = int(floor(sqrt(X / 3))) for a in range(1, a_max + 1): t = cputime() - c_max = int(floor((a*a + X)/(4*a))) + c_max = int(floor((a * a + X) / (4 * a))) for c in range(a, c_max + 1): for v1 in v_list[a]: v1_H = v1 * H @@ -353,10 +349,10 @@ def B_v1(v): return v1_H * v2 for v2 in v_list[c]: b = abs(B_v1(v2)) - if b <= a and 4*a*c-b*b <= X: - qf = (a,b,c) + if b <= a and 4 * a * c - b * b <= X: + qf = (a, b, c) count = ZZ(4) if b == 0 else ZZ(2) - coeffs[qf] = coeffs.get(qf, ZZ(0)) + count + coeffs[qf] = coeffs.get(qf, ZZ.zero()) + count verbose("done a = %d" % a, t) return coeffs diff --git a/src/sage/quadratic_forms/ternary.pyx b/src/sage/quadratic_forms/ternary.pyx index ddcfbfdb6a9..28dd9514c30 100644 --- a/src/sage/quadratic_forms/ternary.pyx +++ b/src/sage/quadratic_forms/ternary.pyx @@ -67,23 +67,31 @@ def _reduced_ternary_form_eisenstein_with_matrix(a1, a2, a3, a23, a13, a12): sage: Q(M) == Qr True """ - M = identity_matrix(3) + # M = identity_matrix(3) + # M = matrix(ZZ, 3, [m11, m12, m13, m21, m22, m23, m31, m32, m33]) + m11, m12, m13, m21, m22, m23, m31, m32, m33 = 1, 0, 0, 0, 1, 0, 0, 0, 1 loop = True while loop: # adjust - v = a1+a2+a23+a13+a12 - if v < 0: - M *= matrix(ZZ, 3, [1, 0, 1, 0, 1, 1, 0, 0, 1]) + v = a1 + a2 + a23 + a13 + a12 + if (v < 0): + # M *= matrix(ZZ, 3, [1, 0, 1, 0, 1, 1, 0, 0, 1]) + [m13] = [m11 + m12 + m13] + [m23] = [m21 + m22 + m23] + [m33] = [m31 + m32 + m33] a3 += v - a23 += a12+2*a2 - a13 += a12+2*a1 + a23 += a12 + 2*a2 + a13 += a12 + 2*a1 # cuadred 12 m = red_mfact(a1, a12) - M *= matrix(ZZ, 3, [1, m, 0, 0, 1, 0, 0, 0, 1]) + # M *= matrix(ZZ, 3, [1, m, 0, 0, 1, 0, 0, 0, 1]) + [m12] = [m*m11 + m12] + [m22] = [m*m21 + m22] + [m32] = [m*m31 + m32] t = a1*m a12 += t a2 += a12*m @@ -92,7 +100,10 @@ def _reduced_ternary_form_eisenstein_with_matrix(a1, a2, a3, a23, a13, a12): # cuadred 23 m = red_mfact(a2, a23) - M *= matrix(ZZ, 3, [1, 0, 0, 0, 1, m, 0, 0, 1]) + # M *= matrix(ZZ, 3, [1, 0, 0, 0, 1, m, 0, 0, 1]) + [m13] = [m*m12 + m13] + [m23] = [m*m22 + m23] + [m33] = [m*m32 + m33] t = a2*m a23 += t a3 += a23*m @@ -101,7 +112,10 @@ def _reduced_ternary_form_eisenstein_with_matrix(a1, a2, a3, a23, a13, a12): # cuadred 13 m = red_mfact(a1, a13) - M *= matrix(ZZ, 3, [1, 0, m, 0, 1, 0, 0, 0, 1]) + # M *= matrix(ZZ, 3, [1, 0, m, 0, 1, 0, 0, 0, 1]) + [m13] = [m*m11 + m13] + [m23] = [m*m21 + m23] + [m33] = [m*m31 + m33] t = a1*m a13 += t a3 += a13*m @@ -110,19 +124,28 @@ def _reduced_ternary_form_eisenstein_with_matrix(a1, a2, a3, a23, a13, a12): # order 12 if a1 > a2 or (a1 == a2 and abs(a23) > abs(a13)): - M *= matrix(ZZ, 3, [0, -1, 0, -1, 0, 0, 0, 0, -1]) + # M *= matrix(ZZ, 3, [0, -1, 0, -1, 0, 0, 0, 0, -1]) + [m11, m12, m13] = [-m12, -m11, -m13] + [m21, m22, m23] = [-m22, -m21, -m23] + [m31, m32, m33] = [-m32, -m31, -m33] [a1, a2] = [a2, a1] [a13, a23] = [a23, a13] # order 23 if a2 > a3 or (a2 == a3 and abs(a13) > abs(a12)): - M *= matrix(ZZ, 3, [-1, 0, 0, 0, 0, -1, 0, -1, 0]) + # M *= matrix(ZZ, 3, [-1, 0, 0, 0, 0, -1, 0, -1, 0]) + [m11, m12, m13] = [-m11, -m13, -m12] + [m21, m22, m23] = [-m21, -m23, -m22] + [m31, m32, m33] = [-m31, -m33, -m32] [a2, a3] = [a3, a2] [a13, a12] = [a12, a13] # order 12 if a1 > a2 or (a1 == a2 and abs(a23) > abs(a13)): - M *= matrix(ZZ, 3, [0, -1, 0, -1, 0, 0, 0, 0, -1]) + # M *= matrix(ZZ, 3, [0, -1, 0, -1, 0, 0, 0, 0, -1]) + [m11, m12, m13] = [-m12, -m11, -m13] + [m21, m22, m23] = [-m22, -m21, -m23] + [m31, m32, m33] = [-m32, -m31, -m33] [a1, a2] = [a2, a1] [a13, a23] = [a23, a13] @@ -130,110 +153,159 @@ def _reduced_ternary_form_eisenstein_with_matrix(a1, a2, a3, a23, a13, a12): if a23*a13*a12 > 0: # a23, a13, a12 positive - if a23 < 0: - M *= diagonal_matrix([-1, 1, 1]) + if (a23 < 0): + # M *= diagonal_matrix([-1, 1, 1]) + m11 = -m11 + m21 = -m21 + m31 = -m31 a23 = -a23 - if a13 < 0: - M *= diagonal_matrix([1, -1, 1]) + if (a13 < 0): + # M *= diagonal_matrix([1, -1, 1]) + m12 = -m12 + m22 = -m22 + m32 = -m32 a13 = -a13 - if a12 < 0: - M *= diagonal_matrix([1, 1, -1]) + if (a12 < 0): + # M *= diagonal_matrix([1, 1, -1]) + m13 = -m13 + m23 = -m23 + m33 = -m33 a12 = -a12 else: # a23, a13, a12 nonpositive [s1, s2, s3] = [a23 > 0, a13 > 0, a12 > 0] - if (s1+s2+s3) % 2: + if (s1 + s2 + s3) % 2: if a23 == 0: s1 = 1 else: if a13 == 0: s2 = 1 else: - if a12 == 0: + if (a12 == 0): s3 = 1 if s1: - M *= diagonal_matrix([-1, 1, 1]) + # M *= diagonal_matrix([-1, 1, 1]) + m11 = -m11 + m21 = -m21 + m31 = -m31 a23 = -a23 if s2: - M *= diagonal_matrix([1, -1, 1]) + # M *= diagonal_matrix([1, -1, 1]) + m12 = -m12 + m22 = -m22 + m32 = -m32 a13 = -a13 if s3: - M *= diagonal_matrix([1, 1, -1]) + # M *= diagonal_matrix([1, 1, -1]) + m13 = -m13 + m23 = -m23 + m33 = -m33 a12 = -a12 - loop = not (abs(a23) <= a2 and abs(a13) <= a1 and abs(a12) <= a1 and a1+a2+a23+a13+a12 >= 0) + loop = not (abs(a23) <= a2 and abs(a13) <= a1 and abs(a12) <= a1 and a1 + a2 + a23 + a13 + a12 >= 0) # adj 3 - if a1+a2+a23+a13+a12 == 0 and 2*a1+2*a13+a12 > 0: - M *= matrix(ZZ, 3, [-1, 0, 1, 0, -1, 1, 0, 0, 1]) - # a3 += a1+a2+a23+a13+a12 - a23 = -2*a2-a23-a12 - a13 = -2*a1-a13-a12 + if a1 + a2 + a23 + a13 + a12 == 0 and 2*a1 + 2*a13 + a12 > 0: + # M *= matrix(ZZ, 3, [-1, 0, 1, 0, -1, 1, 0, 0, 1]) + [m11, m12, m13] = [-m11, -m12, m11 + m12 + m13] + [m21, m22, m23] = [-m21, -m22, m21 + m22 + m23] + [m31, m32, m33] = [-m31, -m32, m31 + m32 + m33] + # a3 += a1+a2+a23+a13+a12 = 0 + a23 = -2*a2 - a23 - a12 + a13 = -2*a1 - a13 - a12 # adj 5.12 if a1 == -a12 and a13 != 0: - M *= matrix(ZZ, 3, [-1, -1, 0, 0, -1, 0, 0, 0, 1]) - # a2 += a1+a12 - a23 = -a23-a13 + # M *= matrix(ZZ, 3, [-1, -1, 0, 0, -1, 0, 0, 0, 1]) + [m11, m12] = [-m11, -m11 - m12] + [m21, m22] = [-m21, -m21 - m22] + [m31, m32] = [-m31, -m31 - m32] + # a2 += a1 + a12 = 0 + a23 = -a23 - a13 a13 = -a13 - a12 = -a12 # = 2*a1+a12 + a12 = -a12 # = 2*a1 + a12 # adj 5.13 if a1 == -a13 and a12 != 0: - M *= matrix(ZZ, 3, [-1, 0, -1, 0, 1, 0, 0, 0, -1]) - # a3 += a1+a13 - a23 = -a23-a12 - a13 = -a13 # = 2*a1+a13 + # M *= matrix(ZZ, 3, [-1, 0, -1, 0, 1, 0, 0, 0, -1]) + [m11, m13] = [-m11, -m11 - m13] + [m21, m23] = [-m21, -m21 - m23] + [m31, m33] = [-m31, -m31 - m33] + # a3 += a1 + a13 = 0 + a23 = -a23 - a12 + a13 = -a13 # = 2*a1 + a13 a12 = -a12 # adj 5.23 if a2 == -a23 and a12 != 0: - M *= matrix(ZZ, 3, [1, 0, 0, 0, -1, -1, 0, 0, -1]) - # a3 += a2+a23 - a23 = -a23 # = 2*a2+a23 - a13 = -a13-a12 + # M *= matrix(ZZ, 3, [1, 0, 0, 0, -1, -1, 0, 0, -1]) + [m12, m13] = [-m12, -m12 - m13] + [m22, m23] = [-m22, -m22 - m23] + [m32, m33] = [-m32, -m32 - m33] + # a3 += a2 + a23 = 0 + a23 = -a23 # = 2*a2 + a23 + a13 = -a13 - a12 a12 = -a12 # adj 4.12 if a1 == a12 and a13 > 2*a23: - M *= matrix(ZZ, 3, [-1, -1, 0, 0, 1, 0, 0, 0, -1]) - # a 2 += a1-a12 + # M *= matrix(ZZ, 3, [-1, -1, 0, 0, 1, 0, 0, 0, -1]) + [m11, m12, m13] = [-m11, -m11 + m12, -m13] + [m21, m22, m23] = [-m21, -m21 + m22, -m23] + [m31, m32, m33] = [-m31, -m31 + m32, -m33] + # a2 += a1 - a12 = 0 a23 = -a23 + a13 # a12 = 2*a1 - a12 # adj 4.13 if a1 == a13 and a12 > 2*a23: - M *= matrix(ZZ, 3, [-1, 0, -1, 0, -1, 0, 0, 0, 1]) - # a3 += a1-a13 + # M *= matrix(ZZ, 3, [-1, 0, -1, 0, -1, 0, 0, 0, 1]) + [m11, m12, m13] = [-m11, -m12, -m11 + m13] + [m21, m22, m23] = [-m21, -m22, -m21 + m23] + [m31, m32, m33] = [-m31, -m32, -m31 + m33] + # a3 += a1 - a13 = 0 a23 = -a23 + a12 # a13 = 2*a1 - a13 # adj 4.23 if a2 == a23 and a12 > 2*a13: - M *= matrix(ZZ, 3, [-1, 0, 0, 0, -1, -1, 0, 0, 1]) - # a3 += a2-a23 + # M *= matrix(ZZ, 3, [-1, 0, 0, 0, -1, -1, 0, 0, 1]) + [m11, m12, m13] = [-m11, -m12, -m12 + m13] + [m21, m22, m23] = [-m21, -m22, -m22 + m23] + [m31, m32, m33] = [-m31, -m32, -m32 + m33] + # a3 += a2 - a23 = 0 # a23 = 2*a2 - a23 a13 = -a13 + a12 # order 12 if a1 == a2 and abs(a23) > abs(a13): - M *= matrix(ZZ, 3, [0, -1, 0, -1, 0, 0, 0, 0, -1]) + # M *= matrix(ZZ, 3, [0, -1, 0, -1, 0, 0, 0, 0, -1]) + [m11, m12, m13] = [-m12, -m11, -m13] + [m21, m22, m23] = [-m22, -m21, -m23] + [m31, m32, m33] = [-m32, -m31, -m33] [a1, a2] = [a2, a1] [a13, a23] = [a23, a13] # order 23 if a2 == a3 and abs(a13) > abs(a12): - M *= matrix(ZZ, 3, [-1, 0, 0, 0, 0, -1, 0, -1, 0]) + # M *= matrix(ZZ, 3, [-1, 0, 0, 0, 0, -1, 0, -1, 0]) + [m11, m12, m13] = [-m11, -m13, -m12] + [m21, m22, m23] = [-m21, -m23, -m22] + [m31, m32, m33] = [-m31, -m33, -m32] [a13, a12] = [a12, a13] # order 12 if a1 == a2 and abs(a23) > abs(a13): - M *= matrix(ZZ, 3, [0, -1, 0, -1, 0, 0, 0, 0, -1]) + # M *= matrix(ZZ, 3, [0, -1, 0, -1, 0, 0, 0, 0, -1]) + [m11, m12, m13] = [-m12, -m11, -m13] + [m21, m22, m23] = [-m22, -m21, -m23] + [m31, m32, m33] = [-m32, -m31, -m33] [a13, a23] = [a23, a13] - return (a1, a2, a3, a23, a13, a12), M + return (a1, a2, a3, a23, a13, a12), \ + matrix(ZZ, 3, (m11, m12, m13, m21, m22, m23, m31, m32, m33)) def _reduced_ternary_form_eisenstein_without_matrix(a1, a2, a3, a23, a13, a12): diff --git a/src/sage/quadratic_forms/ternary_qf.py b/src/sage/quadratic_forms/ternary_qf.py index 6a08d00f26c..4184c839528 100644 --- a/src/sage/quadratic_forms/ternary_qf.py +++ b/src/sage/quadratic_forms/ternary_qf.py @@ -116,6 +116,20 @@ def coefficients(self): """ return self._a, self._b, self._c, self._r, self._s, self._t + def __hash__(self): + """ + Returns a hash for self. + + EXAMPLES:: + + sage: Q = TernaryQF([1, 2, 3, 4, 5, 6]) + sage: Q.__hash__() + 5881802312257552497 # 64-bit + 1770036893 # 32-bit + """ + + return hash(self.coefficients()) + def coefficient(self, n): r""" Return the `n`-th coefficient of the ternary quadratic form. diff --git a/src/sage/quivers/algebra_elements.pxd b/src/sage/quivers/algebra_elements.pxd index 3beb69914d0..e47696270da 100644 --- a/src/sage/quivers/algebra_elements.pxd +++ b/src/sage/quivers/algebra_elements.pxd @@ -83,14 +83,14 @@ cdef class PathAlgebraElement(RingElement): # functions. cdef path_order_t cmp_terms cdef long _hash - cpdef _add_(self, other) - cpdef _mul_(self, other) + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept cpdef ssize_t degree(self) except -2 - cpdef dict monomial_coefficients(self) - cpdef list coefficients(self) - cpdef list monomials(self) - cpdef list support(self) - cpdef list terms(self) - cpdef object coefficient(self, QuiverPath P) - cdef list _sorted_items_for_printing(self) - cdef inline PathAlgebraElement _new_(self, path_homog_poly_t *h) + cpdef dict monomial_coefficients(self) noexcept + cpdef list coefficients(self) noexcept + cpdef list monomials(self) noexcept + cpdef list support(self) noexcept + cpdef list terms(self) noexcept + cpdef object coefficient(self, QuiverPath P) noexcept + cdef list _sorted_items_for_printing(self) noexcept + cdef inline PathAlgebraElement _new_(self, path_homog_poly_t *h) noexcept diff --git a/src/sage/quivers/algebra_elements.pxi b/src/sage/quivers/algebra_elements.pxi index a6372328fdd..7b9a9883f28 100644 --- a/src/sage/quivers/algebra_elements.pxi +++ b/src/sage/quivers/algebra_elements.pxi @@ -68,7 +68,7 @@ cdef bint mon_create_keep(path_mon_t out, biseq_t Mon, long Pos, mp_size_t L_len # It changes an existing monomial in-place (which should NEVER # be done on a monomial that is in use), re-allocating memory # and filling it with the given bounded integer sequence (not a copy). -cdef bint mon_realloc_keep(path_mon_t out, biseq_t Mon, long Pos, mp_size_t L_len, mp_size_t S_len): +cdef bint mon_realloc_keep(path_mon_t out, biseq_t Mon, long Pos, mp_size_t L_len, mp_size_t S_len) noexcept: biseq_dealloc(out.path) out.path[0] = Mon[0] out.pos = Pos @@ -84,11 +84,11 @@ cdef inline bint mon_copy(path_mon_t out, path_mon_t M) except -1: # Deallocate the monomial, which means to decrease the reference count, # or to actually deallocate the data if there is no reference left. -cdef inline void mon_free(path_mon_t M): +cdef inline void mon_free(path_mon_t M) noexcept: biseq_dealloc(M.path) # Linearisation -cdef inline tuple mon_pickle(path_mon_t M): +cdef inline tuple mon_pickle(path_mon_t M) noexcept: return (bitset_pickle(M.path.data) if M.path.length>0 else (), M.path.itembitsize, M.path.length, M.pos, M.l_len, M.s_len) @@ -286,7 +286,7 @@ freelist.used = 0 freelist.pool = check_allocarray(poolsize, sizeof(path_term_t*)) # Deallocate the term, and return the pointer .nxt, without using kill list -cdef inline path_term_t *term_free_force(path_term_t *T): +cdef inline path_term_t *term_free_force(path_term_t *T) noexcept: mon_free(T.mon) cdef path_term_t *out = T.nxt sig_free(T) @@ -323,7 +323,7 @@ _freelist_protector = _FreeListProtector() # Put the term on the freelist (unless the list is full), # and return the pointer .nxt -cdef inline path_term_t *term_free(path_term_t *T): +cdef inline path_term_t *term_free(path_term_t *T) noexcept: if T.coef!=NULL: Py_XDECREF(T.coef) if likely(freelist.used < poolsize): @@ -408,18 +408,18 @@ cdef path_term_t *term_copy_recursive(path_term_t *T) except NULL: return first # Hash of a term; probably not a good one. -cdef inline long term_hash(path_term_t *T): +cdef inline long term_hash(path_term_t *T) noexcept: return (hash(T.coef)+(T.mon.l_len<<5)+(T.mon.pos<<10))^bitset_hash(T.mon.path.data) # Recall that a monomial a*I*b (with I a generator of a free module) # is encoded by a path a*s*b for some monomial s that refers to a # so-called Schreyer ordering. The total degree of a*I*b is the length # of a plus the length of b. -cdef inline mp_size_t term_total_degree(path_term_t *T): +cdef inline mp_size_t term_total_degree(path_term_t *T) noexcept: return T.mon.path.length-T.mon.s_len # Linearisation -cdef inline tuple term_pickle(path_term_t *T): +cdef inline tuple term_pickle(path_term_t *T) noexcept: return (T.coef, mon_pickle(T.mon)) # De-linearisation @@ -628,14 +628,14 @@ cdef inline path_poly_t *poly_create() except NULL: return out # Deallocate all terms of the polynomial, but NOT the polynomial itself -cdef inline void poly_dealloc(path_poly_t *P): +cdef inline void poly_dealloc(path_poly_t *P) noexcept: cdef path_term_t *T = P.lead while T!=NULL: T = term_free(T) # Deallocate all terms of the polynomial, and free the chunk of memory # used by the polynomial. -cdef inline void poly_free(path_poly_t *P): +cdef inline void poly_free(path_poly_t *P) noexcept: poly_dealloc(P) sig_free(P) @@ -689,7 +689,7 @@ cdef bint poly_icopy_scale(path_poly_t *out, path_poly_t *P, object coef) except return True # Linearisation of a path polynomials -cdef list poly_pickle(path_poly_t *P): +cdef list poly_pickle(path_poly_t *P) noexcept: cdef list L = [] cdef path_term_t *T = P.lead while T != NULL: @@ -722,7 +722,7 @@ cdef bint poly_inplace_unpickle(path_poly_t *P, list data) except -1: # Rich comparison of P1 and P2, using the given monomial ordering cmp_terms. # Return a boolean. -cdef bint poly_richcmp(path_poly_t *P1, path_poly_t *P2, path_order_t cmp_terms, int op): +cdef bint poly_richcmp(path_poly_t *P1, path_poly_t *P2, path_order_t cmp_terms, int op) noexcept: cdef path_term_t *T1 = P1.lead cdef path_term_t *T2 = P2.lead cdef int c @@ -747,7 +747,7 @@ cdef bint poly_richcmp(path_poly_t *P1, path_poly_t *P2, path_order_t cmp_terms, return rich_to_bool(op, 1) # Hash of a polynomial. Probably not a very strong hash. -cdef inline long poly_hash(path_poly_t *P): +cdef inline long poly_hash(path_poly_t *P) noexcept: cdef path_term_t *T = P.lead cdef long out = 0 while T != NULL: @@ -758,7 +758,7 @@ cdef inline long poly_hash(path_poly_t *P): # Change T1 inplace to T1+T2.coeff*T1. If the new coefficient is zero, # then T1.coef becomes NULL -cdef inline void term_iadd(path_term_t *T1, path_term_t *T2): +cdef inline void term_iadd(path_term_t *T1, path_term_t *T2) noexcept: cdef object coef = (T1.coef) + (T2.coef) Py_XDECREF(T1.coef) if coef: @@ -1205,7 +1205,7 @@ cdef path_homog_poly_t *homog_poly_init_list(int start, int end, list L, path_or poly_iadd_term_d(out.poly, term_create(coef, P._path, pos, 0, 0), cmp_terms) return out -cdef void homog_poly_free(path_homog_poly_t *P): +cdef void homog_poly_free(path_homog_poly_t *P) noexcept: cdef path_homog_poly_t *nxt while P!=NULL: nxt = P.nxt @@ -1232,7 +1232,7 @@ cdef path_homog_poly_t *homog_poly_copy(path_homog_poly_t *H) except NULL: return out # Linearisation -cdef list homog_poly_pickle(path_homog_poly_t *H): +cdef list homog_poly_pickle(path_homog_poly_t *H) noexcept: cdef list L = [] while H != NULL: L.append((H.start, H.end, poly_pickle(H.poly))) @@ -1297,7 +1297,7 @@ cdef path_homog_poly_t *homog_poly_scale(path_homog_poly_t *H, object coef) exce H = H.nxt return out -cdef path_homog_poly_t *homog_poly_get_predecessor_of_component(path_homog_poly_t *H, int s, int e): +cdef path_homog_poly_t *homog_poly_get_predecessor_of_component(path_homog_poly_t *H, int s, int e) noexcept: # Search through H.nxt.nxt... and return the pointer C to a component of H # such that either C.nxt.start==s and C.nxt.end==e, or the component for # (s,e) should be inserted between C and C.nxt. Return NULL if H==NULL or diff --git a/src/sage/quivers/algebra_elements.pyx b/src/sage/quivers/algebra_elements.pyx index 3d05ba7e270..54906701d26 100644 --- a/src/sage/quivers/algebra_elements.pyx +++ b/src/sage/quivers/algebra_elements.pyx @@ -211,7 +211,7 @@ cdef class PathAlgebraElement(RingElement): """ return path_algebra_element_unpickle, (self._parent, homog_poly_pickle(self.data)) - cdef list _sorted_items_for_printing(self): + cdef list _sorted_items_for_printing(self) noexcept: """ Return list of pairs ``(M,c)``, where ``c`` is a coefficient and ``M`` will be passed to ``self.parent()._repr_monomial`` resp. to @@ -402,7 +402,7 @@ cdef class PathAlgebraElement(RingElement): H = H.nxt return True - cpdef dict monomial_coefficients(self): + cpdef dict monomial_coefficients(self) noexcept: """ Return the dictionary keyed by the monomials appearing in this element, the values being the coefficients. @@ -451,7 +451,7 @@ cdef class PathAlgebraElement(RingElement): H = H.nxt return D - cpdef list coefficients(self): + cpdef list coefficients(self) noexcept: """ Return the list of coefficients. @@ -485,7 +485,7 @@ cdef class PathAlgebraElement(RingElement): H = H.nxt return L - cpdef list monomials(self): + cpdef list monomials(self) noexcept: """ Return the list of monomials appearing in this element. @@ -547,7 +547,7 @@ cdef class PathAlgebraElement(RingElement): H = H.nxt return L - cpdef list terms(self): + cpdef list terms(self) noexcept: """ Return the list of terms. @@ -600,7 +600,7 @@ cdef class PathAlgebraElement(RingElement): H = H.nxt return L - cpdef list support(self): + cpdef list support(self) noexcept: """ Return the list of monomials, as elements of the underlying partial semigroup. @@ -685,7 +685,7 @@ cdef class PathAlgebraElement(RingElement): return tmp raise ValueError("{} is not a single term".format(self)) - cpdef object coefficient(self, QuiverPath P): + cpdef object coefficient(self, QuiverPath P) noexcept: """ Return the coefficient of a monomial. @@ -775,7 +775,7 @@ cdef class PathAlgebraElement(RingElement): T = T.nxt H = H.nxt - cdef PathAlgebraElement _new_(self, path_homog_poly_t *h): + cdef PathAlgebraElement _new_(self, path_homog_poly_t *h) noexcept: """ Create a new path algebra element from C interface data. """ @@ -941,7 +941,7 @@ cdef class PathAlgebraElement(RingElement): self._hash = hash(frozenset(self.monomial_coefficients().items())) return self._hash - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Helper for comparison of path algebra elements. @@ -999,7 +999,7 @@ cdef class PathAlgebraElement(RingElement): return rich_to_bool(op, 1) # negation - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ EXAMPLES:: @@ -1013,7 +1013,7 @@ cdef class PathAlgebraElement(RingElement): return self._new_(homog_poly_neg(self.data)) # addition - cpdef _add_(self, other): + cpdef _add_(self, other) noexcept: """ EXAMPLES:: @@ -1089,7 +1089,7 @@ cdef class PathAlgebraElement(RingElement): H1 = H1.nxt H2 = H2.nxt - cpdef _sub_(self, other): + cpdef _sub_(self, other) noexcept: """ EXAMPLES:: @@ -1178,7 +1178,7 @@ cdef class PathAlgebraElement(RingElement): # (scalar) multiplication - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: """ EXAMPLES:: @@ -1208,7 +1208,7 @@ cdef class PathAlgebraElement(RingElement): return self._new_(outnxt) return self._new_(out) - cpdef _rmul_(self, Element left): + cpdef _rmul_(self, Element left) noexcept: """ EXAMPLES:: @@ -1275,7 +1275,7 @@ cdef class PathAlgebraElement(RingElement): # Multiplication in the algebra - cpdef _mul_(self, other): + cpdef _mul_(self, other) noexcept: """ EXAMPLES:: @@ -1381,7 +1381,7 @@ cdef class PathAlgebraElement(RingElement): tmp = tmp.nxt return self._new_(out_orig) -cpdef PathAlgebraElement path_algebra_element_unpickle(P, list data): +cpdef PathAlgebraElement path_algebra_element_unpickle(P, list data) noexcept: """ Auxiliary function for unpickling. diff --git a/src/sage/quivers/paths.pxd b/src/sage/quivers/paths.pxd index 5757bf6e219..88bfe92ca0f 100644 --- a/src/sage/quivers/paths.pxd +++ b/src/sage/quivers/paths.pxd @@ -4,9 +4,9 @@ from sage.data_structures.bounded_integer_sequences cimport biseq_t cdef class QuiverPath(MonoidElement): cdef biseq_t _path cdef int _start, _end - cdef QuiverPath _new_(self, int start, int end) - cpdef _mul_(self, other) - cpdef _mod_(self, right) - cpdef tuple complement(self, QuiverPath subpath) + cdef QuiverPath _new_(self, int start, int end) noexcept + cpdef _mul_(self, other) noexcept + cpdef _mod_(self, right) noexcept + cpdef tuple complement(self, QuiverPath subpath) noexcept cpdef bint has_subpath(self, QuiverPath subpath) except -1 cpdef bint has_prefix(self, QuiverPath subpath) except -1 diff --git a/src/sage/quivers/paths.pyx b/src/sage/quivers/paths.pyx index f2642ada119..38fdc03beba 100644 --- a/src/sage/quivers/paths.pyx +++ b/src/sage/quivers/paths.pyx @@ -109,7 +109,7 @@ cdef class QuiverPath(MonoidElement): """ biseq_dealloc(self._path) - cdef QuiverPath _new_(self, int start, int end): + cdef QuiverPath _new_(self, int start, int end) noexcept: """ TESTS:: @@ -260,7 +260,7 @@ cdef class QuiverPath(MonoidElement): """ return self._path.length != 0 - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Comparison for :class:`QuiverPaths`. @@ -465,7 +465,7 @@ cdef class QuiverPath(MonoidElement): for i in range(self._path.length): yield E[biseq_getitem(self._path, i)] - cpdef _mul_(self, other): + cpdef _mul_(self, other) noexcept: """ Compose two paths. @@ -503,7 +503,7 @@ cdef class QuiverPath(MonoidElement): biseq_init_concat(OUT._path, self._path,right._path) return OUT - cpdef _mod_(self, other): + cpdef _mod_(self, other) noexcept: """ Return what remains of this path after removing the initial segment ``other``. @@ -606,7 +606,7 @@ cdef class QuiverPath(MonoidElement): return (None, None, None) return (self[:i], self[i:], P[self._path.length-i:]) - cpdef tuple complement(self, QuiverPath subpath): + cpdef tuple complement(self, QuiverPath subpath) noexcept: """ Return a pair ``(a,b)`` of paths s.t. ``self = a*subpath*b``, or ``(None, None)`` if ``subpath`` is not a subpath of this path. diff --git a/src/sage/repl/ipython_kernel/interact.py b/src/sage/repl/ipython_kernel/interact.py index 0551c83480e..c9c3d627657 100644 --- a/src/sage/repl/ipython_kernel/interact.py +++ b/src/sage/repl/ipython_kernel/interact.py @@ -22,18 +22,6 @@ x: IntSlider(value=5, description='x', max=10) sage: f.widget.children (IntSlider(value=5, description='x', max=10), Output()) - -.. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - from sage.repl.ipython_kernel.interact import interact - @interact - def f(x=(0, 10)): - pass - """ # **************************************************************************** @@ -72,16 +60,6 @@ class sage_interactive(interactive): x: IntSlider(value=10, description='x') y: Text(value='hello', description='y') z: Dropdown(description='z', options=('one', 'two', 'three'), value=None) - - .. ONLY:: html - - .. JUPYTER-EXECUTE:: - :hide-code: - :hide-output: - - from sage.repl.ipython_kernel.interact import sage_interactive - def myfunc(x=10, y="hello", z=None): pass - sage_interactive(myfunc, x=(0,100), z=["one", "two", "three"]) """ def __init__(self, *args, **kwds): """ diff --git a/src/sage/repl/ipython_kernel/kernel.py b/src/sage/repl/ipython_kernel/kernel.py index db7554eed59..ce5ce6bf65d 100644 --- a/src/sage/repl/ipython_kernel/kernel.py +++ b/src/sage/repl/ipython_kernel/kernel.py @@ -94,54 +94,68 @@ def help_links(self): See the Jupyter documentation. - .. NOTE:: - - Urls starting with "kernelspecs" are prepended by the - browser with the appropriate path. - EXAMPLES:: sage: from sage.repl.ipython_kernel.kernel import SageKernel sage: sk = SageKernel.__new__(SageKernel) sage: sk.help_links [{'text': 'Sage Documentation', - 'url': 'kernelspecs/sagemath/doc/html/en/index.html'}, + 'url': 'https://doc.sagemath.org/html/en/index.html'}, ...] """ + # DEPRECATED: The URLs in the form 'kernelspecs/...' were used for + # classical Jupyter notebooks. For instance, + # + # 'kernelspecs/sagemath/doc/html/en/index.html' + # + # is constructed by kernel_url('doc/html/en/index.html'), but these + # URLs of local files don't work for JupyterLab. Hence all URLs here + # have been replaced with URLs of online documents. + from sage.repl.ipython_kernel.install import SageKernelSpec identifier = SageKernelSpec.identifier() def kernel_url(x): + # URLs starting with 'kernelspecs' are prepended by the + # browser with the appropriate path return 'kernelspecs/{0}/{1}'.format(identifier, x) return [ { 'text': 'Sage Documentation', - 'url': kernel_url('doc/html/en/index.html'), + 'url': "https://doc.sagemath.org/html/en/index.html", + }, + { + 'text': 'A Tour of Sage', + 'url': "https://doc.sagemath.org/html/en/a_tour_of_sage/index.html", }, { 'text': 'Tutorial', - 'url': kernel_url('doc/html/en/tutorial/index.html'), + 'url': "https://doc.sagemath.org/html/en/tutorial/index.html", }, { 'text': 'Thematic Tutorials', - 'url': kernel_url('doc/html/en/thematic_tutorials/index.html'), + 'url': "https://doc.sagemath.org/html/en/thematic_tutorials/index.html", }, { - 'text': 'FAQs', - 'url': kernel_url('doc/html/en/faq/index.html'), + 'text': 'PREP Tutorials', + 'url': "https://doc.sagemath.org/html/en/prep/index.html", }, { - 'text': 'PREP Tutorials', - 'url': kernel_url('doc/html/en/prep/index.html'), + 'text': 'Constructions', + 'url': "https://doc.sagemath.org/html/en/constructions/index.html", + }, + { + 'text': 'FAQ', + 'url': "https://doc.sagemath.org/html/en/faq/index.html", }, { 'text': 'Reference', - 'url': kernel_url('doc/html/en/reference/index.html'), + 'url': "https://doc.sagemath.org/html/en/reference/index.html", }, { 'text': "Developer's Guide", - 'url': kernel_url('doc/html/en/developer/index.html'), + 'url': "https://doc.sagemath.org/html/en/developer/index.html", }, { 'text': "Python", diff --git a/src/sage/repl/rich_output/backend_ipython.py b/src/sage/repl/rich_output/backend_ipython.py index 86bdf342e3e..69e63b76d60 100644 --- a/src/sage/repl/rich_output/backend_ipython.py +++ b/src/sage/repl/rich_output/backend_ipython.py @@ -17,6 +17,7 @@ import os import sys +import html from IPython.display import publish_display_data from sage.repl.rich_output.backend_base import BackendBase from sage.repl.rich_output.output_catalog import * @@ -574,7 +575,7 @@ def displayhook(self, plain_text, rich_output): 'text/plain': plain_text.text.get_str(), }, {}) elif isinstance(rich_output, OutputSceneThreejs): - escaped_html = rich_output.html.get_str().replace('"', '"') + escaped_html = html.escape(rich_output.html.get_str()) iframe = IFRAME_TEMPLATE.format( escaped_html=escaped_html, width='100%', diff --git a/src/sage/rings/complex_arb.pxd b/src/sage/rings/complex_arb.pxd index 5f858a20fcf..d985745c1f5 100644 --- a/src/sage/rings/complex_arb.pxd +++ b/src/sage/rings/complex_arb.pxd @@ -6,7 +6,7 @@ from sage.rings.ring cimport Field cdef void ComplexIntervalFieldElement_to_acb( acb_t target, - ComplexIntervalFieldElement source) + ComplexIntervalFieldElement source) noexcept cdef int acb_to_ComplexIntervalFieldElement( ComplexIntervalFieldElement target, @@ -14,15 +14,15 @@ cdef int acb_to_ComplexIntervalFieldElement( cdef class ComplexBall(RingElement): cdef acb_t value - cdef ComplexBall _new(self) - cpdef _add_(self, other) - cpdef _mul_(self, other) - cpdef ComplexIntervalFieldElement _complex_mpfi_(self, parent) - cpdef RealBall real(self) - cpdef RealBall imag(self) - cpdef pow(self, expo, analytic=?) + cdef ComplexBall _new(self) noexcept + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept + cpdef ComplexIntervalFieldElement _complex_mpfi_(self, parent) noexcept + cpdef RealBall real(self) noexcept + cpdef RealBall imag(self) noexcept + cpdef pow(self, expo, analytic=?) noexcept - cdef inline ComplexBall _new(self): + cdef inline ComplexBall _new(self) noexcept: cdef ComplexBall res = ComplexBall.__new__(ComplexBall) res._parent = self._parent return res diff --git a/src/sage/rings/complex_arb.pyx b/src/sage/rings/complex_arb.pyx index a22ce3c5e53..f36a89bb229 100644 --- a/src/sage/rings/complex_arb.pyx +++ b/src/sage/rings/complex_arb.pyx @@ -197,7 +197,7 @@ from sage.rings.integer_ring import ZZ cdef void ComplexIntervalFieldElement_to_acb( acb_t target, - ComplexIntervalFieldElement source): + ComplexIntervalFieldElement source) noexcept: """ Convert a :class:`ComplexIntervalFieldElement` to an ``acb``. @@ -250,7 +250,7 @@ cdef class IntegrationContext: cdef object exn_tb cdef int acb_calc_func_callback(acb_ptr out, const acb_t inp, void * param, - long order, long prec): + long order, long prec) noexcept: r""" Callback used for numerical integration @@ -1254,16 +1254,16 @@ class ComplexBallField(UniqueRepresentation, sage.rings.abc.ComplexBallField): return res -cdef inline bint _do_sig(long prec): +cdef inline bint _do_sig(long prec) noexcept: """ Whether signal handlers should be installed for calls to arb. """ return (prec > 1000) -cdef inline long prec(ComplexBall ball): +cdef inline long prec(ComplexBall ball) noexcept: return ball._parent._prec -cdef bint arb_contained_unit_interval(arb_t b): +cdef bint arb_contained_unit_interval(arb_t b) noexcept: r""" Test if a real ball is contained in [-1,1]. Useful for dealing with branch cuts of inverse trigonometric functions. @@ -1281,7 +1281,7 @@ cdef bint arb_contained_unit_interval(arb_t b): finally: arb_clear(u) -cdef bint arb_gt_neg_one(arb_t b): +cdef bint arb_gt_neg_one(arb_t b) noexcept: r""" Test if a real ball is contained in [-1,∞). Useful for dealing with branch cuts. @@ -1293,7 +1293,7 @@ cdef bint arb_gt_neg_one(arb_t b): arb_clear(neg_one) return res -cdef inline real_ball_field(ComplexBall ball): +cdef inline real_ball_field(ComplexBall ball) noexcept: return ball._parent._base cdef class ComplexBall(RingElement): @@ -1545,7 +1545,7 @@ cdef class ComplexBall(RingElement): # Conversions - cpdef ComplexIntervalFieldElement _complex_mpfi_(self, parent): + cpdef ComplexIntervalFieldElement _complex_mpfi_(self, parent) noexcept: """ Return :class:`ComplexIntervalFieldElement` of the same value. @@ -1804,7 +1804,7 @@ cdef class ComplexBall(RingElement): # Real and imaginary part, midpoint, radius - cpdef RealBall real(self): + cpdef RealBall real(self) noexcept: """ Return the real part of this ball. @@ -1825,7 +1825,7 @@ cdef class ComplexBall(RingElement): arb_set(r.value, acb_realref(self.value)) return r - cpdef RealBall imag(self): + cpdef RealBall imag(self) noexcept: """ Return the imaginary part of this ball. @@ -2330,7 +2330,7 @@ cdef class ComplexBall(RingElement): """ return acb_is_real(self.value) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Compare ``left`` and ``right``. @@ -2617,7 +2617,7 @@ cdef class ComplexBall(RingElement): acb_conj(res.value, self.value) return res - cpdef _add_(self, other): + cpdef _add_(self, other) noexcept: """ Return the sum of two balls, rounded to the ambient field's precision. @@ -2635,7 +2635,7 @@ cdef class ComplexBall(RingElement): if _do_sig(prec(self)): sig_off() return res - cpdef _sub_(self, other): + cpdef _sub_(self, other) noexcept: """ Return the difference of two balls, rounded to the ambient field's precision. @@ -2676,7 +2676,7 @@ cdef class ComplexBall(RingElement): if _do_sig(prec(self)): sig_off() return res - cpdef _mul_(self, other): + cpdef _mul_(self, other) noexcept: """ Return the product of two balls, rounded to the ambient field's precision. @@ -2776,7 +2776,7 @@ cdef class ComplexBall(RingElement): raise TypeError("unsupported operand type(s) for >>: '{}' and '{}'" .format(type(val).__name__, type(shift).__name__)) - cpdef _div_(self, other): + cpdef _div_(self, other) noexcept: """ Return the quotient of two balls, rounded to the ambient field's precision. @@ -2843,7 +2843,7 @@ cdef class ComplexBall(RingElement): else: return sage.structure.element.bin_op(base, expo, operator.pow) - cpdef pow(self, expo, analytic=False): + cpdef pow(self, expo, analytic=False) noexcept: r""" Raise this ball to the power of ``expo``. diff --git a/src/sage/rings/complex_conversion.pxd b/src/sage/rings/complex_conversion.pxd index 2053005e340..d6144974f9a 100644 --- a/src/sage/rings/complex_conversion.pxd +++ b/src/sage/rings/complex_conversion.pxd @@ -4,4 +4,4 @@ from sage.categories.map cimport Map cdef class CCtoCDF(Map): - cpdef Element _call_(self, x) + cpdef Element _call_(self, x) noexcept diff --git a/src/sage/rings/complex_conversion.pyx b/src/sage/rings/complex_conversion.pyx index abf179064c6..e7e53724f9c 100644 --- a/src/sage/rings/complex_conversion.pyx +++ b/src/sage/rings/complex_conversion.pyx @@ -5,7 +5,7 @@ from sage.libs.gsl.complex cimport GSL_SET_COMPLEX cdef class CCtoCDF(Map): - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ EXAMPLES:: sage: from sage.rings.complex_conversion import CCtoCDF diff --git a/src/sage/rings/complex_double.pxd b/src/sage/rings/complex_double.pxd index 821b9943b51..789db2ba3ad 100644 --- a/src/sage/rings/complex_double.pxd +++ b/src/sage/rings/complex_double.pxd @@ -11,10 +11,10 @@ cdef class ComplexDoubleField_class(sage.rings.abc.ComplexDoubleField): cdef class ComplexDoubleElement(sage.structure.element.FieldElement): cdef gsl_complex _complex - cdef ComplexDoubleElement _new_c(self, gsl_complex x) - cpdef _add_(self, other) - cpdef _mul_(self, other) - cpdef _pow_(self, other) + cdef ComplexDoubleElement _new_c(self, gsl_complex x) noexcept + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept + cpdef _pow_(self, other) noexcept -cdef ComplexDoubleElement new_ComplexDoubleElement() +cdef ComplexDoubleElement new_ComplexDoubleElement() noexcept diff --git a/src/sage/rings/complex_double.pyx b/src/sage/rings/complex_double.pyx index 8b9883d1279..ed46913433f 100644 --- a/src/sage/rings/complex_double.pyx +++ b/src/sage/rings/complex_double.pyx @@ -377,7 +377,7 @@ cdef class ComplexDoubleField_class(sage.rings.abc.ComplexDoubleField): else: return ComplexDoubleElement(x, 0) - cpdef _coerce_map_from_(self, S): + cpdef _coerce_map_from_(self, S) noexcept: """ Return the canonical coerce of `x` into the complex double field, if it is defined, otherwise raise a ``TypeError``. @@ -691,7 +691,7 @@ cdef class ComplexDoubleField_class(sage.rings.abc.ComplexDoubleField): return Factorization([(x - a, 1) for a in roots], unit) -cdef ComplexDoubleElement new_ComplexDoubleElement(): +cdef ComplexDoubleElement new_ComplexDoubleElement() noexcept: """ Creates a new (empty) :class:`ComplexDoubleElement`. """ @@ -761,7 +761,7 @@ cdef class ComplexDoubleElement(FieldElement): return (ComplexDoubleElement, (GSL_REAL(self._complex), GSL_IMAG(self._complex))) - cdef ComplexDoubleElement _new_c(self, gsl_complex x): + cdef ComplexDoubleElement _new_c(self, gsl_complex x) noexcept: """ C-level code for creating a :class:`ComplexDoubleElement` from a ``gsl_complex``. @@ -786,7 +786,7 @@ cdef class ComplexDoubleElement(FieldElement): """ return hash(complex(self)) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ We order the complex numbers in dictionary order by real parts then imaginary parts. @@ -1158,7 +1158,7 @@ cdef class ComplexDoubleElement(FieldElement): # Arithmetic ####################################################################### - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Add ``self`` and ``right``. @@ -1170,7 +1170,7 @@ cdef class ComplexDoubleElement(FieldElement): return self._new_c(gsl_complex_add(self._complex, (right)._complex)) - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Subtract ``self`` and ``right``. @@ -1182,7 +1182,7 @@ cdef class ComplexDoubleElement(FieldElement): return self._new_c(gsl_complex_sub(self._complex, (right)._complex)) - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Multiply ``self`` and ``right``. @@ -1194,7 +1194,7 @@ cdef class ComplexDoubleElement(FieldElement): return self._new_c(gsl_complex_mul(self._complex, (right)._complex)) - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Divide ``self`` by ``right``. @@ -1228,7 +1228,7 @@ cdef class ComplexDoubleElement(FieldElement): """ return self._new_c(gsl_complex_inverse(self._complex)) - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ This function returns the negative of the complex number `z`: @@ -1615,7 +1615,7 @@ cdef class ComplexDoubleElement(FieldElement): """ return self.real().is_NaN() or self.imag().is_NaN() - cpdef _pow_(self, other): + cpdef _pow_(self, other) noexcept: r""" The complex number ``self`` raised to the power ``other``. @@ -1681,7 +1681,7 @@ cdef class ComplexDoubleElement(FieldElement): z = other return self._new_c(gsl_complex_pow(self._complex, z._complex)) - cdef _pow_long(self, long other): + cdef _pow_long(self, long other) noexcept: if other == 1: return self elif other == 0: @@ -1697,7 +1697,7 @@ cdef class ComplexDoubleElement(FieldElement): res = gsl_complex_pow_real(self._complex, other) return self._new_c(res) - cpdef _pow_int(self, other): + cpdef _pow_int(self, other) noexcept: if not GSL_IMAG(self._complex): # If self is real, the result should be real too real = GSL_REAL(self._complex) ** other @@ -2515,7 +2515,7 @@ cdef class FloatToCDF(Morphism): R = Set_PythonType(R) Morphism.__init__(self, Hom(R, CDF)) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Create an :class:`ComplexDoubleElement`. @@ -2565,7 +2565,7 @@ cdef class ComplexToCDF(Morphism): R = Set_PythonType(R) Morphism.__init__(self, Hom(R, CDF)) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Create an :class:`ComplexDoubleElement`. @@ -2619,7 +2619,7 @@ def ComplexDoubleField(): from sage.misc.parser import Parser cdef cdf_parser = Parser(float, float, {"I" : _CDF.gen(), "i" : _CDF.gen()}) -cdef inline double complex extract_double_complex(ComplexDoubleElement x): +cdef inline double complex extract_double_complex(ComplexDoubleElement x) noexcept: """ Return the value of ``x`` as a c99 complex double. """ @@ -2629,7 +2629,7 @@ cdef inline double complex extract_double_complex(ComplexDoubleElement x): return z -cdef inline ComplexDoubleElement ComplexDoubleElement_from_doubles(double re, double im): +cdef inline ComplexDoubleElement ComplexDoubleElement_from_doubles(double re, double im) noexcept: """ Create a new :class:`ComplexDoubleElement` with the specified real and imaginary parts. diff --git a/src/sage/rings/complex_interval.pxd b/src/sage/rings/complex_interval.pxd index b0a64632ad5..56513b65747 100644 --- a/src/sage/rings/complex_interval.pxd +++ b/src/sage/rings/complex_interval.pxd @@ -11,7 +11,7 @@ cdef class ComplexIntervalFieldElement(sage.structure.element.FieldElement): cdef mpfr_prec_t _prec cdef object _multiplicative_order - cdef inline ComplexIntervalFieldElement _new(self): + cdef inline ComplexIntervalFieldElement _new(self) noexcept: """ Quickly create a new complex interval with the same parent as ``self``. @@ -20,7 +20,7 @@ cdef class ComplexIntervalFieldElement(sage.structure.element.FieldElement): cdef object _multiplicative_order = None return t.__new__(t, self._parent) - cdef inline RealIntervalFieldElement _new_real(self): + cdef inline RealIntervalFieldElement _new_real(self) noexcept: """ Quickly create a new real interval with the same precision as ``self``. diff --git a/src/sage/rings/complex_interval.pyx b/src/sage/rings/complex_interval.pyx index 7fe25fd8114..c38261d136d 100644 --- a/src/sage/rings/complex_interval.pyx +++ b/src/sage/rings/complex_interval.pyx @@ -681,7 +681,7 @@ cdef class ComplexIntervalFieldElement(FieldElement): """ return mpfi_has_zero(self.__re) and mpfi_has_zero(self.__im) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Add ``self`` and ``right``. @@ -695,7 +695,7 @@ cdef class ComplexIntervalFieldElement(FieldElement): mpfi_add(x.__im, self.__im, (right).__im) return x - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Subtract ``self`` by ``right``. @@ -709,7 +709,7 @@ cdef class ComplexIntervalFieldElement(FieldElement): mpfi_sub(x.__im, self.__im, (right).__im) return x - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Multiply ``self`` and ``right``. @@ -779,7 +779,7 @@ cdef class ComplexIntervalFieldElement(FieldElement): mpfi_clear(t) return x - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Divide ``self`` by ``right``. @@ -1512,7 +1512,7 @@ cdef class ComplexIntervalFieldElement(FieldElement): """ return bool(self.real()) or bool(self.imag()) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: r""" As with the real interval fields this never returns false positives. diff --git a/src/sage/rings/complex_mpc.pxd b/src/sage/rings/complex_mpc.pxd index f7d8cb9492c..68fb73f4afa 100644 --- a/src/sage/rings/complex_mpc.pxd +++ b/src/sage/rings/complex_mpc.pxd @@ -6,9 +6,9 @@ cimport sage.rings.ring cdef class MPComplexNumber(sage.structure.element.FieldElement): cdef mpc_t value cdef char init - cdef MPComplexNumber _new(self) - cpdef _add_(self, other) - cpdef _mul_(self, other) + cdef MPComplexNumber _new(self) noexcept + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept cdef class MPComplexField_class(sage.rings.ring.Field): cdef readonly int _prec @@ -16,5 +16,5 @@ cdef class MPComplexField_class(sage.rings.ring.Field): cdef object __rnd_str cdef object __real_field cdef object __imag_field - cdef MPComplexNumber _new(self) - cpdef _an_element_(self) + cdef MPComplexNumber _new(self) noexcept + cpdef _an_element_(self) noexcept diff --git a/src/sage/rings/complex_mpc.pyx b/src/sage/rings/complex_mpc.pyx index ae2bd50c735..562286db44e 100644 --- a/src/sage/rings/complex_mpc.pyx +++ b/src/sage/rings/complex_mpc.pyx @@ -118,14 +118,14 @@ _mpc_rounding_modes = [ 'RNDNN', 'RNDZN', 'RNDUN', 'RNDDN', '', '', '', '', '', '', '', '', '', '', '', '', 'RNDDN', 'RNDZD', 'RNDUD', 'RNDDD' ] -cdef inline mpfr_rnd_t rnd_re(mpc_rnd_t rnd): +cdef inline mpfr_rnd_t rnd_re(mpc_rnd_t rnd) noexcept: """ Return the numeric value of the real part rounding mode. This is an internal function. """ return (rnd & 3) -cdef inline mpfr_rnd_t rnd_im(mpc_rnd_t rnd): +cdef inline mpfr_rnd_t rnd_im(mpc_rnd_t rnd) noexcept: """ Return the numeric value of the imaginary part rounding mode. This is an internal function. @@ -145,7 +145,7 @@ complex_ten = '(?P(?P' + sign + r')?\s*(?P' + sign + r')\s*(?P' + imaginary_ten + '))?)' re_complex_ten = re.compile(r'^\s*(?:' + complex_ten + r')\s*$', re.I) -cpdef inline split_complex_string(string, int base=10): +cpdef inline split_complex_string(string, int base=10) noexcept: """ Split and return in that order the real and imaginary parts of a complex in a string. @@ -322,7 +322,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field): ParentWithGens.__init__(self, self._real_field(), ('I',), False, category=Fields().Infinite()) self._populate_coercion_lists_(coerce_list=[MPFRtoMPC(self._real_field(), self)]) - cdef MPComplexNumber _new(self): + cdef MPComplexNumber _new(self) noexcept: """ Return a new complex number with parent ``self`. """ @@ -436,7 +436,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field): zz._set(z) return zz - cpdef _coerce_map_from_(self, S): + cpdef _coerce_map_from_(self, S) noexcept: """ Canonical coercion of `z` to this mpc complex field. @@ -538,7 +538,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field): """ return 1 - cpdef _an_element_(self): + cpdef _an_element_(self) noexcept: """ Return an element of this complex field. @@ -698,7 +698,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement): A floating point approximation to a complex number using any specified precision common to both real and imaginary part. """ - cdef MPComplexNumber _new(self): + cdef MPComplexNumber _new(self) noexcept: """ Return a new complex number with same parent as ``self``. """ @@ -1258,7 +1258,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement): """ return gmpy2.GMPy_MPC_From_mpfr(self.value.re, self.value.im) - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: r""" Compare ``self`` to ``other``. @@ -1375,7 +1375,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement): # Basic Arithmetic ################################ - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Add two complex numbers with the same parent. @@ -1390,7 +1390,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement): mpc_add(z.value, self.value, (right).value, (self._parent).__rnd) return z - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Subtract two complex numbers with the same parent. @@ -1405,7 +1405,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement): mpc_sub(z.value, self.value, (right).value, (self._parent).__rnd) return z - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Multiply two complex numbers with the same parent. @@ -1420,7 +1420,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement): mpc_mul(z.value, self.value, (right).value, (self._parent).__rnd) return z - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Divide two complex numbers with the same parent. @@ -1439,7 +1439,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement): mpc_div(z.value, self.value, x.value, (self._parent).__rnd) return z - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ Return the negative of this complex number. @@ -2391,12 +2391,12 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement): mpc_set(res.value, a.value, rnd) return res -cdef inline mp_exp_t min_exp_t(mp_exp_t a, mp_exp_t b): +cdef inline mp_exp_t min_exp_t(mp_exp_t a, mp_exp_t b) noexcept: return a if a < b else b -cdef inline mp_exp_t max_exp_t(mp_exp_t a, mp_exp_t b): +cdef inline mp_exp_t max_exp_t(mp_exp_t a, mp_exp_t b) noexcept: return a if a > b else b -cdef inline mp_exp_t max_exp(MPComplexNumber z): +cdef inline mp_exp_t max_exp(MPComplexNumber z) noexcept: """ Quickly return the maximum exponent of the real and complex parts of ``z``, which is useful for estimating its magnitude. @@ -2444,7 +2444,7 @@ __create_MPComplexNumber_version0 = __create__MPComplexNumber_version0 #***************************************************************************** cdef class MPCtoMPC(Map): - cpdef Element _call_(self, z): + cpdef Element _call_(self, z) noexcept: """ EXAMPLES:: @@ -2481,7 +2481,7 @@ cdef class MPCtoMPC(Map): return MPCtoMPC(self.codomain(), self.domain()) cdef class INTEGERtoMPC(Map): - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ EXAMPLES:: @@ -2504,7 +2504,7 @@ cdef class INTEGERtoMPC(Map): return y cdef class MPFRtoMPC(Map): - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ EXAMPLES:: @@ -2528,7 +2528,7 @@ cdef class MPFRtoMPC(Map): return y cdef class CCtoMPC(Map): - cpdef Element _call_(self, z): + cpdef Element _call_(self, z) noexcept: """ EXAMPLES:: diff --git a/src/sage/rings/complex_mpfr.pxd b/src/sage/rings/complex_mpfr.pxd index 9b8c8d08bf4..4aa6de62a69 100644 --- a/src/sage/rings/complex_mpfr.pxd +++ b/src/sage/rings/complex_mpfr.pxd @@ -9,9 +9,9 @@ cdef class ComplexNumber(sage.structure.element.FieldElement): cdef mpfr_prec_t _prec cdef object _multiplicative_order - cpdef _add_(self, other) - cpdef _mul_(self, other) - cdef RealNumber abs_c(ComplexNumber self) - cdef RealNumber norm_c(ComplexNumber self) + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept + cdef RealNumber abs_c(ComplexNumber self) noexcept + cdef RealNumber norm_c(ComplexNumber self) noexcept - cdef ComplexNumber _new(self) + cdef ComplexNumber _new(self) noexcept diff --git a/src/sage/rings/complex_mpfr.pyx b/src/sage/rings/complex_mpfr.pyx index 1862cea7bbf..d6f92bb2fee 100644 --- a/src/sage/rings/complex_mpfr.pyx +++ b/src/sage/rings/complex_mpfr.pyx @@ -867,7 +867,7 @@ cdef class ComplexNumber(sage.structure.element.FieldElement): True """ - cdef ComplexNumber _new(self): + cdef ComplexNumber _new(self) noexcept: """ Quickly creates a new initialized complex number with the same parent as ``self``. @@ -1460,7 +1460,7 @@ cdef class ComplexNumber(sage.structure.element.FieldElement): import sympy return self.real()._sympy_() + self.imag()._sympy_() * sympy.I - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Add ``self`` to ``right``. @@ -1475,7 +1475,7 @@ cdef class ComplexNumber(sage.structure.element.FieldElement): mpfr_add(x.__im, self.__im, (right).__im, rnd) return x - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Subtract ``right`` from ``self``. @@ -1490,7 +1490,7 @@ cdef class ComplexNumber(sage.structure.element.FieldElement): mpfr_sub(x.__im, self.__im, (right).__im, rnd) return x - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Multiply ``self`` by ``right``. @@ -1559,7 +1559,7 @@ cdef class ComplexNumber(sage.structure.element.FieldElement): """ return self.norm_c() - cdef RealNumber norm_c(ComplexNumber self): + cdef RealNumber norm_c(ComplexNumber self) noexcept: cdef RealNumber x x = RealNumber(self._parent._real_field(), None) @@ -1576,7 +1576,7 @@ cdef class ComplexNumber(sage.structure.element.FieldElement): mpfr_clear(t1) return x - cdef RealNumber abs_c(ComplexNumber self): + cdef RealNumber abs_c(ComplexNumber self) noexcept: cdef RealNumber x x = RealNumber(self._parent._real_field(), None) @@ -1594,7 +1594,7 @@ cdef class ComplexNumber(sage.structure.element.FieldElement): mpfr_clear(t1) return x - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Divide ``self`` by ``right``. @@ -1951,7 +1951,7 @@ cdef class ComplexNumber(sage.structure.element.FieldElement): return complex(mpfr_get_d(self.__re, rnd), mpfr_get_d(self.__im, rnd)) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Compare ``left`` and ``right``. @@ -3340,7 +3340,7 @@ cdef class RRtoCC(Map): self._zero = ComplexNumber(CC, 0) self._repr_type_str = "Natural" - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ A helper for pickling and copying. @@ -3366,7 +3366,7 @@ cdef class RRtoCC(Map): slots['_zero'] = self._zero return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ A helper for unpickling and copying. @@ -3385,7 +3385,7 @@ cdef class RRtoCC(Map): Map._update_slots(self, _slots) self._zero = _slots['_zero'] - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ EXAMPLES:: @@ -3399,13 +3399,13 @@ cdef class RRtoCC(Map): mpfr_set_ui(z.__im, 0, rnd) return z -cdef inline mp_exp_t min_exp_t(mp_exp_t a, mp_exp_t b): +cdef inline mp_exp_t min_exp_t(mp_exp_t a, mp_exp_t b) noexcept: return a if a < b else b -cdef inline mp_exp_t max_exp_t(mp_exp_t a, mp_exp_t b): +cdef inline mp_exp_t max_exp_t(mp_exp_t a, mp_exp_t b) noexcept: return a if a > b else b -cdef inline mp_exp_t max_exp(ComplexNumber z): +cdef inline mp_exp_t max_exp(ComplexNumber z) noexcept: """ Quickly return the maximum exponent of the real and complex parts of z, which is useful for estimating its magnitude. @@ -3416,7 +3416,7 @@ cdef inline mp_exp_t max_exp(ComplexNumber z): return mpfr_get_exp(z.__im) return max_exp_t(mpfr_get_exp(z.__re), mpfr_get_exp(z.__im)) -cpdef int cmp_abs(ComplexNumber a, ComplexNumber b): +cpdef int cmp_abs(ComplexNumber a, ComplexNumber b) noexcept: """ Return `-1`, `0`, or `1` according to whether `|a|` is less than, equal to, or greater than `|b|`. diff --git a/src/sage/rings/convert/mpfi.pyx b/src/sage/rings/convert/mpfi.pyx index 3ca01ac276f..abef4963bcf 100644 --- a/src/sage/rings/convert/mpfi.pyx +++ b/src/sage/rings/convert/mpfi.pyx @@ -35,7 +35,7 @@ from ..complex_double cimport ComplexDoubleElement from cypari2.gen cimport Gen -cdef inline int return_real(mpfi_ptr im): +cdef inline int return_real(mpfi_ptr im) noexcept: """ Called by ``mpfi_set_sage`` on the imaginary part when converting a real number. diff --git a/src/sage/rings/factorint.pyx b/src/sage/rings/factorint.pyx index d4df0e5ea05..ad0b735eaaa 100644 --- a/src/sage/rings/factorint.pyx +++ b/src/sage/rings/factorint.pyx @@ -30,7 +30,7 @@ from sage.misc.misc_c import prod cdef extern from "limits.h": long LONG_MAX -cpdef aurifeuillian(n, m, F=None, bint check=True): +cpdef aurifeuillian(n, m, F=None, bint check=True) noexcept: r""" Return the Aurifeuillian factors `F_n^\pm(m^2n)`. @@ -114,7 +114,7 @@ cpdef aurifeuillian(n, m, F=None, bint check=True): assert (not check or Fm.divides(F)) return [Fm, F // Fm] -cpdef factor_aurifeuillian(n, check=True): +cpdef factor_aurifeuillian(n, check=True) noexcept: r""" Return Aurifeuillian factors of `n` if `n = x^{(2k-1)x} \pm 1` (where the sign is '-' if x = 1 mod 4, and '+' otherwise) else `n` @@ -245,7 +245,7 @@ def factor_cunningham(m, proof=None): else: return IntegerFactorization(L)*n.factor(proof=proof) -cpdef factor_trial_division(m, long limit=LONG_MAX): +cpdef factor_trial_division(m, long limit=LONG_MAX) noexcept: r""" Return partial factorization of ``self`` obtained using trial division for all primes up to ``limit``, where ``limit`` must fit in a C ``signed long``. diff --git a/src/sage/rings/fast_arith.pxd b/src/sage/rings/fast_arith.pxd index 7a99e658b91..c13e5e36548 100644 --- a/src/sage/rings/fast_arith.pxd +++ b/src/sage/rings/fast_arith.pxd @@ -1,4 +1,4 @@ -cpdef prime_range(start, stop=*, algorithm=*, bint py_ints=*) +cpdef prime_range(start, stop=*, algorithm=*, bint py_ints=*) noexcept cdef class arith_int: cdef int abs_int(self, int x) except -1 diff --git a/src/sage/rings/fast_arith.pyx b/src/sage/rings/fast_arith.pyx index 0eca810920e..5d43ed41c6f 100644 --- a/src/sage/rings/fast_arith.pyx +++ b/src/sage/rings/fast_arith.pyx @@ -40,7 +40,7 @@ from libc.math cimport sqrt from sage.rings.integer cimport Integer -cpdef prime_range(start, stop=None, algorithm=None, bint py_ints=False): +cpdef prime_range(start, stop=None, algorithm=None, bint py_ints=False) noexcept: r""" Return a list of all primes between ``start`` and ``stop - 1``, inclusive. diff --git a/src/sage/rings/finite_rings/element_base.pxd b/src/sage/rings/finite_rings/element_base.pxd index c214e4745a9..ec09f9cc769 100644 --- a/src/sage/rings/finite_rings/element_base.pxd +++ b/src/sage/rings/finite_rings/element_base.pxd @@ -8,5 +8,5 @@ cdef class FinitePolyExtElement(FiniteRingElement): pass cdef class Cache_base(SageObject): - cpdef FinitePolyExtElement fetch_int(self, number) + cpdef FinitePolyExtElement fetch_int(self, number) noexcept diff --git a/src/sage/rings/finite_rings/element_base.pyx b/src/sage/rings/finite_rings/element_base.pyx index e9ab5b5d4ab..beeae9fa4c9 100755 --- a/src/sage/rings/finite_rings/element_base.pyx +++ b/src/sage/rings/finite_rings/element_base.pyx @@ -1077,7 +1077,7 @@ cdef class FinitePolyExtElement(FiniteRingElement): integer_representation = deprecated_function_alias(33941, to_integer) cdef class Cache_base(SageObject): - cpdef FinitePolyExtElement fetch_int(self, number): + cpdef FinitePolyExtElement fetch_int(self, number) noexcept: r""" Given an integer less than `p^n` with base `2` representation `a_0 + a_1 \cdot 2 + \cdots + a_k 2^k`, this returns diff --git a/src/sage/rings/finite_rings/element_givaro.pxd b/src/sage/rings/finite_rings/element_givaro.pxd index c4d16de21f5..1e5c4b46527 100644 --- a/src/sage/rings/finite_rings/element_givaro.pxd +++ b/src/sage/rings/finite_rings/element_givaro.pxd @@ -62,7 +62,7 @@ cdef class FiniteField_givaroElement(FinitePolyExtElement): cdef int element cdef Cache_givaro _cache cdef object _multiplicative_order - cdef FiniteField_givaroElement _new_c(self, int value) + cdef FiniteField_givaroElement _new_c(self, int value) noexcept cdef class Cache_givaro(Cache_base): cdef GivaroGfq *objectptr # C++ object @@ -73,13 +73,13 @@ cdef class Cache_givaro(Cache_base): cdef bint _has_array cdef bint _is_conway cdef Parent parent - cdef gen_array(self) - cpdef int exponent(self) - cpdef int order_c(self) - cpdef int characteristic(self) - cpdef FiniteField_givaroElement gen(self) - cpdef FiniteField_givaroElement element_from_data(self, e) - cdef FiniteField_givaroElement _new_c(self, int value) + cdef gen_array(self) noexcept + cpdef int exponent(self) noexcept + cpdef int order_c(self) noexcept + cpdef int characteristic(self) noexcept + cpdef FiniteField_givaroElement gen(self) noexcept + cpdef FiniteField_givaroElement element_from_data(self, e) noexcept + cdef FiniteField_givaroElement _new_c(self, int value) noexcept cpdef int int_to_log(self, int i) except -1 cpdef int log_to_int(self, int i) except -1 @@ -87,4 +87,4 @@ cdef class FiniteField_givaro_iterator: cdef int iterator cdef Cache_givaro _cache -cdef FiniteField_givaroElement make_FiniteField_givaroElement(Cache_givaro cache, int x) +cdef FiniteField_givaroElement make_FiniteField_givaroElement(Cache_givaro cache, int x) noexcept diff --git a/src/sage/rings/finite_rings/element_givaro.pyx b/src/sage/rings/finite_rings/element_givaro.pyx index ead2551ded5..0483b4949e7 100644 --- a/src/sage/rings/finite_rings/element_givaro.pyx +++ b/src/sage/rings/finite_rings/element_givaro.pyx @@ -76,7 +76,7 @@ cdef object MPolynomial cdef object Polynomial -cdef void late_import(): +cdef void late_import() noexcept: """ Late import of modules """ @@ -208,7 +208,7 @@ cdef class Cache_givaro(Cache_base): self._array = self.gen_array() self._has_array = True - cdef gen_array(self): + cdef gen_array(self) noexcept: """ Generates an array/list/tuple containing all elements of ``self`` indexed by their power with respect to the internal generator. @@ -226,7 +226,7 @@ cdef class Cache_givaro(Cache_base): """ delete(self.objectptr) - cpdef int characteristic(self): + cpdef int characteristic(self) noexcept: """ Return the characteristic of this field. @@ -249,7 +249,7 @@ cdef class Cache_givaro(Cache_base): """ return Integer(self.order_c()) - cpdef int order_c(self): + cpdef int order_c(self) noexcept: """ Return the order of this field. @@ -261,7 +261,7 @@ cdef class Cache_givaro(Cache_base): """ return self.objectptr.cardinality() - cpdef int exponent(self): + cpdef int exponent(self) noexcept: r""" Return the degree of this field over `\GF{p}`. @@ -295,7 +295,7 @@ cdef class Cache_givaro(Cache_base): self.objectptr.random(generator, res) return make_FiniteField_givaroElement(self, res) - cpdef FiniteField_givaroElement element_from_data(self, e): + cpdef FiniteField_givaroElement element_from_data(self, e) noexcept: """ Coerces several data types to ``self``. @@ -466,7 +466,7 @@ cdef class Cache_givaro(Cache_base): return make_FiniteField_givaroElement(self, res) - cpdef FiniteField_givaroElement gen(self): + cpdef FiniteField_givaroElement gen(self) noexcept: """ Return a generator of the field. @@ -546,7 +546,7 @@ cdef class Cache_givaro(Cache_base): sig_off() return r - cpdef FiniteField_givaroElement fetch_int(self, number): + cpdef FiniteField_givaroElement fetch_int(self, number) noexcept: r""" Given an integer ``n`` return a finite field element in ``self`` which equals ``n`` under the condition that :meth:`gen()` is set to @@ -754,7 +754,7 @@ cdef class Cache_givaro(Cache_base): rep = 'int' return unpickle_Cache_givaro, (self.parent, p, k, self.parent.polynomial(), rep, self._has_array) - cdef FiniteField_givaroElement _new_c(self, int value): + cdef FiniteField_givaroElement _new_c(self, int value) noexcept: return make_FiniteField_givaroElement(self, value) @@ -872,7 +872,7 @@ cdef class FiniteField_givaroElement(FinitePolyExtElement): self._cache = parent._cache self.element = 0 - cdef FiniteField_givaroElement _new_c(self, int value): + cdef FiniteField_givaroElement _new_c(self, int value) noexcept: return make_FiniteField_givaroElement(self._cache, value) def __dealloc__(FiniteField_givaroElement self): @@ -1076,7 +1076,7 @@ cdef class FiniteField_givaroElement(FinitePolyExtElement): else: raise ValueError("must be a perfect square.") - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Add two elements. @@ -1091,7 +1091,7 @@ cdef class FiniteField_givaroElement(FinitePolyExtElement): (right).element) return make_FiniteField_givaroElement(self._cache, r) - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Multiply two elements. @@ -1108,7 +1108,7 @@ cdef class FiniteField_givaroElement(FinitePolyExtElement): (right).element) return make_FiniteField_givaroElement(self._cache, r) - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Divide two elements @@ -1130,7 +1130,7 @@ cdef class FiniteField_givaroElement(FinitePolyExtElement): (right).element) return make_FiniteField_givaroElement(self._cache, r) - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Subtract two elements. @@ -1281,7 +1281,7 @@ cdef class FiniteField_givaroElement(FinitePolyExtElement): return make_FiniteField_givaroElement(cache, cache.objectptr.one) return make_FiniteField_givaroElement(cache, r) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Comparison of finite field elements is correct or equality tests and somewhat random for ``<`` and ``>`` type of @@ -1738,7 +1738,7 @@ def unpickle_FiniteField_givaroElement(parent, int x): from sage.misc.persist import register_unpickle_override register_unpickle_override('sage.rings.finite_field_givaro', 'unpickle_FiniteField_givaroElement', unpickle_FiniteField_givaroElement) -cdef inline FiniteField_givaroElement make_FiniteField_givaroElement(Cache_givaro cache, int x): +cdef inline FiniteField_givaroElement make_FiniteField_givaroElement(Cache_givaro cache, int x) noexcept: cdef FiniteField_givaroElement y if cache._has_array: diff --git a/src/sage/rings/finite_rings/element_ntl_gf2e.pxd b/src/sage/rings/finite_rings/element_ntl_gf2e.pxd index e98744413b5..b699f6e3ef6 100644 --- a/src/sage/rings/finite_rings/element_ntl_gf2e.pxd +++ b/src/sage/rings/finite_rings/element_ntl_gf2e.pxd @@ -13,9 +13,9 @@ cdef class Cache_ntl_gf2e(Cache_base): cdef public FiniteField_ntl_gf2eElement _gen cdef Integer _order cdef Integer _degree - cdef FiniteField_ntl_gf2eElement _new(self) + cdef FiniteField_ntl_gf2eElement _new(self) noexcept cdef class FiniteField_ntl_gf2eElement(FinitePolyExtElement): cdef GF2E_c x cdef Cache_ntl_gf2e _cache - cdef FiniteField_ntl_gf2eElement _new(FiniteField_ntl_gf2eElement self) + cdef FiniteField_ntl_gf2eElement _new(FiniteField_ntl_gf2eElement self) noexcept diff --git a/src/sage/rings/finite_rings/element_ntl_gf2e.pyx b/src/sage/rings/finite_rings/element_ntl_gf2e.pyx index 7c5ab521b7a..ef41e6d8dc1 100644 --- a/src/sage/rings/finite_rings/element_ntl_gf2e.pyx +++ b/src/sage/rings/finite_rings/element_ntl_gf2e.pyx @@ -96,10 +96,10 @@ cdef int late_import() except -1: cdef extern from "arpa/inet.h": unsigned int htonl(unsigned int) -cdef little_endian(): +cdef little_endian() noexcept: return htonl(1) != 1 -cdef unsigned int switch_endianess(unsigned int i): +cdef unsigned int switch_endianess(unsigned int i) noexcept: cdef size_t j cdef unsigned int ret = 0 for j in range(sizeof(int)): @@ -205,7 +205,7 @@ cdef class Cache_ntl_gf2e(Cache_base): mod_poly = GF2XModulus_GF2X(modulus) print(ccrepr(mod_poly)) - cdef FiniteField_ntl_gf2eElement _new(self): + cdef FiniteField_ntl_gf2eElement _new(self) noexcept: """ Return a new element in ``self``. Use this method to construct 'empty' elements. @@ -374,7 +374,7 @@ cdef class Cache_ntl_gf2e(Cache_base): raise ValueError("Cannot coerce element %s to this field." % e) - cpdef FiniteField_ntl_gf2eElement fetch_int(self, number): + cpdef FiniteField_ntl_gf2eElement fetch_int(self, number) noexcept: r""" Given an integer less than `p^n` with base `2` representation `a_0 + a_1 \cdot 2 + \cdots + a_k 2^k`, this returns @@ -508,7 +508,7 @@ cdef class FiniteField_ntl_gf2eElement(FinitePolyExtElement): self._parent = parent (self._parent._cache).F.restore() - cdef FiniteField_ntl_gf2eElement _new(FiniteField_ntl_gf2eElement self): + cdef FiniteField_ntl_gf2eElement _new(FiniteField_ntl_gf2eElement self) noexcept: cdef FiniteField_ntl_gf2eElement y (self._parent._cache).F.restore() y = FiniteField_ntl_gf2eElement.__new__(FiniteField_ntl_gf2eElement) @@ -654,7 +654,7 @@ cdef class FiniteField_ntl_gf2eElement(FinitePolyExtElement): else: return a - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Add two elements. @@ -670,7 +670,7 @@ cdef class FiniteField_ntl_gf2eElement(FinitePolyExtElement): GF2E_add(r.x, (self).x, (right).x) return r - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Multiply two elements. @@ -686,7 +686,7 @@ cdef class FiniteField_ntl_gf2eElement(FinitePolyExtElement): GF2E_mul(r.x, (self).x, (right).x) return r - cpdef _div_(self, other): + cpdef _div_(self, other) noexcept: """ Divide two elements. @@ -709,7 +709,7 @@ cdef class FiniteField_ntl_gf2eElement(FinitePolyExtElement): GF2E_div(r.x, self.x, o.x) return r - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Subtract two elements. @@ -758,7 +758,7 @@ cdef class FiniteField_ntl_gf2eElement(FinitePolyExtElement): cdef FiniteField_ntl_gf2eElement o = self._parent._cache._one_element return o._div_(self) - cdef _pow_long(self, long n): + cdef _pow_long(self, long n) noexcept: """ EXAMPLES:: @@ -797,7 +797,7 @@ cdef class FiniteField_ntl_gf2eElement(FinitePolyExtElement): GF2E_power(r.x, self.x, n) return r - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Comparison of finite field elements. diff --git a/src/sage/rings/finite_rings/element_pari_ffelt.pxd b/src/sage/rings/finite_rings/element_pari_ffelt.pxd index 0b66436dcd4..f80aeb55532 100644 --- a/src/sage/rings/finite_rings/element_pari_ffelt.pxd +++ b/src/sage/rings/finite_rings/element_pari_ffelt.pxd @@ -7,6 +7,6 @@ cdef class FiniteFieldElement_pari_ffelt(FinitePolyExtElement): # This holds a reference to a PARI clone. cdef GEN val - cdef FiniteFieldElement_pari_ffelt _new(self) - cdef void construct(self, GEN g) + cdef FiniteFieldElement_pari_ffelt _new(self) noexcept + cdef void construct(self, GEN g) noexcept cdef int construct_from(self, x) except -1 diff --git a/src/sage/rings/finite_rings/element_pari_ffelt.pyx b/src/sage/rings/finite_rings/element_pari_ffelt.pyx index 2d29f424e3b..792aa9ce257 100644 --- a/src/sage/rings/finite_rings/element_pari_ffelt.pyx +++ b/src/sage/rings/finite_rings/element_pari_ffelt.pyx @@ -345,7 +345,7 @@ cdef class FiniteFieldElement_pari_ffelt(FinitePolyExtElement): if self.val is not NULL: gunclone_deep(self.val) - cdef FiniteFieldElement_pari_ffelt _new(self): + cdef FiniteFieldElement_pari_ffelt _new(self) noexcept: """ Create an empty element with the same parent as ``self``. """ @@ -354,7 +354,7 @@ cdef class FiniteFieldElement_pari_ffelt(FinitePolyExtElement): x._parent = self._parent return x - cdef void construct(self, GEN g): + cdef void construct(self, GEN g) noexcept: """ Initialise ``self`` to the FFELT ``g``, reset the PARI stack, and call sig_off(). @@ -599,7 +599,7 @@ cdef class FiniteFieldElement_pari_ffelt(FinitePolyExtElement): # immutable return self - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ Comparison of finite field elements. @@ -659,7 +659,7 @@ cdef class FiniteFieldElement_pari_ffelt(FinitePolyExtElement): sig_off() return rich_to_bool(op, r) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Addition. @@ -675,7 +675,7 @@ cdef class FiniteFieldElement_pari_ffelt(FinitePolyExtElement): (right).val)) return x - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Subtraction. @@ -691,7 +691,7 @@ cdef class FiniteFieldElement_pari_ffelt(FinitePolyExtElement): (right).val)) return x - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Multiplication. @@ -707,7 +707,7 @@ cdef class FiniteFieldElement_pari_ffelt(FinitePolyExtElement): (right).val)) return x - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Division. diff --git a/src/sage/rings/finite_rings/finite_field_base.pyx b/src/sage/rings/finite_rings/finite_field_base.pyx index 4e799ad57e8..c60f3d2ec07 100644 --- a/src/sage/rings/finite_rings/finite_field_base.pyx +++ b/src/sage/rings/finite_rings/finite_field_base.pyx @@ -1316,7 +1316,7 @@ cdef class FiniteField(Field): return V, phi, psi - cpdef _coerce_map_from_(self, R): + cpdef _coerce_map_from_(self, R) noexcept: r""" Canonical coercion to ``self``. @@ -1387,7 +1387,7 @@ cdef class FiniteField(Field): and hasattr(self, '_prefix') and hasattr(R, '_prefix')): return R.hom((self.gen() ** ((self.order() - 1)//(R.order() - 1)),)) - cpdef _convert_map_from_(self, R): + cpdef _convert_map_from_(self, R) noexcept: """ Conversion from p-adic fields. diff --git a/src/sage/rings/finite_rings/hom_finite_field.pxd b/src/sage/rings/finite_rings/hom_finite_field.pxd index 199d655d6d6..64da809024f 100644 --- a/src/sage/rings/finite_rings/hom_finite_field.pxd +++ b/src/sage/rings/finite_rings/hom_finite_field.pxd @@ -11,7 +11,7 @@ cdef class FiniteFieldHomomorphism_generic(RingHomomorphism_im_gens): cdef _gen cdef _section_class - cpdef Element _call_(self, x) + cpdef Element _call_(self, x) noexcept cdef class FrobeniusEndomorphism_finite_field(FrobeniusEndomorphism_generic): @@ -19,4 +19,4 @@ cdef class FrobeniusEndomorphism_finite_field(FrobeniusEndomorphism_generic): cdef long _degree_fixed cdef long _order - cpdef Element _call_(self, x) + cpdef Element _call_(self, x) noexcept diff --git a/src/sage/rings/finite_rings/hom_finite_field.pyx b/src/sage/rings/finite_rings/hom_finite_field.pyx index fa38753d79f..5f54c04dd36 100644 --- a/src/sage/rings/finite_rings/hom_finite_field.pyx +++ b/src/sage/rings/finite_rings/hom_finite_field.pyx @@ -121,7 +121,7 @@ cdef class SectionFiniteFieldHomomorphism_generic(Section): """ A class implementing sections of embeddings between finite fields. """ - cpdef Element _call_(self, x): # Not optimized + cpdef Element _call_(self, x) noexcept: # Not optimized """ TESTS:: @@ -291,7 +291,7 @@ cdef class FiniteFieldHomomorphism_generic(RingHomomorphism_im_gens): """ return self.domain()._latex_() + " \\hookrightarrow " + self.codomain()._latex_() - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ TESTS:: @@ -426,7 +426,7 @@ cdef class FiniteFieldHomomorphism_generic(RingHomomorphism_im_gens): """ return Morphism.__hash__(self) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: r""" Helper function for copying and pickling @@ -454,7 +454,7 @@ cdef class FiniteFieldHomomorphism_generic(RingHomomorphism_im_gens): slots['_section_class'] = self._section_class return slots - cdef _update_slots(self, dict slots): + cdef _update_slots(self, dict slots) noexcept: r""" Helper function for copying and pickling @@ -609,7 +609,7 @@ cdef class FrobeniusEndomorphism_finite_field(FrobeniusEndomorphism_generic): return s - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ TESTS:: @@ -830,7 +830,7 @@ cdef class FrobeniusEndomorphism_finite_field(FrobeniusEndomorphism_generic): """ return Morphism.__hash__(self) - cdef _update_slots(self, dict slots): + cdef _update_slots(self, dict slots) noexcept: r""" Helper function for copying and pickling diff --git a/src/sage/rings/finite_rings/hom_finite_field_givaro.pxd b/src/sage/rings/finite_rings/hom_finite_field_givaro.pxd index eec5a6d299d..62898386212 100644 --- a/src/sage/rings/finite_rings/hom_finite_field_givaro.pxd +++ b/src/sage/rings/finite_rings/hom_finite_field_givaro.pxd @@ -11,7 +11,7 @@ cdef class SectionFiniteFieldHomomorphism_givaro(SectionFiniteFieldHomomorphism_ cdef long _power cdef Cache_givaro _codomain_cache - cpdef Element _call_(self, x) + cpdef Element _call_(self, x) noexcept cdef class FiniteFieldHomomorphism_givaro(FiniteFieldHomomorphism_generic): @@ -20,7 +20,7 @@ cdef class FiniteFieldHomomorphism_givaro(FiniteFieldHomomorphism_generic): cdef long _power cdef Cache_givaro _codomain_cache - cpdef Element _call_(self, x) + cpdef Element _call_(self, x) noexcept cdef class FrobeniusEndomorphism_givaro(FrobeniusEndomorphism_finite_field): diff --git a/src/sage/rings/finite_rings/hom_finite_field_givaro.pyx b/src/sage/rings/finite_rings/hom_finite_field_givaro.pyx index aae6c84ab25..21036266df1 100644 --- a/src/sage/rings/finite_rings/hom_finite_field_givaro.pyx +++ b/src/sage/rings/finite_rings/hom_finite_field_givaro.pyx @@ -96,7 +96,7 @@ cdef class SectionFiniteFieldHomomorphism_givaro(SectionFiniteFieldHomomorphism_ self._codomain_cache = ((self._codomain.gen()))._cache - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ TESTS:: @@ -174,7 +174,7 @@ cdef class FiniteFieldHomomorphism_givaro(FiniteFieldHomomorphism_generic): self._order_codomain = codomain.cardinality() - 1 - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ TESTS:: @@ -263,7 +263,7 @@ cdef class FrobeniusEndomorphism_givaro(FrobeniusEndomorphism_finite_field): # copied from element_givaro.pyx -cdef inline FiniteField_givaroElement make_FiniteField_givaroElement(Cache_givaro cache, int x): +cdef inline FiniteField_givaroElement make_FiniteField_givaroElement(Cache_givaro cache, int x) noexcept: cdef FiniteField_givaroElement y if cache._has_array: diff --git a/src/sage/rings/finite_rings/hom_prime_finite_field.pyx b/src/sage/rings/finite_rings/hom_prime_finite_field.pyx index e141120d918..6bc38546612 100644 --- a/src/sage/rings/finite_rings/hom_prime_finite_field.pyx +++ b/src/sage/rings/finite_rings/hom_prime_finite_field.pyx @@ -35,7 +35,7 @@ from sage.rings.finite_rings.finite_field_base import FiniteField cdef class SectionFiniteFieldHomomorphism_prime(SectionFiniteFieldHomomorphism_generic): - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: try: return self._codomain._element_constructor(x) except TypeError: @@ -75,7 +75,7 @@ cdef class FiniteFieldHomomorphism_prime(FiniteFieldHomomorphism_generic): FiniteFieldHomomorphism_generic.__init__(self, parent, im_gens, base_map=base_map, check=check, section_class=section_class) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ TESTS:: @@ -104,7 +104,7 @@ cdef class FrobeniusEndomorphism_prime(FrobeniusEndomorphism_finite_field): self._order = 1 self._power = 0 - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ TESTS:: diff --git a/src/sage/rings/finite_rings/integer_mod.pxd b/src/sage/rings/finite_rings/integer_mod.pxd index 351ffa25e1b..5d16bad880e 100644 --- a/src/sage/rings/finite_rings/integer_mod.pxd +++ b/src/sage/rings/finite_rings/integer_mod.pxd @@ -10,7 +10,7 @@ cdef class NativeIntStruct: cdef int_fast64_t int64 cdef readonly list table # list of elements of IntegerModRing(n) cdef readonly list inverses # list of inverses (None if not invertible) - cdef inline type element_class(self): + cdef inline type element_class(self) noexcept: if self.int32 > 0: return IntegerMod_int elif self.int64 > 0: @@ -21,35 +21,35 @@ cdef class NativeIntStruct: cdef class IntegerMod_abstract(FiniteRingElement): cdef NativeIntStruct _modulus - cdef _new_c_from_long(self, long value) - cdef IntegerMod_abstract _new_c_fast(self, unsigned long value) - cdef void set_from_mpz(self, mpz_t value) - cdef void set_from_long(self, long value) - cdef void set_from_ulong_fast(self, unsigned long value) + cdef _new_c_from_long(self, long value) noexcept + cdef IntegerMod_abstract _new_c_fast(self, unsigned long value) noexcept + cdef void set_from_mpz(self, mpz_t value) noexcept + cdef void set_from_long(self, long value) noexcept + cdef void set_from_ulong_fast(self, unsigned long value) noexcept cdef bint is_square_c(self) except -2 - cpdef bint is_one(self) - cpdef bint is_unit(self) - cpdef _floordiv_(self, other) + cpdef bint is_one(self) noexcept + cpdef bint is_unit(self) noexcept + cpdef _floordiv_(self, other) noexcept cdef class IntegerMod_gmp(IntegerMod_abstract): cdef mpz_t value - cdef IntegerMod_gmp _new_c(self) - cdef shift(IntegerMod_gmp self, long k) + cdef IntegerMod_gmp _new_c(self) noexcept + cdef shift(IntegerMod_gmp self, long k) noexcept cdef class IntegerMod_int(IntegerMod_abstract): cdef int_fast32_t ivalue - cdef void set_from_int(IntegerMod_int self, int_fast32_t value) - cdef int_fast32_t get_int_value(IntegerMod_int self) - cdef IntegerMod_int _new_c(self, int_fast32_t value) - cdef shift(IntegerMod_int self, int k) + cdef void set_from_int(IntegerMod_int self, int_fast32_t value) noexcept + cdef int_fast32_t get_int_value(IntegerMod_int self) noexcept + cdef IntegerMod_int _new_c(self, int_fast32_t value) noexcept + cdef shift(IntegerMod_int self, int k) noexcept cdef class IntegerMod_int64(IntegerMod_abstract): cdef int_fast64_t ivalue - cdef void set_from_int(IntegerMod_int64 self, int_fast64_t value) - cdef int_fast64_t get_int_value(IntegerMod_int64 self) - cdef IntegerMod_int64 _new_c(self, int_fast64_t value) - cdef shift(IntegerMod_int64 self, int k) + cdef void set_from_int(IntegerMod_int64 self, int_fast64_t value) noexcept + cdef int_fast64_t get_int_value(IntegerMod_int64 self) noexcept + cdef IntegerMod_int64 _new_c(self, int_fast64_t value) noexcept + cdef shift(IntegerMod_int64 self, int k) noexcept cdef int_fast32_t mod_inverse_int(int_fast32_t x, int_fast32_t n) except 0 -cdef bint use_32bit_type(int_fast64_t modulus) +cdef bint use_32bit_type(int_fast64_t modulus) noexcept diff --git a/src/sage/rings/finite_rings/integer_mod.pyx b/src/sage/rings/finite_rings/integer_mod.pyx index 4fb4656cdd2..b2cd1a1fa24 100644 --- a/src/sage/rings/finite_rings/integer_mod.pyx +++ b/src/sage/rings/finite_rings/integer_mod.pyx @@ -78,7 +78,7 @@ from libc.math cimport log2, ceil from sage.libs.gmp.all cimport * -cdef bint use_32bit_type(int_fast64_t modulus): +cdef bint use_32bit_type(int_fast64_t modulus) noexcept: return modulus <= INTEGER_MOD_INT32_LIMIT from sage.arith.long cimport ( @@ -219,7 +219,7 @@ def is_IntegerMod(x): return isinstance(x, IntegerMod_abstract) -cdef inline inverse_or_None(x): +cdef inline inverse_or_None(x) noexcept: try: return ~x except ArithmeticError: @@ -393,7 +393,7 @@ cdef class IntegerMod_abstract(FiniteRingElement): raise self.set_from_mpz(z.value) - cdef IntegerMod_abstract _new_c_fast(self, unsigned long value): + cdef IntegerMod_abstract _new_c_fast(self, unsigned long value) noexcept: cdef type t = type(self) x = t.__new__(t) x._parent = self._parent @@ -401,7 +401,7 @@ cdef class IntegerMod_abstract(FiniteRingElement): x.set_from_ulong_fast(value) return x - cdef _new_c_from_long(self, long value): + cdef _new_c_from_long(self, long value) noexcept: cdef type t = type(self) cdef IntegerMod_abstract x = t.__new__(t) x._parent = self._parent @@ -409,13 +409,13 @@ cdef class IntegerMod_abstract(FiniteRingElement): x.set_from_long(value) return x - cdef void set_from_mpz(self, mpz_t value): + cdef void set_from_mpz(self, mpz_t value) noexcept: raise NotImplementedError("must be defined in child class") - cdef void set_from_long(self, long value): + cdef void set_from_long(self, long value) noexcept: raise NotImplementedError("must be defined in child class") - cdef void set_from_ulong_fast(self, unsigned long value): + cdef void set_from_ulong_fast(self, unsigned long value) noexcept: """ Set ``self`` to the value in ``value`` where ``value`` is assumed to be less than the modulus @@ -999,10 +999,10 @@ cdef class IntegerMod_abstract(FiniteRingElement): else: return x - n - cpdef bint is_one(self): + cpdef bint is_one(self) noexcept: raise NotImplementedError - cpdef bint is_unit(self): + cpdef bint is_unit(self) noexcept: raise NotImplementedError @coerce_binop @@ -1916,7 +1916,7 @@ cdef class IntegerMod_abstract(FiniteRingElement): return infinity return r - cpdef _floordiv_(self, right): + cpdef _floordiv_(self, right) noexcept: """ Exact division for prime moduli, for compatibility with other fields. @@ -1975,7 +1975,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract): def __cinit__(self): mpz_init(self.value) - cdef IntegerMod_gmp _new_c(self): + cdef IntegerMod_gmp _new_c(self) noexcept: cdef IntegerMod_gmp x x = IntegerMod_gmp.__new__(IntegerMod_gmp) x._modulus = self._modulus @@ -1985,12 +1985,12 @@ cdef class IntegerMod_gmp(IntegerMod_abstract): def __dealloc__(self): mpz_clear(self.value) - cdef void set_from_mpz(self, mpz_t value): + cdef void set_from_mpz(self, mpz_t value) noexcept: cdef sage.rings.integer.Integer modulus modulus = self._modulus.sageInteger mpz_mod(self.value, value, modulus.value) - cdef void set_from_long(self, long value): + cdef void set_from_long(self, long value) noexcept: r""" EXAMPLES:: @@ -2001,7 +2001,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract): mpz_set_si(self.value, value) mpz_mod(self.value, self.value, self._modulus.sageInteger.value) - cdef void set_from_ulong_fast(self, unsigned long value): + cdef void set_from_ulong_fast(self, unsigned long value) noexcept: mpz_set_ui(self.value, value) def __lshift__(IntegerMod_gmp self, k): @@ -2032,7 +2032,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract): """ return self.shift(-long(k)) - cdef shift(IntegerMod_gmp self, long k): + cdef shift(IntegerMod_gmp self, long k) noexcept: r""" Performs a bit-shift specified by ``k`` on ``self``. @@ -2074,7 +2074,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract): mpz_fdiv_q_2exp(x.value, self.value, -k) return x - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ EXAMPLES:: @@ -2089,7 +2089,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract): i = mpz_cmp((left).value, (right).value) return rich_to_bool_sgn(op, i) - cpdef bint is_one(IntegerMod_gmp self): + cpdef bint is_one(IntegerMod_gmp self) noexcept: """ Returns ``True`` if this is `1`, otherwise ``False``. @@ -2117,7 +2117,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract): """ return mpz_cmp_si(self.value, 0) != 0 - cpdef bint is_unit(self): + cpdef bint is_unit(self) noexcept: """ Return ``True`` iff this element is a unit. @@ -2175,7 +2175,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract): # immutable return self - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ EXAMPLES:: @@ -2190,7 +2190,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract): mpz_sub(x.value, x.value, self._modulus.sageInteger.value) return x - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ EXAMPLES:: @@ -2205,7 +2205,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract): mpz_add(x.value, x.value, self._modulus.sageInteger.value) return x - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ EXAMPLES:: @@ -2221,7 +2221,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract): mpz_sub(x.value, self._modulus.sageInteger.value, self.value) return x - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ EXAMPLES:: @@ -2235,7 +2235,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract): mpz_fdiv_r(x.value, x.value, self._modulus.sageInteger.value) return x - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ EXAMPLES:: @@ -2419,7 +2419,7 @@ cdef class IntegerMod_int(IntegerMod_abstract): True """ - cdef IntegerMod_int _new_c(self, int_fast32_t value): + cdef IntegerMod_int _new_c(self, int_fast32_t value) noexcept: if self._modulus.table is not None: return self._modulus.table[value] cdef IntegerMod_int x = IntegerMod_int.__new__(IntegerMod_int) @@ -2428,18 +2428,18 @@ cdef class IntegerMod_int(IntegerMod_abstract): x.ivalue = value return x - cdef void set_from_mpz(self, mpz_t value): + cdef void set_from_mpz(self, mpz_t value) noexcept: self.ivalue = mpz_fdiv_ui(value, self._modulus.int32) - cdef void set_from_long(self, long value): + cdef void set_from_long(self, long value) noexcept: self.ivalue = value % self._modulus.int32 if self.ivalue < 0: self.ivalue += self._modulus.int32 - cdef void set_from_ulong_fast(self, unsigned long value): + cdef void set_from_ulong_fast(self, unsigned long value) noexcept: self.ivalue = value - cdef void set_from_int(IntegerMod_int self, int_fast32_t ivalue): + cdef void set_from_int(IntegerMod_int self, int_fast32_t ivalue) noexcept: if ivalue < 0: self.ivalue = self._modulus.int32 + (ivalue % self._modulus.int32) elif ivalue >= self._modulus.int32: @@ -2447,10 +2447,10 @@ cdef class IntegerMod_int(IntegerMod_abstract): else: self.ivalue = ivalue - cdef int_fast32_t get_int_value(IntegerMod_int self): + cdef int_fast32_t get_int_value(IntegerMod_int self) noexcept: return self.ivalue - cpdef _richcmp_(self, right, int op): + cpdef _richcmp_(self, right, int op) noexcept: """ EXAMPLES:: @@ -2472,7 +2472,7 @@ cdef class IntegerMod_int(IntegerMod_abstract): else: return rich_to_bool(op, 1) - cpdef bint is_one(IntegerMod_int self): + cpdef bint is_one(IntegerMod_int self) noexcept: """ Returns ``True`` if this is `1`, otherwise ``False``. @@ -2504,7 +2504,7 @@ cdef class IntegerMod_int(IntegerMod_abstract): """ return self.ivalue != 0 - cpdef bint is_unit(IntegerMod_int self): + cpdef bint is_unit(IntegerMod_int self) noexcept: """ Return ``True`` iff this element is a unit @@ -2574,7 +2574,7 @@ cdef class IntegerMod_int(IntegerMod_abstract): # immutable return self - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ EXAMPLES:: @@ -2588,7 +2588,7 @@ cdef class IntegerMod_int(IntegerMod_abstract): x = x - self._modulus.int32 return self._new_c(x) - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ EXAMPLES:: @@ -2602,7 +2602,7 @@ cdef class IntegerMod_int(IntegerMod_abstract): x = x + self._modulus.int32 return self._new_c(x) - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ EXAMPLES:: @@ -2615,7 +2615,7 @@ cdef class IntegerMod_int(IntegerMod_abstract): return self return self._new_c(self._modulus.int32 - self.ivalue) - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ EXAMPLES:: @@ -2625,7 +2625,7 @@ cdef class IntegerMod_int(IntegerMod_abstract): """ return self._new_c((self.ivalue * (right).ivalue) % self._modulus.int32) - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ EXAMPLES:: @@ -2698,7 +2698,7 @@ cdef class IntegerMod_int(IntegerMod_abstract): """ return self.shift(-int(k)) - cdef shift(IntegerMod_int self, int k): + cdef shift(IntegerMod_int self, int k) noexcept: """ Performs a bit-shift specified by ``k`` on ``self``. @@ -3089,7 +3089,7 @@ cdef class IntegerMod_int(IntegerMod_abstract): ### End of class -cdef int_fast32_t gcd_int(int_fast32_t a, int_fast32_t b): +cdef int_fast32_t gcd_int(int_fast32_t a, int_fast32_t b) noexcept: """ Returns the gcd of a and b @@ -3145,7 +3145,7 @@ cdef int_fast32_t mod_inverse_int(int_fast32_t x, int_fast32_t n) except 0: raise ZeroDivisionError(f"inverse of Mod({x}, {n}) does not exist") -cdef int_fast32_t mod_pow_int(int_fast32_t base, int_fast32_t exp, int_fast32_t n): +cdef int_fast32_t mod_pow_int(int_fast32_t base, int_fast32_t exp, int_fast32_t n) noexcept: """ Returns base^exp mod n @@ -3251,7 +3251,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract): - Robert Bradshaw (2006-09-14) """ - cdef IntegerMod_int64 _new_c(self, int_fast64_t value): + cdef IntegerMod_int64 _new_c(self, int_fast64_t value) noexcept: cdef IntegerMod_int64 x x = IntegerMod_int64.__new__(IntegerMod_int64) x._modulus = self._modulus @@ -3259,18 +3259,18 @@ cdef class IntegerMod_int64(IntegerMod_abstract): x.ivalue = value return x - cdef void set_from_mpz(self, mpz_t value): + cdef void set_from_mpz(self, mpz_t value) noexcept: self.ivalue = mpz_fdiv_ui(value, self._modulus.int64) - cdef void set_from_long(self, long value): + cdef void set_from_long(self, long value) noexcept: self.ivalue = value % self._modulus.int64 if self.ivalue < 0: self.ivalue += self._modulus.int64 - cdef void set_from_ulong_fast(self, unsigned long value): + cdef void set_from_ulong_fast(self, unsigned long value) noexcept: self.ivalue = value - cdef void set_from_int(IntegerMod_int64 self, int_fast64_t ivalue): + cdef void set_from_int(IntegerMod_int64 self, int_fast64_t ivalue) noexcept: if ivalue < 0: self.ivalue = self._modulus.int64 + (ivalue % self._modulus.int64) # Is ivalue % self._modulus.int64 actually negative? elif ivalue >= self._modulus.int64: @@ -3278,10 +3278,10 @@ cdef class IntegerMod_int64(IntegerMod_abstract): else: self.ivalue = ivalue - cdef int_fast64_t get_int_value(IntegerMod_int64 self): + cdef int_fast64_t get_int_value(IntegerMod_int64 self) noexcept: return self.ivalue - cpdef _richcmp_(self, right, int op): + cpdef _richcmp_(self, right, int op) noexcept: """ EXAMPLES:: @@ -3303,7 +3303,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract): else: return rich_to_bool(op, 1) - cpdef bint is_one(IntegerMod_int64 self): + cpdef bint is_one(IntegerMod_int64 self) noexcept: """ Returns ``True`` if this is `1`, otherwise ``False``. @@ -3331,7 +3331,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract): """ return self.ivalue != 0 - cpdef bint is_unit(IntegerMod_int64 self): + cpdef bint is_unit(IntegerMod_int64 self) noexcept: """ Return ``True`` iff this element is a unit. @@ -3410,7 +3410,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract): # immutable return self - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ EXAMPLES:: @@ -3424,7 +3424,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract): x = x - self._modulus.int64 return self._new_c(x) - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ EXAMPLES:: @@ -3438,7 +3438,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract): x = x + self._modulus.int64 return self._new_c(x) - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ EXAMPLES:: @@ -3451,7 +3451,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract): return self return self._new_c(self._modulus.int64 - self.ivalue) - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ EXAMPLES:: @@ -3462,7 +3462,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract): return self._new_c((self.ivalue * (right).ivalue) % self._modulus.int64) - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ EXAMPLES:: @@ -3518,7 +3518,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract): """ return self.shift(-int(k)) - cdef shift(IntegerMod_int64 self, int k): + cdef shift(IntegerMod_int64 self, int k) noexcept: """ Performs a bit-shift specified by ``k`` on ``self``. @@ -3765,7 +3765,7 @@ cdef int mpz_pow_helper(mpz_t res, mpz_t base, object exp, mpz_t modulus) except if not mpz_invert(res, res, modulus): raise ZeroDivisionError("Inverse does not exist.") -cdef int_fast64_t gcd_int64(int_fast64_t a, int_fast64_t b): +cdef int_fast64_t gcd_int64(int_fast64_t a, int_fast64_t b) noexcept: """ Returns the gcd of a and b @@ -3819,7 +3819,7 @@ cdef int_fast64_t mod_inverse_int64(int_fast64_t x, int_fast64_t n) except 0: raise ZeroDivisionError(f"inverse of Mod({x}, {n}) does not exist") -cdef int_fast64_t mod_pow_int64(int_fast64_t base, int_fast64_t exp, int_fast64_t n): +cdef int_fast64_t mod_pow_int64(int_fast64_t base, int_fast64_t exp, int_fast64_t n) noexcept: """ Returns base^exp mod n @@ -3994,7 +3994,7 @@ def square_root_mod_prime_power(IntegerMod_abstract a, p, e): x *= p**(val//2) return x -cpdef square_root_mod_prime(IntegerMod_abstract a, p=None): +cpdef square_root_mod_prime(IntegerMod_abstract a, p=None) noexcept: r""" Calculates the square root of `a`, where `a` is an integer mod `p`; if `a` is not a perfect square, @@ -4269,7 +4269,7 @@ cdef class IntegerMod_hom(Morphism): self.zero = C._element_constructor_(0) self.modulus = C._pyx_order - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for pickling and copying. @@ -4296,7 +4296,7 @@ cdef class IntegerMod_hom(Morphism): slots['modulus'] = self.modulus return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for pickling and copying. @@ -4324,7 +4324,7 @@ cdef class IntegerMod_hom(Morphism): self.zero = _slots['zero'] self.modulus = _slots['modulus'] - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: return IntegerMod(self._codomain, x) cdef class IntegerMod_to_IntegerMod(IntegerMod_hom): @@ -4355,7 +4355,7 @@ cdef class IntegerMod_to_IntegerMod(IntegerMod_hom): import sage.categories.homset IntegerMod_hom.__init__(self, sage.categories.homset.Hom(R, S)) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: cdef IntegerMod_abstract a zero = self.zero cdef unsigned long value @@ -4423,7 +4423,7 @@ cdef class Integer_to_IntegerMod(IntegerMod_hom): import sage.categories.homset IntegerMod_hom.__init__(self, sage.categories.homset.Hom(integer_ring.ZZ, R)) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: cdef IntegerMod_abstract a cdef Py_ssize_t res if self.modulus.table is not None: @@ -4495,7 +4495,7 @@ cdef class IntegerMod_to_Integer(Map): from sage.categories.sets_cat import Sets Morphism.__init__(self, sage.categories.homset.Hom(R, integer_ring.ZZ, Sets())) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: cdef Integer ans = Integer.__new__(Integer) if isinstance(x, IntegerMod_gmp): mpz_set(ans.value, (x).value) @@ -4534,7 +4534,7 @@ cdef class Int_to_IntegerMod(IntegerMod_hom): from sage.sets.pythonclass import Set_PythonType IntegerMod_hom.__init__(self, sage.categories.homset.Hom(Set_PythonType(int), R)) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: cdef IntegerMod_abstract a zero = self.zero diff --git a/src/sage/rings/finite_rings/residue_field.pyx b/src/sage/rings/finite_rings/residue_field.pyx index b466ee5e2c1..17a431f3496 100644 --- a/src/sage/rings/finite_rings/residue_field.pyx +++ b/src/sage/rings/finite_rings/residue_field.pyx @@ -995,7 +995,7 @@ cdef class ReductionMap(Map): self._repr_type_str = "Partially defined reduction" Map.__init__(self, Hom(K, F, SetsWithPartialMaps())) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1026,7 +1026,7 @@ cdef class ReductionMap(Map): slots['_section'] = self._section return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1056,7 +1056,7 @@ cdef class ReductionMap(Map): self._PB = _slots['_PB'] self._section = _slots['_section'] - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Apply this reduction map to an element that coerces into the global field. @@ -1305,7 +1305,7 @@ cdef class ResidueFieldHomomorphism_global(RingHomomorphism): self._repr_type_str = "Reduction" RingHomomorphism.__init__(self, Hom(K,F)) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1337,7 +1337,7 @@ cdef class ResidueFieldHomomorphism_global(RingHomomorphism): slots['_section'] = self._section return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1368,7 +1368,7 @@ cdef class ResidueFieldHomomorphism_global(RingHomomorphism): self._PB = _slots['_PB'] self._section = _slots['_section'] - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Applies this morphism to an element. @@ -1572,7 +1572,7 @@ cdef class LiftingMap(Section): self._PB = PB Section.__init__(self, reduction) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1598,7 +1598,7 @@ cdef class LiftingMap(Section): slots['_PB'] = self._PB return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1623,7 +1623,7 @@ cdef class LiftingMap(Section): self._to_order = _slots['_to_order'] self._PB = _slots['_PB'] - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Lift from this residue class field to the number field. diff --git a/src/sage/rings/fraction_field_FpT.pxd b/src/sage/rings/fraction_field_FpT.pxd index 5029a49727c..a385a3d7742 100644 --- a/src/sage/rings/fraction_field_FpT.pxd +++ b/src/sage/rings/fraction_field_FpT.pxd @@ -10,15 +10,15 @@ cdef class FpTElement(FieldElement): cdef bint initialized cdef long p - cdef FpTElement _new_c(self) - cpdef _add_(self, other) - cpdef _mul_(self, other) - cdef FpTElement _copy_c(self) - cpdef numerator(self) - cpdef denominator(self) - cpdef FpTElement next(self) - cpdef _sqrt_or_None(self) - cpdef bint is_square(self) + cdef FpTElement _new_c(self) noexcept + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept + cdef FpTElement _copy_c(self) noexcept + cpdef numerator(self) noexcept + cpdef denominator(self) noexcept + cpdef FpTElement next(self) noexcept + cpdef _sqrt_or_None(self) noexcept + cpdef bint is_square(self) noexcept cdef class FpT_iter: cdef parent diff --git a/src/sage/rings/fraction_field_FpT.pyx b/src/sage/rings/fraction_field_FpT.pyx index c9bb5d5a384..4c99862ca24 100644 --- a/src/sage/rings/fraction_field_FpT.pyx +++ b/src/sage/rings/fraction_field_FpT.pyx @@ -160,7 +160,7 @@ cdef class FpTElement(FieldElement): return (unpickle_FpT_element, (self._parent, self.numer(), self.denom())) - cdef FpTElement _new_c(self): + cdef FpTElement _new_c(self) noexcept: """ Creates a new FpTElement in the same field, leaving the value to be initialized. """ @@ -172,7 +172,7 @@ cdef class FpTElement(FieldElement): x.initialized = True return x - cdef FpTElement _copy_c(self): + cdef FpTElement _copy_c(self) noexcept: """ Creates a new FpTElement in the same field, with the same value as self. """ @@ -199,7 +199,7 @@ cdef class FpTElement(FieldElement): """ return self.numerator() - cpdef numerator(self): + cpdef numerator(self) noexcept: """ Return the numerator of this element, as an element of the polynomial ring. @@ -230,7 +230,7 @@ cdef class FpTElement(FieldElement): """ return self.denominator() - cpdef denominator(self): + cpdef denominator(self) noexcept: """ Return the denominator of this element, as an element of the polynomial ring. @@ -358,7 +358,7 @@ cdef class FpTElement(FieldElement): else: return "\\frac{%s}{%s}" % (self.numer()._latex_(), self.denom()._latex_()) - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ Compare this with another element. @@ -463,7 +463,7 @@ cdef class FpTElement(FieldElement): nmod_poly_swap(x._numer, x._denom) return x - cpdef _add_(self, _other): + cpdef _add_(self, _other) noexcept: """ Return the sum of this fraction field element and another. @@ -491,7 +491,7 @@ cdef class FpTElement(FieldElement): normalize(x._numer, x._denom, self.p) return x - cpdef _sub_(self, _other): + cpdef _sub_(self, _other) noexcept: """ Return the difference of this fraction field element and another. @@ -513,7 +513,7 @@ cdef class FpTElement(FieldElement): normalize(x._numer, x._denom, self.p) return x - cpdef _mul_(self, _other): + cpdef _mul_(self, _other) noexcept: """ Return the product of this fraction field element and another. @@ -533,7 +533,7 @@ cdef class FpTElement(FieldElement): normalize(x._numer, x._denom, self.p) return x - cpdef _div_(self, _other): + cpdef _div_(self, _other) noexcept: """ Return the quotient of this fraction field element and another. @@ -557,7 +557,7 @@ cdef class FpTElement(FieldElement): normalize(x._numer, x._denom, self.p) return x - cpdef FpTElement next(self): + cpdef FpTElement next(self) noexcept: """ Iterate through all polynomials, returning the "next" polynomial after this one. @@ -663,7 +663,7 @@ cdef class FpTElement(FieldElement): nmod_poly_clear(g) return next - cpdef _sqrt_or_None(self): + cpdef _sqrt_or_None(self) noexcept: """ Return the square root of ``self``, or ``None``. @@ -735,7 +735,7 @@ cdef class FpTElement(FieldElement): nmod_poly_clear(denom) return None - cpdef bint is_square(self): + cpdef bint is_square(self) noexcept: """ Return ``True`` if this element is the square of another element of the fraction field. @@ -1052,7 +1052,7 @@ cdef class Polyring_FpT_coerce(RingHomomorphism): RingHomomorphism.__init__(self, R.ring_of_integers().Hom(R)) self.p = R.base_ring().characteristic() - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1068,7 +1068,7 @@ cdef class Polyring_FpT_coerce(RingHomomorphism): slots['p'] = self.p return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1083,7 +1083,7 @@ cdef class Polyring_FpT_coerce(RingHomomorphism): self.p = _slots['p'] RingHomomorphism._update_slots(self, _slots) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: """ Applies the coercion. @@ -1106,7 +1106,7 @@ cdef class Polyring_FpT_coerce(RingHomomorphism): ans.initialized = True return ans - cpdef Element _call_with_args(self, _x, args=(), kwds={}): + cpdef Element _call_with_args(self, _x, args=(), kwds={}) noexcept: """ This function allows the map to take multiple arguments, usually used to specify both numerator and denominator. @@ -1255,7 +1255,7 @@ cdef class FpT_Polyring_section(Section): self.p = f.p Section.__init__(self, f) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1277,7 +1277,7 @@ cdef class FpT_Polyring_section(Section): slots['p'] = self.p return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1298,7 +1298,7 @@ cdef class FpT_Polyring_section(Section): self.p = _slots['p'] Section._update_slots(self, _slots) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: """ Applies the section. @@ -1370,7 +1370,7 @@ cdef class Fp_FpT_coerce(RingHomomorphism): RingHomomorphism.__init__(self, R.base_ring().Hom(R)) self.p = R.base_ring().characteristic() - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1389,7 +1389,7 @@ cdef class Fp_FpT_coerce(RingHomomorphism): slots['p'] = self.p return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1407,7 +1407,7 @@ cdef class Fp_FpT_coerce(RingHomomorphism): self.p = _slots['p'] RingHomomorphism._update_slots(self, _slots) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: """ Applies the coercion. @@ -1430,7 +1430,7 @@ cdef class Fp_FpT_coerce(RingHomomorphism): ans.initialized = True return ans - cpdef Element _call_with_args(self, _x, args=(), kwds={}): + cpdef Element _call_with_args(self, _x, args=(), kwds={}) noexcept: """ This function allows the map to take multiple arguments, usually used to specify both numerator and denominator. @@ -1558,7 +1558,7 @@ cdef class FpT_Fp_section(Section): self.p = f.p Section.__init__(self, f) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1586,7 +1586,7 @@ cdef class FpT_Fp_section(Section): slots['p'] = self.p return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1613,7 +1613,7 @@ cdef class FpT_Fp_section(Section): self.p = _slots['p'] Section._update_slots(self, _slots) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: """ Applies the section. @@ -1692,7 +1692,7 @@ cdef class ZZ_FpT_coerce(RingHomomorphism): RingHomomorphism.__init__(self, ZZ.Hom(R)) self.p = R.base_ring().characteristic() - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1713,7 +1713,7 @@ cdef class ZZ_FpT_coerce(RingHomomorphism): slots['p'] = self.p return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1733,7 +1733,7 @@ cdef class ZZ_FpT_coerce(RingHomomorphism): self.p = _slots['p'] RingHomomorphism._update_slots(self, _slots) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: """ Applies the coercion. @@ -1756,7 +1756,7 @@ cdef class ZZ_FpT_coerce(RingHomomorphism): ans.initialized = True return ans - cpdef Element _call_with_args(self, _x, args=(), kwds={}): + cpdef Element _call_with_args(self, _x, args=(), kwds={}) noexcept: """ This function allows the map to take multiple arguments, usually used to specify both numerator and denominator. @@ -1842,7 +1842,7 @@ cdef class ZZ_FpT_coerce(RingHomomorphism): """ return ZZ.convert_map_from(self.codomain().base_ring()) * Fp_FpT_coerce(self.codomain()).section() -cdef inline bint normalize(nmod_poly_t numer, nmod_poly_t denom, long p): +cdef inline bint normalize(nmod_poly_t numer, nmod_poly_t denom, long p) noexcept: """ Put ``numer`` / ``denom`` into a normal form: denominator monic and sharing no common factor with the numerator. @@ -1887,14 +1887,14 @@ cdef inline bint normalize(nmod_poly_t numer, nmod_poly_t denom, long p): nmod_poly_clear(g) -cdef inline unsigned long nmod_poly_leading(nmod_poly_t poly): +cdef inline unsigned long nmod_poly_leading(nmod_poly_t poly) noexcept: """ Return the leading coefficient of ``poly``. """ return nmod_poly_get_coeff_ui(poly, nmod_poly_degree(poly)) -cdef inline void nmod_poly_inc(nmod_poly_t poly, bint monic): +cdef inline void nmod_poly_inc(nmod_poly_t poly, bint monic) noexcept: """ Set poly to the "next" polynomial: this is just counting in base p. @@ -1915,7 +1915,7 @@ cdef inline void nmod_poly_inc(nmod_poly_t poly, bint monic): nmod_poly_set_coeff_ui(poly, n + 1, 1) -cdef inline long nmod_poly_cmp(nmod_poly_t a, nmod_poly_t b): +cdef inline long nmod_poly_cmp(nmod_poly_t a, nmod_poly_t b) noexcept: """ Compare `a` and `b`, returning 0 if they are equal. @@ -1943,7 +1943,7 @@ cdef inline long nmod_poly_cmp(nmod_poly_t a, nmod_poly_t b): return 0 -cdef bint nmod_poly_sqrt_check(nmod_poly_t poly): +cdef bint nmod_poly_sqrt_check(nmod_poly_t poly) noexcept: """ Quick check to see if ``poly`` could possibly be a square. """ @@ -1971,7 +1971,7 @@ def unpickle_FpT_element(K, numer, denom): # Somehow this isn't in FLINT, evidently. It could be moved # elsewhere at some point. -cdef int sage_cmp_nmod_poly_t(nmod_poly_t L, nmod_poly_t R): +cdef int sage_cmp_nmod_poly_t(nmod_poly_t L, nmod_poly_t R) noexcept: """ Compare two ``nmod_poly_t`` in a Pythonic way, so this returns `-1`, `0`, or `1`, and is consistent. diff --git a/src/sage/rings/fraction_field_element.pyx b/src/sage/rings/fraction_field_element.pyx index 2134c2fa07b..cb0bbce912f 100644 --- a/src/sage/rings/fraction_field_element.pyx +++ b/src/sage/rings/fraction_field_element.pyx @@ -159,7 +159,7 @@ cdef class FractionFieldElement(FieldElement): nden = codomain.coerce(self._denominator._im_gens_(codomain, im_gens, base_map=base_map)) return codomain.coerce(nnum/nden) - cpdef reduce(self): + cpdef reduce(self) noexcept: """ Reduce this fraction. @@ -548,7 +548,7 @@ cdef class FractionFieldElement(FieldElement): return s - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Compute the sum of ``self`` and ``right``. @@ -633,7 +633,7 @@ cdef class FractionFieldElement(FieldElement): return self.__class__(self._parent, rnum*sden + rden*snum, rden*sden, coerce=False, reduce=False) - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Computes the product of ``self`` and ``right``. @@ -699,7 +699,7 @@ cdef class FractionFieldElement(FieldElement): return self.__class__(self._parent, rnum * snum, rden * sden, coerce=False, reduce=False) - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Computes the quotient of ``self`` and ``right``. @@ -934,7 +934,7 @@ cdef class FractionFieldElement(FieldElement): return self.__class__(self._parent, self._denominator, self._numerator, coerce=False, reduce=False) - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ EXAMPLES:: @@ -1171,7 +1171,7 @@ cdef class FractionFieldElement_1poly_field(FractionFieldElement): if not reduce: self.normalize_leading_coefficients() - cdef normalize_leading_coefficients(self): + cdef normalize_leading_coefficients(self) noexcept: """ See :meth:`reduce`. """ @@ -1216,7 +1216,7 @@ cdef class FractionFieldElement_1poly_field(FractionFieldElement): L.sort() return L - cpdef reduce(self): + cpdef reduce(self) noexcept: """ Pick a normalized representation of self. diff --git a/src/sage/rings/function_field/element.pxd b/src/sage/rings/function_field/element.pxd index f0418634f82..9ffdbd48383 100644 --- a/src/sage/rings/function_field/element.pxd +++ b/src/sage/rings/function_field/element.pxd @@ -5,6 +5,6 @@ cdef class FunctionFieldElement(FieldElement): cdef readonly object _x cdef readonly object _matrix - cdef FunctionFieldElement _new_c(self) - cpdef bint is_nth_power(self, n) - cpdef FunctionFieldElement nth_root(self, n) + cdef FunctionFieldElement _new_c(self) noexcept + cpdef bint is_nth_power(self, n) noexcept + cpdef FunctionFieldElement nth_root(self, n) noexcept diff --git a/src/sage/rings/function_field/element.pyx b/src/sage/rings/function_field/element.pyx index 9a82b611d18..dceaa85fd2e 100644 --- a/src/sage/rings/function_field/element.pyx +++ b/src/sage/rings/function_field/element.pyx @@ -122,7 +122,7 @@ cdef class FunctionFieldElement(FieldElement): return (make_FunctionFieldElement, (self._parent, type(self), self._x)) - cdef FunctionFieldElement _new_c(self): + cdef FunctionFieldElement _new_c(self) noexcept: cdef type t = type(self) cdef FunctionFieldElement x = t.__new__(t) x._parent = self._parent @@ -671,7 +671,7 @@ cdef class FunctionFieldElement(FieldElement): # v < 0 raise ValueError('has a pole at the place') - cpdef bint is_nth_power(self, n): + cpdef bint is_nth_power(self, n) noexcept: r""" Return whether this element is an ``n``-th power in the rational function field. @@ -698,7 +698,7 @@ cdef class FunctionFieldElement(FieldElement): """ raise NotImplementedError("is_nth_power() not implemented for generic elements") - cpdef FunctionFieldElement nth_root(self, n): + cpdef FunctionFieldElement nth_root(self, n) noexcept: """ Return an ``n``-th root of this element in the function field. diff --git a/src/sage/rings/function_field/element_polymod.pyx b/src/sage/rings/function_field/element_polymod.pyx index 9e198d0b042..5e748b22a6f 100644 --- a/src/sage/rings/function_field/element_polymod.pyx +++ b/src/sage/rings/function_field/element_polymod.pyx @@ -112,7 +112,7 @@ cdef class FunctionFieldElement_polymod(FunctionFieldElement): """ return hash(self._x) - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ Do rich comparison with the other element with respect to ``op`` @@ -129,7 +129,7 @@ cdef class FunctionFieldElement_polymod(FunctionFieldElement): cdef FunctionFieldElement right = other return richcmp(left._x, right._x, op) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Add the element with the other element. @@ -152,7 +152,7 @@ cdef class FunctionFieldElement_polymod(FunctionFieldElement): res._x = self._x + (right)._x return res - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Subtract the other element from the element. @@ -173,7 +173,7 @@ cdef class FunctionFieldElement_polymod(FunctionFieldElement): res._x = self._x - (right)._x return res - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Multiply the element with the other element. @@ -192,7 +192,7 @@ cdef class FunctionFieldElement_polymod(FunctionFieldElement): res._x = (self._x * (right)._x) % self._parent.polynomial() return res - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Divide the element with the other element. @@ -231,7 +231,7 @@ cdef class FunctionFieldElement_polymod(FunctionFieldElement): P = self._parent return P(self._x.xgcd(P._polynomial)[1]) - cpdef list list(self): + cpdef list list(self) noexcept: """ Return the list of the coefficients representing the element. @@ -251,7 +251,7 @@ cdef class FunctionFieldElement_polymod(FunctionFieldElement): """ return self._x.padded_list(self._parent.degree()) - cpdef FunctionFieldElement nth_root(self, n): + cpdef FunctionFieldElement nth_root(self, n) noexcept: r""" Return an ``n``-th root of this element in the function field. @@ -317,7 +317,7 @@ cdef class FunctionFieldElement_polymod(FunctionFieldElement): raise NotImplementedError("nth_root() not implemented for this n") - cpdef bint is_nth_power(self, n): + cpdef bint is_nth_power(self, n) noexcept: r""" Return whether this element is an ``n``-th power in the function field. @@ -367,7 +367,7 @@ cdef class FunctionFieldElement_polymod(FunctionFieldElement): raise NotImplementedError("is_nth_power() not implemented for this n") - cdef FunctionFieldElement _pth_root(self): + cdef FunctionFieldElement _pth_root(self) noexcept: r""" Helper method for :meth:`nth_root` and :meth:`is_nth_power` which computes a `p`-th root if the characteristic is `p` and the constant diff --git a/src/sage/rings/function_field/element_rational.pyx b/src/sage/rings/function_field/element_rational.pyx index 0d306d6826e..faa70ee7aee 100644 --- a/src/sage/rings/function_field/element_rational.pyx +++ b/src/sage/rings/function_field/element_rational.pyx @@ -85,7 +85,7 @@ cdef class FunctionFieldElement_rational(FunctionFieldElement): """ return self._x - cpdef list list(self): + cpdef list list(self) noexcept: """ Return a list with just the element. @@ -143,7 +143,7 @@ cdef class FunctionFieldElement_rational(FunctionFieldElement): """ return hash(self._x) - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ Compare the element with the other element with respect to ``op`` @@ -174,7 +174,7 @@ cdef class FunctionFieldElement_rational(FunctionFieldElement): except TypeError: return NotImplemented - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Add the element with the other element. @@ -192,7 +192,7 @@ cdef class FunctionFieldElement_rational(FunctionFieldElement): res._x = self._x + (right)._x return res - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Subtract the other element from the element. @@ -210,7 +210,7 @@ cdef class FunctionFieldElement_rational(FunctionFieldElement): res._x = self._x - (right)._x return res - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Multiply the element with the other element @@ -228,7 +228,7 @@ cdef class FunctionFieldElement_rational(FunctionFieldElement): res._x = self._x * (right)._x return res - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Divide the element with the other element @@ -359,7 +359,7 @@ cdef class FunctionFieldElement_rational(FunctionFieldElement): else: return self._parent(self._x.sqrt()) - cpdef bint is_nth_power(self, n): + cpdef bint is_nth_power(self, n) noexcept: r""" Return whether this element is an ``n``-th power in the rational function field. @@ -412,7 +412,7 @@ cdef class FunctionFieldElement_rational(FunctionFieldElement): raise NotImplementedError("is_nth_power() not implemented for the given n") - cpdef FunctionFieldElement nth_root(self, n): + cpdef FunctionFieldElement nth_root(self, n) noexcept: r""" Return an ``n``-th root of this element in the function field. diff --git a/src/sage/rings/integer.pxd b/src/sage/rings/integer.pxd index fff6b56a5fc..2f81c164943 100644 --- a/src/sage/rings/integer.pxd +++ b/src/sage/rings/integer.pxd @@ -10,35 +10,35 @@ cdef class Integer(EuclideanDomainElement): # https://github.com/cython/cython/issues/1984 cdef __mpz_struct value[1] - cdef void set_from_mpz(self, mpz_t value) - cdef hash_c(self) - - cpdef __pari__(self) - - cpdef _shift_helper(Integer self, y, int sign) - cpdef _add_(self, other) - cpdef _mul_(self, other) - cpdef _pow_(self, other) - cdef _and(Integer self, Integer other) - cdef _or(Integer self, Integer other) - cdef _xor(Integer self, Integer other) - - cpdef size_t _exact_log_log2_iter(self,Integer m) - cpdef size_t _exact_log_mpfi_log(self,m) - cpdef RingElement _valuation(Integer self, Integer p) - cdef object _val_unit(Integer self, Integer p) - cdef Integer _divide_knowing_divisible_by(Integer self, Integer right) - cdef bint _is_power_of(Integer self, Integer n) + cdef void set_from_mpz(self, mpz_t value) noexcept + cdef hash_c(self) noexcept + + cpdef __pari__(self) noexcept + + cpdef _shift_helper(Integer self, y, int sign) noexcept + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept + cpdef _pow_(self, other) noexcept + cdef _and(Integer self, Integer other) noexcept + cdef _or(Integer self, Integer other) noexcept + cdef _xor(Integer self, Integer other) noexcept + + cpdef size_t _exact_log_log2_iter(self,Integer m) noexcept + cpdef size_t _exact_log_mpfi_log(self,m) noexcept + cpdef RingElement _valuation(Integer self, Integer p) noexcept + cdef object _val_unit(Integer self, Integer p) noexcept + cdef Integer _divide_knowing_divisible_by(Integer self, Integer right) noexcept + cdef bint _is_power_of(Integer self, Integer n) noexcept cdef bint _pseudoprime_is_prime(self, proof) except -1 cdef int mpz_set_str_python(mpz_ptr z, char* s, int base) except -1 -cdef Integer smallInteger(long value) +cdef Integer smallInteger(long value) noexcept cdef bint _small_primes_table[500] -cdef inline Integer _Integer_from_mpz(mpz_t e): +cdef inline Integer _Integer_from_mpz(mpz_t e) noexcept: cdef Integer z = Integer.__new__(Integer) mpz_set(z.value, e) return z diff --git a/src/sage/rings/integer.pyx b/src/sage/rings/integer.pyx index 4202bcc9a10..5ce9df2fc3c 100644 --- a/src/sage/rings/integer.pyx +++ b/src/sage/rings/integer.pyx @@ -210,11 +210,11 @@ cdef object numpy_long_interface = {'typestr': '=i4' if sizeof(long) == 4 else ' cdef object numpy_int64_interface = {'typestr': '=i8'} cdef object numpy_object_interface = {'typestr': '|O'} -cdef set_from_Integer(Integer self, Integer other): +cdef set_from_Integer(Integer self, Integer other) noexcept: mpz_set(self.value, other.value) -cdef _digits_naive(mpz_t v,l,int offset,Integer base,digits): +cdef _digits_naive(mpz_t v,l,int offset,Integer base,digits) noexcept: """ This method fills in digit entries in the list, l, using the most basic digit algorithm -- repeat division by base. @@ -261,7 +261,7 @@ cdef _digits_naive(mpz_t v,l,int offset,Integer base,digits): mpz_clear(mpz_value) -cdef _digits_internal(mpz_t v,l,int offset,int power_index,power_list,digits): +cdef _digits_internal(mpz_t v,l,int offset,int power_index,power_list,digits) noexcept: """ INPUT: @@ -335,7 +335,7 @@ def is_Integer(x): """ return isinstance(x, Integer) -cdef inline Integer as_Integer(x): +cdef inline Integer as_Integer(x) noexcept: if isinstance(x, Integer): return x else: @@ -772,7 +772,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): """ return codomain.coerce(self) - cdef _xor(Integer self, Integer other): + cdef _xor(Integer self, Integer other) noexcept: cdef Integer x x = PY_NEW(Integer) mpz_xor(x.value, self.value, other.value) @@ -914,7 +914,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): return rich_to_bool_sgn(op, c) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: r""" EXAMPLES:: @@ -1733,7 +1733,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): else: return self.abs().exact_log(base) + 1 - cdef void set_from_mpz(Integer self, mpz_t value): + cdef void set_from_mpz(Integer self, mpz_t value) noexcept: mpz_set(self.value, value) def __add__(left, right): @@ -1762,7 +1762,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): return coercion_model.bin_op(left, right, operator.add) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Integer addition. @@ -1780,7 +1780,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): mpz_add(x.value, self.value, (right).value) return x - cdef _add_long(self, long n): + cdef _add_long(self, long n) noexcept: """ Fast path for adding a C long. @@ -1849,7 +1849,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): return coercion_model.bin_op(left, right, operator.sub) - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Integer subtraction. @@ -1887,12 +1887,12 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): mpz_neg(x.value, self.value) return x - cpdef _neg_(self): + cpdef _neg_(self) noexcept: cdef Integer x = PY_NEW(Integer) mpz_neg(x.value, self.value) return x - cpdef _act_on_(self, s, bint self_on_left): + cpdef _act_on_(self, s, bint self_on_left) noexcept: """ EXAMPLES:: @@ -1909,7 +1909,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): else: return s * int(self) # will raise the appropriate exception - cdef _mul_long(self, long n): + cdef _mul_long(self, long n) noexcept: """ Fast path for multiplying a C long. @@ -1957,7 +1957,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): return coercion_model.bin_op(left, right, operator.mul) - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Integer multiplication. @@ -2030,7 +2030,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): return coercion_model.bin_op(left, right, operator.truediv) - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: r""" Computes `\frac{a}{b}` @@ -2047,7 +2047,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): mpq_div_zz(x.value, self.value, (right).value) return x - cpdef _floordiv_(self, right): + cpdef _floordiv_(self, right) noexcept: r""" Computes the whole part of `\frac{x}{y}`. @@ -2189,7 +2189,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): # left is a non-Element: do the powering with a Python int return left ** int(right) - cpdef _pow_(self, other): + cpdef _pow_(self, other) noexcept: """ Integer powering. @@ -2269,7 +2269,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): else: return ~r - cdef _pow_long(self, long n): + cdef _pow_long(self, long n) noexcept: if n == 0: return smallInteger(1) elif n == 1: @@ -2299,7 +2299,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): sig_off() return q - cpdef _pow_int(self, n): + cpdef _pow_int(self, n) noexcept: """ Integer powering to an integer exponent. @@ -2429,7 +2429,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): raise ValueError("%s is not a %s power" % (self, integer_ring.ZZ(n).ordinal_str())) - cpdef size_t _exact_log_log2_iter(self,Integer m): + cpdef size_t _exact_log_log2_iter(self,Integer m) noexcept: r""" This is only for internal use only. You should expect it to crash and burn for negative or other malformed input. In particular, if @@ -2508,7 +2508,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): sig_off() return l_min - cpdef size_t _exact_log_mpfi_log(self,m): + cpdef size_t _exact_log_mpfi_log(self,m) noexcept: """ This is only for internal use only. You should expect it to crash and burn for negative or other malformed input. @@ -3683,7 +3683,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): """ return mpz_pythonhash(self.value) - cdef hash_c(self): + cdef hash_c(self) noexcept: """ A C version of the __hash__ function. """ @@ -4174,7 +4174,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): sig_off() return t - cpdef RingElement _valuation(Integer self, Integer p): + cpdef RingElement _valuation(Integer self, Integer p) noexcept: r""" Return the p-adic valuation of ``self``. @@ -4199,7 +4199,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): mpz_clear(u) return v - cdef object _val_unit(Integer self, Integer p): + cdef object _val_unit(Integer self, Integer p) noexcept: r""" Return a pair: the p-adic valuation of ``self``, and the p-adic unit of ``self``. @@ -4348,7 +4348,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): mpz_tdiv_q_2exp(odd.value, self.value, bits) return odd - cdef Integer _divide_knowing_divisible_by(Integer self, Integer right): + cdef Integer _divide_knowing_divisible_by(Integer self, Integer right) noexcept: r""" Return the integer ``self`` / ``right`` when ``self`` is divisible by right. @@ -4901,7 +4901,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): return R.zero() return R(self).abs().log() - cdef bint _is_power_of(Integer self, Integer n): + cdef bint _is_power_of(Integer self, Integer n) noexcept: r""" Return a non-zero int if there is an integer b with `\mathtt{self} = n^b`. @@ -6176,7 +6176,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): d = self//4 return d%4 in [2,3] and d.is_squarefree() - cpdef __pari__(self): + cpdef __pari__(self) noexcept: """ Return the PARI version of this integer. @@ -6642,7 +6642,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): return g, s, t - cpdef _shift_helper(Integer self, y, int sign): + cpdef _shift_helper(Integer self, y, int sign) noexcept: """ Compute left and right shifts of integers. Shifts ``self`` ``y`` bits to the left if ``sign`` is `1`, and to the right @@ -6784,7 +6784,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): return x >> int(y) return (x)._shift_helper(y, -1) - cdef _and(Integer self, Integer other): + cdef _and(Integer self, Integer other) noexcept: cdef Integer x = PY_NEW(Integer) mpz_and(x.value, self.value, other.value) return x @@ -6805,7 +6805,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): return (x)._and(y) return coercion_model.bin_op(x, y, operator.and_) - cdef _or(Integer self, Integer other): + cdef _or(Integer self, Integer other) noexcept: cdef Integer x = PY_NEW(Integer) mpz_ior(x.value, self.value, other.value) return x @@ -7414,7 +7414,7 @@ cdef class int_to_Z(Morphism): from sage.sets.pythonclass import Set_PythonType Morphism.__init__(self, sage.categories.homset.Hom(Set_PythonType(int), integer_ring.ZZ)) - cpdef Element _call_(self, a): + cpdef Element _call_(self, a) noexcept: """ Return a new integer with the same value as ``a``. @@ -7459,7 +7459,7 @@ cdef class long_to_Z(Morphism): from sage.sets.pythonclass import Set_PythonType Morphism.__init__(self, sage.categories.homset.Hom(Set_PythonType(long), integer_ring.ZZ)) - cpdef Element _call_(self, a): + cpdef Element _call_(self, a) noexcept: cdef Integer r cdef long l cdef int err = 0 @@ -7607,7 +7607,7 @@ cdef PyObject* fast_tp_new(type t, args, kwds) except NULL: return new -cdef void fast_tp_dealloc(PyObject* o): +cdef void fast_tp_dealloc(PyObject* o) noexcept: # If there is room in the pool for a used integer object, # then put it in rather than deallocating it. global integer_pool, integer_pool_count @@ -7642,7 +7642,7 @@ cdef void fast_tp_dealloc(PyObject* o): from sage.misc.allocator cimport hook_tp_functions -cdef hook_fast_tp_functions(): +cdef hook_fast_tp_functions() noexcept: """ Initialize the fast integer creation functions. """ @@ -7660,7 +7660,7 @@ cdef hook_fast_tp_functions(): # to be constructed/destructed. hook_tp_functions(global_dummy_Integer, (&fast_tp_new), (&fast_tp_dealloc), False) -cdef integer(x): +cdef integer(x) noexcept: if isinstance(x, Integer): return x return Integer(x) @@ -7688,7 +7688,7 @@ hook_fast_tp_functions() # zero and one initialization initialized = False -cdef set_zero_one_elements(): +cdef set_zero_one_elements() noexcept: global the_integer_ring, initialized if initialized: return the_integer_ring._zero_element = Integer(0) @@ -7707,7 +7707,7 @@ DEF small_pool_max = 256 # we could use the above zero and one here cdef list small_pool = [Integer(k) for k in range(small_pool_min, small_pool_max+1)] -cdef inline Integer smallInteger(long value): +cdef inline Integer smallInteger(long value) noexcept: """ This is the fastest way to create a (likely) small Integer. """ diff --git a/src/sage/rings/integer_fake.pxd b/src/sage/rings/integer_fake.pxd index 4a02062c64b..2bd7a91142e 100644 --- a/src/sage/rings/integer_fake.pxd +++ b/src/sage/rings/integer_fake.pxd @@ -46,7 +46,7 @@ cdef extern from "integer_fake.h": bint unlikely(bint c) # Defined by Cython -cdef inline bint is_Integer(x): +cdef inline bint is_Integer(x) noexcept: global Integer if unlikely(Integer is NULL): import sage.rings.integer diff --git a/src/sage/rings/integer_ring.pyx b/src/sage/rings/integer_ring.pyx index c7a05a13e16..b510c4ba992 100644 --- a/src/sage/rings/integer_ring.pyx +++ b/src/sage/rings/integer_ring.pyx @@ -72,7 +72,7 @@ cimport sage.rings.integer as integer from . import ring arith = None -cdef void late_import(): +cdef void late_import() noexcept: # A hack to avoid circular imports. global arith if arith is None: @@ -524,7 +524,7 @@ cdef class IntegerRing_class(PrincipalIdealDomain): yield -n n += 1 - cpdef _coerce_map_from_(self, S): + cpdef _coerce_map_from_(self, S) noexcept: r""" ``x`` canonically coerces to the integers `\ZZ` only if ``x`` is an int, long or already an element of `\ZZ`. diff --git a/src/sage/rings/laurent_series_ring_element.pxd b/src/sage/rings/laurent_series_ring_element.pxd index 8df5a92c9e7..2b37b80e3b0 100644 --- a/src/sage/rings/laurent_series_ring_element.pxd +++ b/src/sage/rings/laurent_series_ring_element.pxd @@ -4,7 +4,7 @@ cdef class LaurentSeries(AlgebraElement): cdef ModuleElement __u cdef long __n - cdef _normalize(self) - cpdef _add_(self, other) - cpdef _mul_(self, other) + cdef _normalize(self) noexcept + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept diff --git a/src/sage/rings/laurent_series_ring_element.pyx b/src/sage/rings/laurent_series_ring_element.pyx index d56996f3f78..b15e6cbdcf0 100644 --- a/src/sage/rings/laurent_series_ring_element.pyx +++ b/src/sage/rings/laurent_series_ring_element.pyx @@ -303,7 +303,7 @@ cdef class LaurentSeries(AlgebraElement): x = im_gens[0] return codomain(self.__u._im_gens_(codomain, im_gens, base_map=base_map) * x**self.__n) - cdef _normalize(self): + cdef _normalize(self) noexcept: r""" A Laurent series is a pair (u(t), n), where either u=0 (to some precision) or u is a unit. This pair corresponds to @@ -729,7 +729,7 @@ cdef class LaurentSeries(AlgebraElement): self.__u = self.__u._parent(coeffs) self._normalize() - cpdef _add_(self, right_m): + cpdef _add_(self, right_m) noexcept: """ Add two power series with the same parent. @@ -787,7 +787,7 @@ cdef class LaurentSeries(AlgebraElement): # 3. Add return type(self)(self._parent, f1 + f2, m) - cpdef _sub_(self, right_m): + cpdef _sub_(self, right_m) noexcept: """ Subtract two power series with the same parent. @@ -915,7 +915,7 @@ cdef class LaurentSeries(AlgebraElement): """ return type(self)(self._parent, -self.__u, self.__n) - cpdef _mul_(self, right_r): + cpdef _mul_(self, right_r) noexcept: """ EXAMPLES:: @@ -930,10 +930,10 @@ cdef class LaurentSeries(AlgebraElement): self.__u * right.__u, self.__n + right.__n) - cpdef _rmul_(self, Element c): + cpdef _rmul_(self, Element c) noexcept: return type(self)(self._parent, self.__u._rmul_(c), self.__n) - cpdef _lmul_(self, Element c): + cpdef _lmul_(self, Element c) noexcept: return type(self)(self._parent, self.__u._lmul_(c), self.__n) def __pow__(_self, r, dummy): @@ -1082,7 +1082,7 @@ cdef class LaurentSeries(AlgebraElement): """ return type(self)(self._parent, self.__u >> (n - self.__n), n) - cpdef _div_(self, right_r): + cpdef _div_(self, right_r) noexcept: """ EXAMPLES:: @@ -1203,7 +1203,7 @@ cdef class LaurentSeries(AlgebraElement): """ return min(self.valuation(), other.valuation()) - cpdef _richcmp_(self, right_r, int op): + cpdef _richcmp_(self, right_r, int op) noexcept: r""" Comparison of ``self`` and ``right``. diff --git a/src/sage/rings/morphism.pyx b/src/sage/rings/morphism.pyx index 5f7dc12cdb1..04fca55cd60 100644 --- a/src/sage/rings/morphism.pyx +++ b/src/sage/rings/morphism.pyx @@ -514,7 +514,7 @@ cdef class RingMap_lift(RingMap): H = R.Hom(S, Sets()) RingMap.__init__(self, H) - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -533,7 +533,7 @@ cdef class RingMap_lift(RingMap): self.to_S = _slots['to_S'] Morphism._update_slots(self, _slots) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -549,7 +549,7 @@ cdef class RingMap_lift(RingMap): slots['to_S'] = self.to_S return slots - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ Compare a ring lifting maps ``self`` to ``other``. @@ -613,7 +613,7 @@ cdef class RingMap_lift(RingMap): """ return "Choice of lifting map" - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Evaluate this function at ``x``. @@ -700,7 +700,7 @@ cdef class RingHomomorphism(RingMap): raise TypeError("lift must have correct codomain") self._lift = lift - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -719,7 +719,7 @@ cdef class RingHomomorphism(RingMap): self._lift = _slots['_lift'] Morphism._update_slots(self, _slots) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1809,7 +1809,7 @@ cdef class RingHomomorphism_im_gens(RingHomomorphism): """ return self._base_map - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1829,7 +1829,7 @@ cdef class RingHomomorphism_im_gens(RingHomomorphism): self._base_map = _slots.get('_base_map') RingHomomorphism._update_slots(self, _slots) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1850,7 +1850,7 @@ cdef class RingHomomorphism_im_gens(RingHomomorphism): slots['_base_map'] = self._base_map return slots - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: r""" EXAMPLES: @@ -1957,7 +1957,7 @@ cdef class RingHomomorphism_im_gens(RingHomomorphism): s += '\nwith map of base ring' return s - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Evaluate this homomorphism at ``x``. @@ -2121,7 +2121,7 @@ cdef class RingHomomorphism_from_base(RingHomomorphism): """ return self._underlying - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -2151,7 +2151,7 @@ cdef class RingHomomorphism_from_base(RingHomomorphism): self._underlying = _slots['__underlying'] # double underscore for legacy pickles RingHomomorphism._update_slots(self, _slots) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -2182,7 +2182,7 @@ cdef class RingHomomorphism_from_base(RingHomomorphism): slots['__underlying'] = self._underlying return slots - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: r""" EXAMPLES: @@ -2266,7 +2266,7 @@ cdef class RingHomomorphism_from_base(RingHomomorphism): U = repr(self._underlying).split('\n') return 'Induced from base ring by\n'+'\n'.join(U) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Evaluate this homomorphism at ``x``. @@ -2370,7 +2370,7 @@ cdef class RingHomomorphism_from_fraction_field(RingHomomorphism): """ return self._morphism._repr_defn() - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: r""" Return the value of this morphism at ``x``. @@ -2389,7 +2389,7 @@ cdef class RingHomomorphism_from_fraction_field(RingHomomorphism): """ return self._morphism(x.numerator()) / self._morphism(x.denominator()) - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper function for copying and pickling. @@ -2408,7 +2408,7 @@ cdef class RingHomomorphism_from_fraction_field(RingHomomorphism): self._morphism = _slots['_morphism'] RingHomomorphism._update_slots(self, _slots) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper function for copying and pickling. @@ -2475,7 +2475,7 @@ cdef class RingHomomorphism_cover(RingHomomorphism): """ RingHomomorphism.__init__(self, parent) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Evaluate this covering homomorphism at ``x``, which just involves coercing ``x`` into the domain, then codomain. @@ -2534,7 +2534,7 @@ cdef class RingHomomorphism_cover(RingHomomorphism): """ return self.codomain().defining_ideal() - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ Compare ``self`` to ``other``. @@ -2685,7 +2685,7 @@ cdef class RingHomomorphism_from_quotient(RingHomomorphism): self._lift = pi.lift() self.phi = phi - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -2714,7 +2714,7 @@ cdef class RingHomomorphism_from_quotient(RingHomomorphism): self.phi = _slots['phi'] RingHomomorphism._update_slots(self, _slots) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -2778,7 +2778,7 @@ cdef class RingHomomorphism_from_quotient(RingHomomorphism): """ return self.phi - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ Compare ``self`` to ``other``. @@ -2839,7 +2839,7 @@ cdef class RingHomomorphism_from_quotient(RingHomomorphism): return '\n'.join('{} |--> {}'.format(D.gen(i), ig[i]) for i in range(D.ngens())) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Evaluate this function at ``x``. @@ -2898,7 +2898,7 @@ cdef class FrobeniusEndomorphism_generic(RingHomomorphism): self._q = self._p ** self._power RingHomomorphism.__init__(self, Hom(domain, domain)) - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Update information with the given slots. @@ -2918,7 +2918,7 @@ cdef class FrobeniusEndomorphism_generic(RingHomomorphism): self._q = self._p ** self._power RingHomomorphism._update_slots(self, _slots) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Return additional information about this morphism as a dictionary. @@ -3008,7 +3008,7 @@ cdef class FrobeniusEndomorphism_generic(RingHomomorphism): s = '\\verb"Frob"^{%s}' % self._power return s - cpdef Element _call_ (self, x): + cpdef Element _call_ (self, x) noexcept: """ TESTS:: diff --git a/src/sage/rings/number_field/class_group.py b/src/sage/rings/number_field/class_group.py index 2bae4dd2df0..93f22993eb3 100644 --- a/src/sage/rings/number_field/class_group.py +++ b/src/sage/rings/number_field/class_group.py @@ -591,8 +591,7 @@ def _iter_inner(self, i0, k): return gk = self.gen(k) for _ in range(self._gens_orders[k]): - for J in self._iter_inner(i0, k + 1): - yield J + yield from self._iter_inner(i0, k + 1) i0 = i0 * gk return diff --git a/src/sage/rings/number_field/number_field_base.pxd b/src/sage/rings/number_field/number_field_base.pxd index ba6a8e98143..f34a25d0dcb 100644 --- a/src/sage/rings/number_field/number_field_base.pxd +++ b/src/sage/rings/number_field/number_field_base.pxd @@ -4,4 +4,4 @@ cdef class NumberField(Field): cdef int _embedded_real cdef list _gen_approx - cpdef _get_embedding_approx(self, size_t i) + cpdef _get_embedding_approx(self, size_t i) noexcept diff --git a/src/sage/rings/number_field/number_field_base.pyx b/src/sage/rings/number_field/number_field_base.pyx index 1d09825477a..538dc8b0579 100644 --- a/src/sage/rings/number_field/number_field_base.pyx +++ b/src/sage/rings/number_field/number_field_base.pyx @@ -392,7 +392,7 @@ cdef class NumberField(Field): self._gen_approx = [] self._embedded_real = 1 - cpdef _get_embedding_approx(self, size_t i): + cpdef _get_embedding_approx(self, size_t i) noexcept: r""" Return an interval approximation of the generator of this number field. diff --git a/src/sage/rings/number_field/number_field_element.pxd b/src/sage/rings/number_field/number_field_element.pxd index c3d8a8b4a4b..612e5cce09c 100644 --- a/src/sage/rings/number_field/number_field_element.pxd +++ b/src/sage/rings/number_field/number_field_element.pxd @@ -21,26 +21,26 @@ cdef class NumberFieldElement(NumberFieldElement_base): cdef object __pari cdef object __matrix - cdef _new(self) - cpdef _add_(self, other) - cpdef _mul_(self, other) + cdef _new(self) noexcept + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept - cpdef _add_(self, other) - cpdef _mul_(self, other) + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept - cpdef _copy_for_parent(self, Parent parent) + cpdef _copy_for_parent(self, Parent parent) noexcept - cdef number_field(self) + cdef number_field(self) noexcept - cdef void _ntl_coeff_as_mpz(self, mpz_t z, long i) - cdef void _ntl_denom_as_mpz(self, mpz_t z) + cdef void _ntl_coeff_as_mpz(self, mpz_t z, long i) noexcept + cdef void _ntl_denom_as_mpz(self, mpz_t z) noexcept - cdef void _reduce_c_(self) + cdef void _reduce_c_(self) noexcept - cpdef list _coefficients(self) + cpdef list _coefficients(self) noexcept - cpdef bint is_rational(self) - cpdef bint is_one(self) + cpdef bint is_rational(self) noexcept + cpdef bint is_one(self) noexcept cdef int _randomize(self, num_bound, den_bound, distribution) except -1 diff --git a/src/sage/rings/number_field/number_field_element.pyx b/src/sage/rings/number_field/number_field_element.pyx index 749b10437f3..e141c38ba79 100644 --- a/src/sage/rings/number_field/number_field_element.pyx +++ b/src/sage/rings/number_field/number_field_element.pyx @@ -172,7 +172,7 @@ cdef class NumberFieldElement(NumberFieldElement_base): sage: a^3 -a - 1 """ - cdef _new(self): + cdef _new(self) noexcept: """ Quickly creates a new initialized NumberFieldElement with the same parent as self. @@ -184,7 +184,7 @@ cdef class NumberFieldElement(NumberFieldElement_base): x._fld_denominator = self._fld_denominator return x - cdef number_field(self): + cdef number_field(self) noexcept: r""" Return the number field of self. Only accessible from Cython. @@ -784,7 +784,7 @@ cdef class NumberFieldElement(NumberFieldElement_base): return QQ.zero() return coeffs[n] - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: r""" EXAMPLES:: @@ -2438,7 +2438,7 @@ cdef class NumberFieldElement(NumberFieldElement_base): else: return sbase.power(exp, hold=True) - cdef void _reduce_c_(self): + cdef void _reduce_c_(self) noexcept: """ Pull out common factors from the numerator and denominator! """ @@ -2457,7 +2457,7 @@ cdef class NumberFieldElement(NumberFieldElement_base): self._numerator = t2 self._denominator = t1 - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: r""" EXAMPLES:: @@ -2483,7 +2483,7 @@ cdef class NumberFieldElement(NumberFieldElement_base): x._reduce_c_() return x - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: r""" EXAMPLES:: @@ -2508,7 +2508,7 @@ cdef class NumberFieldElement(NumberFieldElement_base): x._reduce_c_() return x - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Returns the product of self and other as elements of a number field. @@ -2556,7 +2556,7 @@ cdef class NumberFieldElement(NumberFieldElement_base): # but asymptotically fast poly multiplication means it's # actually faster to *not* build a table!?! - cpdef _div_(self, other): + cpdef _div_(self, other) noexcept: """ Returns the quotient of self and other as elements of a number field. @@ -2668,7 +2668,7 @@ cdef class NumberFieldElement(NumberFieldElement_base): """ return not IsZero_ZZX(self._numerator) - cpdef _neg_(self): + cpdef _neg_(self) noexcept: r""" EXAMPLES:: @@ -2683,7 +2683,7 @@ cdef class NumberFieldElement(NumberFieldElement_base): x._denominator = self._denominator return x - cpdef _copy_for_parent(self, Parent parent): + cpdef _copy_for_parent(self, Parent parent) noexcept: r""" Return a copy of ``self`` with the parent replaced by ``parent``. @@ -3247,7 +3247,7 @@ cdef class NumberFieldElement(NumberFieldElement_base): return h - cpdef list _coefficients(self): + cpdef list _coefficients(self) noexcept: """ Return the coefficients of the underlying polynomial corresponding to this number field element. @@ -3280,13 +3280,13 @@ cdef class NumberFieldElement(NumberFieldElement_base): mpz_clear(den) return coeffs - cdef void _ntl_coeff_as_mpz(self, mpz_t z, long i): + cdef void _ntl_coeff_as_mpz(self, mpz_t z, long i) noexcept: if i > ZZX_deg(self._numerator): mpz_set_ui(z, 0) else: ZZX_getitem_as_mpz(z, &self._numerator, i) - cdef void _ntl_denom_as_mpz(self, mpz_t z): + cdef void _ntl_denom_as_mpz(self, mpz_t z) noexcept: cdef Integer denom = Integer.__new__(Integer) ZZ_to_mpz(denom.value, &self._denominator) mpz_set(z, denom.value) @@ -3418,7 +3418,7 @@ cdef class NumberFieldElement(NumberFieldElement_base): if not self: return ZZ.one() else: return sage.rings.infinity.infinity - cpdef bint is_one(self): + cpdef bint is_one(self) noexcept: r""" Test whether this number field element is `1`. @@ -3440,7 +3440,7 @@ cdef class NumberFieldElement(NumberFieldElement_base): return ZZX_IsOne(self._numerator) == 1 and \ ZZ_IsOne(self._denominator) == 1 - cpdef bint is_rational(self): + cpdef bint is_rational(self) noexcept: r""" Test whether this number field element is a rational number. @@ -5267,7 +5267,7 @@ cdef class OrderElement_absolute(NumberFieldElement_absolute): self._number_field = K (self)._parent = order - cdef _new(self): + cdef _new(self) noexcept: """ Quickly creates a new initialized NumberFieldElement with the same parent as ``self``. @@ -5289,7 +5289,7 @@ cdef class OrderElement_absolute(NumberFieldElement_absolute): x._fld_denominator = self._fld_denominator return x - cdef number_field(self): + cdef number_field(self) noexcept: r""" Return the number field of ``self``. Only accessible from Cython. @@ -5383,10 +5383,10 @@ cdef class OrderElement_relative(NumberFieldElement_relative): (self)._parent = order self._number_field = K - cdef number_field(self): + cdef number_field(self) noexcept: return self._number_field - cdef _new(self): + cdef _new(self) noexcept: """ Quickly creates a new initialized NumberFieldElement with the same parent as self. @@ -5695,7 +5695,7 @@ class CoordinateFunction(): ################# -cdef void _ntl_poly(f, ZZX_c *num, ZZ_c *den): +cdef void _ntl_poly(f, ZZX_c *num, ZZ_c *den) noexcept: cdef long i cdef ZZ_c coeff cdef ntl_ZZX _num diff --git a/src/sage/rings/number_field/number_field_element_quadratic.pxd b/src/sage/rings/number_field/number_field_element_quadratic.pxd index 7a4f063de73..76661971848 100644 --- a/src/sage/rings/number_field/number_field_element_quadratic.pxd +++ b/src/sage/rings/number_field/number_field_element_quadratic.pxd @@ -10,25 +10,25 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute): cdef mpz_t a, b, denom cdef Integer D cdef bint standard_embedding - cpdef NumberFieldElement galois_conjugate(self) + cpdef NumberFieldElement galois_conjugate(self) noexcept - cpdef list _coefficients(self) + cpdef list _coefficients(self) noexcept cdef int _randomize(self, num_bound, den_bound, distribution) except -1 cdef int arb_set_real(self, arb_t x, long prec) except -1 - cdef void arb_set_imag(self, arb_t x, long prec) + cdef void arb_set_imag(self, arb_t x, long prec) noexcept - cpdef tuple parts(self) + cpdef tuple parts(self) noexcept cdef class NumberFieldElement_quadratic_sqrt(NumberFieldElement_quadratic): pass cdef class NumberFieldElement_gaussian(NumberFieldElement_quadratic_sqrt): - cpdef real_part(self) - cpdef imag_part(self) + cpdef real_part(self) noexcept + cpdef imag_part(self) noexcept cdef class OrderElement_quadratic(NumberFieldElement_quadratic): pass -cpdef bint is_sqrt_disc(Rational ad, Rational bd) +cpdef bint is_sqrt_disc(Rational ad, Rational bd) noexcept diff --git a/src/sage/rings/number_field/number_field_element_quadratic.pyx b/src/sage/rings/number_field/number_field_element_quadratic.pyx index c32f6aadd10..57c2df2cb43 100644 --- a/src/sage/rings/number_field/number_field_element_quadratic.pyx +++ b/src/sage/rings/number_field/number_field_element_quadratic.pyx @@ -225,7 +225,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute): # __cmp__, sign, real, imag, floor, ceil, ... self.standard_embedding = parent._standard_embedding - cdef _new(self): + cdef _new(self) noexcept: """ Quickly creates a new initialized NumberFieldElement_quadratic with the same parent as self. @@ -243,7 +243,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute): x.D = self.D return x - cdef number_field(self): + cdef number_field(self) noexcept: r""" Return the number field to which this element belongs. Since this is a Cython cdef method, it is not directly accessible by the user, but the @@ -350,7 +350,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute): mpz_set(denom.value, self.denom) return "new QuadraticExtension({}, {}, {})".format(a/denom, b/denom, self.D) - cpdef _copy_for_parent(self, Parent parent): + cpdef _copy_for_parent(self, Parent parent) noexcept: r""" Return a copy of ``self`` with the parent replaced by ``parent``. @@ -786,7 +786,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute): fmpz_clear(tmpz) return 0 - cdef void arb_set_imag(self, arb_t x, long prec): + cdef void arb_set_imag(self, arb_t x, long prec) noexcept: "Set x to the imaginary part of this element" cdef fmpz_t tmpz cdef arb_t rootD @@ -892,7 +892,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute): self.arb_set_imag(acb_imagref(res.value), R._prec) return res - cpdef tuple parts(self): + cpdef tuple parts(self) noexcept: r""" Return a pair of rationals `a` and `b` such that ``self`` `= a+b\sqrt{D}`. @@ -1038,7 +1038,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute): return test return -test - cpdef _richcmp_(left, _right, int op): + cpdef _richcmp_(left, _right, int op) noexcept: r""" Rich comparison of elements. @@ -1295,7 +1295,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute): # Arithmetic ######################################################### - cdef void _reduce_c_(self): + cdef void _reduce_c_(self) noexcept: r""" Reduces into canonical form. @@ -1318,7 +1318,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute): mpz_clear(gcd) - cpdef _add_(self, other_m): + cpdef _add_(self, other_m) noexcept: """ EXAMPLES:: @@ -1376,7 +1376,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute): return res - cpdef _sub_(self, other_m): + cpdef _sub_(self, other_m) noexcept: """ EXAMPLES:: @@ -1444,7 +1444,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute): mpz_set(res.denom, self.denom) return res - cpdef _mul_(self, other_m): + cpdef _mul_(self, other_m) noexcept: """ EXAMPLES:: @@ -1512,7 +1512,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute): res._reduce_c_() return res - cpdef _rmul_(self, Element _c): + cpdef _rmul_(self, Element _c) noexcept: """ EXAMPLES:: @@ -1529,7 +1529,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute): res._reduce_c_() return res - cpdef _lmul_(self, Element _c): + cpdef _lmul_(self, Element _c) noexcept: """ EXAMPLES:: @@ -1613,7 +1613,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute): res._reduce_c_() return res - cpdef NumberFieldElement galois_conjugate(self): + cpdef NumberFieldElement galois_conjugate(self) noexcept: """ Return the image of this element under action of the nontrivial element of the Galois group of this field. @@ -1734,7 +1734,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute): mpq_canonicalize(res.value) return res - cpdef bint is_one(self): + cpdef bint is_one(self) noexcept: r""" Check whether this number field element is `1`. @@ -1758,7 +1758,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute): mpz_cmp_ui(self.b, 0) == 0 and mpz_cmp_ui(self.denom, 1) == 0) - cpdef bint is_rational(self): + cpdef bint is_rational(self) noexcept: r""" Check whether this number field element is a rational number. @@ -1931,7 +1931,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute): mpz_neg(q.b, self.b) return q - cpdef list _coefficients(self): + cpdef list _coefficients(self) noexcept: """ EXAMPLES:: @@ -2417,7 +2417,7 @@ cdef class NumberFieldElement_quadratic_sqrt(NumberFieldElement_quadratic): mpz_set(denom.value, self.denom) return denom - cpdef list _coefficients(self): + cpdef list _coefficients(self) noexcept: """ EXAMPLES:: @@ -2557,7 +2557,7 @@ cdef class NumberFieldElement_gaussian(NumberFieldElement_quadratic_sqrt): return qqbar.AlgebraicReal(coeffs[0]) raise ValueError(f"unable to convert {self!r} to an element of {parent!r}") - cpdef real_part(self): + cpdef real_part(self) noexcept: r""" Real part. @@ -2579,7 +2579,7 @@ cdef class NumberFieldElement_gaussian(NumberFieldElement_quadratic_sqrt): real = real_part - cpdef imag_part(self): + cpdef imag_part(self) noexcept: r""" Imaginary part. @@ -2744,14 +2744,14 @@ cdef class OrderElement_quadratic(NumberFieldElement_quadratic): else: return self.charpoly() - cdef number_field(self): + cdef number_field(self) noexcept: # So few functions actually use self.number_field() for quadratic elements, so # it is better *not* to return a cached value (since the call to _parent.number_field()) # is expensive. return self._parent.number_field() # We must override these since the basering is now ZZ not QQ. - cpdef _rmul_(self, Element _c): + cpdef _rmul_(self, Element _c) noexcept: """ EXAMPLES:: @@ -2771,7 +2771,7 @@ cdef class OrderElement_quadratic(NumberFieldElement_quadratic): res._reduce_c_() return res - cpdef _lmul_(self, Element _c): + cpdef _lmul_(self, Element _c) noexcept: """ EXAMPLES:: @@ -2840,7 +2840,7 @@ cdef class OrderElement_quadratic(NumberFieldElement_quadratic): R = self.parent() return R(_inverse_mod_generic(self, I)) - cpdef list _coefficients(self): + cpdef list _coefficients(self) noexcept: """ EXAMPLES:: @@ -2945,7 +2945,7 @@ cdef class Z_to_quadratic_field_element(Morphism): import sage.categories.homset Morphism.__init__(self, sage.categories.homset.Hom(ZZ, K)) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: r""" Evaluate at an integer ``x``. @@ -3047,7 +3047,7 @@ cdef class Q_to_quadratic_field_element(Morphism): import sage.categories.homset Morphism.__init__(self, sage.categories.homset.Hom(QQ, K)) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: r""" Evaluate at a rational ``x``. @@ -3099,7 +3099,7 @@ cdef class Q_to_quadratic_field_element(Morphism): ##################################################################### ## Helper function -cpdef bint is_sqrt_disc(Rational ad, Rational bd): +cpdef bint is_sqrt_disc(Rational ad, Rational bd) noexcept: r""" Return ``True`` if the pair ``(ad, bd)`` is `\sqrt{D}`. diff --git a/src/sage/rings/number_field/number_field_morphisms.pyx b/src/sage/rings/number_field/number_field_morphisms.pyx index 862b32ffc02..18c2c54d2f2 100644 --- a/src/sage/rings/number_field/number_field_morphisms.pyx +++ b/src/sage/rings/number_field/number_field_morphisms.pyx @@ -61,7 +61,7 @@ cdef class NumberFieldEmbedding(Morphism): else: self._gen_image = R(gen_embedding) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ A helper for pickling and copying. @@ -92,7 +92,7 @@ cdef class NumberFieldEmbedding(Morphism): slots['_gen_image'] = self._gen_image return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ A helper for unpickling and copying. @@ -118,7 +118,7 @@ cdef class NumberFieldEmbedding(Morphism): Morphism._update_slots(self, _slots) self._gen_image = _slots['_gen_image'] - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ EXAMPLES:: @@ -321,7 +321,7 @@ cdef class EmbeddedNumberFieldConversion(Map): self.ambient_field = ambient_field Map.__init__(self, K, L) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ EXAMPLES:: @@ -343,7 +343,7 @@ cdef class EmbeddedNumberFieldConversion(Map): return gen_image -cpdef matching_root(poly, target, ambient_field=None, margin=1, max_prec=None): +cpdef matching_root(poly, target, ambient_field=None, margin=1, max_prec=None) noexcept: """ Given a polynomial and a ``target``, choose the root that ``target`` best approximates as compared in ``ambient_field``. @@ -406,7 +406,7 @@ cpdef matching_root(poly, target, ambient_field=None, margin=1, max_prec=None): ambient_field = ambient_field.to_prec(ambient_field.prec() * 2) -cpdef closest(target, values, margin=1): +cpdef closest(target, values, margin=1) noexcept: """ This is a utility function that returns the item in ``values`` closest to target (with respect to the ``abs`` function). If ``margin`` is greater @@ -625,7 +625,7 @@ cdef class CyclotomicFieldEmbedding(NumberFieldEmbedding): self.ratio = L._log_gen(K.coerce_embedding()(K.gen())) self._gen_image = L.gen() ** self.ratio - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ A helper for pickling and copying. @@ -656,7 +656,7 @@ cdef class CyclotomicFieldEmbedding(NumberFieldEmbedding): slots['ratio'] = self.ratio return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ A helper for unpickling and copying. @@ -683,7 +683,7 @@ cdef class CyclotomicFieldEmbedding(NumberFieldEmbedding): self._gen_image = _slots['_gen_image'] self.ratio = _slots['ratio'] - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ EXAMPLES:: @@ -764,7 +764,7 @@ cdef class CyclotomicFieldConversion(Map): self.phi = L.hom([M.gen()**(n3//n2)]) Map.__init__(self, K, L) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Call a conversion map between cyclotomic fields. diff --git a/src/sage/rings/number_field/order.py b/src/sage/rings/number_field/order.py index e789a97bc75..f0b24b74630 100644 --- a/src/sage/rings/number_field/order.py +++ b/src/sage/rings/number_field/order.py @@ -1083,6 +1083,14 @@ def class_number(self, proof=None): NotImplementedError: computation of class numbers of non-maximal orders not in quadratic fields is not implemented + TESTS: + + Test for PARI bug #2466:: + + sage: x = polygen(ZZ) + sage: R. = EquationOrder(x^2 - 8461) + sage: R.class_number() + 3 """ if not self.is_maximal(): K = self.number_field() diff --git a/src/sage/rings/number_field/totallyreal.pyx b/src/sage/rings/number_field/totallyreal.pyx index 87ae68a4d59..505bf92c35f 100644 --- a/src/sage/rings/number_field/totallyreal.pyx +++ b/src/sage/rings/number_field/totallyreal.pyx @@ -112,7 +112,7 @@ from sage.rings.number_field.totallyreal_data import tr_data, int_has_small_squa from sage.rings.number_field.totallyreal_data cimport tr_data -cpdef double odlyzko_bound_totallyreal(int n): +cpdef double odlyzko_bound_totallyreal(int n) noexcept: r""" This function returns the unconditional Odlyzko bound for the root discriminant of a totally real number field of degree `n`. diff --git a/src/sage/rings/number_field/totallyreal_data.pxd b/src/sage/rings/number_field/totallyreal_data.pxd index 57ab69dca8b..efa01dbb4b7 100644 --- a/src/sage/rings/number_field/totallyreal_data.pxd +++ b/src/sage/rings/number_field/totallyreal_data.pxd @@ -1,13 +1,13 @@ -cdef double eval_seq_as_poly(int *f, int n, double x) -cdef double newton(int *f, int *df, int n, double x0, double eps) -cdef void newton_in_intervals(int *f, int *df, int n, double *beta, double eps, double *rts) -cpdef lagrange_degree_3(int n, int an1, int an2, int an3) +cdef double eval_seq_as_poly(int *f, int n, double x) noexcept +cdef double newton(int *f, int *df, int n, double x0, double eps) noexcept +cdef void newton_in_intervals(int *f, int *df, int n, double *beta, double eps, double *rts) noexcept +cpdef lagrange_degree_3(int n, int an1, int an2, int an3) noexcept cimport sage.rings.integer -cdef int eval_seq_as_poly_int(int *f, int n, int x) +cdef int eval_seq_as_poly_int(int *f, int n, int x) noexcept -cdef int easy_is_irreducible(int *a, int n) +cdef int easy_is_irreducible(int *a, int n) noexcept cdef class tr_data: @@ -22,5 +22,5 @@ cdef class tr_data: cdef int *df - cdef void incr(self, int *f_out, int verbose, int haltk, int phc) + cdef void incr(self, int *f_out, int verbose, int haltk, int phc) noexcept diff --git a/src/sage/rings/number_field/totallyreal_data.pyx b/src/sage/rings/number_field/totallyreal_data.pyx index 84e292f79b2..e504fb6b45f 100644 --- a/src/sage/rings/number_field/totallyreal_data.pyx +++ b/src/sage/rings/number_field/totallyreal_data.pyx @@ -112,7 +112,7 @@ def hermite_constant(n): return gamma -cdef double eval_seq_as_poly(int *f, int n, double x): +cdef double eval_seq_as_poly(int *f, int n, double x) noexcept: r""" Evaluates the sequence a, thought of as a polynomial with @@ -129,7 +129,7 @@ cdef double eval_seq_as_poly(int *f, int n, double x): s = s * x + f[i] return s -cdef double newton(int *f, int *df, int n, double x0, double eps): +cdef double newton(int *f, int *df, int n, double x0, double eps) noexcept: r""" Find the real root x of f (with derivative df) near x0 with provable precision eps, i.e. |x-z| < eps where z is the actual @@ -174,7 +174,7 @@ cdef double newton(int *f, int *df, int n, double x0, double eps): return x cdef void newton_in_intervals(int *f, int *df, int n, double *beta, - double eps, double *rts): + double eps, double *rts) noexcept: r""" Find the real roots of f in the intervals specified by beta: @@ -192,7 +192,7 @@ cdef void newton_in_intervals(int *f, int *df, int n, double *beta, for i from 0 <= i < n: rts[i] = newton(f, df, n, (beta[i]+beta[i+1])/2, eps) -cpdef lagrange_degree_3(int n, int an1, int an2, int an3): +cpdef lagrange_degree_3(int n, int an1, int an2, int an3) noexcept: r""" Private function. Solves the equations which arise in the Lagrange multiplier for degree 3: for each `1 \leq r \leq n-2`, we solve @@ -346,7 +346,7 @@ def int_has_small_square_divisor(sage.rings.integer.Integer d): return asq -cdef int eval_seq_as_poly_int(int *f, int n, int x): +cdef int eval_seq_as_poly_int(int *f, int n, int x) noexcept: r""" Evaluates the sequence a, thought of as a polynomial with @@ -366,7 +366,7 @@ eps_abs = 10.**(-12) phi = 0.618033988749895 sqrt2 = 1.41421356237310 -cdef int easy_is_irreducible(int *a, int n): +cdef int easy_is_irreducible(int *a, int n) noexcept: r""" Very often, polynomials have roots in {+/-1, +/-2, +/-phi, sqrt2}, so we rule these out quickly. Returns 0 if reducible, 1 if inconclusive. @@ -635,7 +635,7 @@ cdef class tr_data: return g - cdef void incr(self, int *f_out, int verbose, int haltk, int phc): + cdef void incr(self, int *f_out, int verbose, int haltk, int phc) noexcept: r""" This function 'increments' the totally real data to the next value which satisfies the bounds essentially given by Rolle's diff --git a/src/sage/rings/padics/CA_template.pxi b/src/sage/rings/padics/CA_template.pxi index 152db86eaf9..cf4eb55a327 100644 --- a/src/sage/rings/padics/CA_template.pxi +++ b/src/sage/rings/padics/CA_template.pxi @@ -94,7 +94,7 @@ cdef class CAElement(pAdicTemplateElement): else: cconv(self.value, x, self.absprec, 0, self.prime_pow) - cdef CAElement _new_c(self): + cdef CAElement _new_c(self) noexcept: """ Create a new element with the same basic info. @@ -119,7 +119,7 @@ cdef class CAElement(pAdicTemplateElement): cconstruct(ans.value, ans.prime_pow) return ans - cdef pAdicTemplateElement _new_with_value(self, celement value, long absprec): + cdef pAdicTemplateElement _new_with_value(self, celement value, long absprec) noexcept: """ Create a new element with a given value and absolute precision. @@ -196,7 +196,7 @@ cdef class CAElement(pAdicTemplateElement): """ return unpickle_cae_v2, (self.__class__, self.parent(), cpickle(self.value, self.prime_pow), self.absprec) - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ Return the additive inverse of this element. @@ -213,7 +213,7 @@ cdef class CAElement(pAdicTemplateElement): creduce_small(ans.value, ans.value, ans.absprec, ans.prime_pow) return ans - cpdef _add_(self, _right): + cpdef _add_(self, _right) noexcept: """ Return the sum of this element and ``_right``. @@ -237,7 +237,7 @@ cdef class CAElement(pAdicTemplateElement): creduce(ans.value, ans.value, ans.absprec, ans.prime_pow) return ans - cpdef _sub_(self, _right): + cpdef _sub_(self, _right) noexcept: """ Return the difference of this element and ``_right``. @@ -281,7 +281,7 @@ cdef class CAElement(pAdicTemplateElement): """ return ~self.parent().fraction_field()(self) - cpdef _mul_(self, _right): + cpdef _mul_(self, _right) noexcept: """ Return the product of this element and ``_right``. @@ -304,7 +304,7 @@ cdef class CAElement(pAdicTemplateElement): creduce(ans.value, ans.value, ans.absprec, ans.prime_pow) return ans - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Return the quotient of this element and ``right``. @@ -531,7 +531,7 @@ cdef class CAElement(pAdicTemplateElement): pright.value, rval, pright.absprec, self.prime_pow) return ans - cdef pAdicTemplateElement _lshift_c(self, long shift): + cdef pAdicTemplateElement _lshift_c(self, long shift) noexcept: r""" Multiplies by `\pi^{\mbox{shift}}`. @@ -563,7 +563,7 @@ cdef class CAElement(pAdicTemplateElement): cshift_notrunc(ans.value, self.value, shift, ans.absprec, ans.prime_pow, self.prime_pow.e > 1) return ans - cdef pAdicTemplateElement _rshift_c(self, long shift): + cdef pAdicTemplateElement _rshift_c(self, long shift) noexcept: r""" Divides by ``π^{\mbox{shift}}``. @@ -812,7 +812,7 @@ cdef class CAElement(pAdicTemplateElement): return 0 return ccmp(self.value, right.value, aprec, aprec < self.absprec, aprec < right.absprec, self.prime_pow) - cdef pAdicTemplateElement lift_to_precision_c(self, long absprec): + cdef pAdicTemplateElement lift_to_precision_c(self, long absprec) noexcept: """ Return an arbitrary lift of this element to higher precision. @@ -995,7 +995,7 @@ cdef class CAElement(pAdicTemplateElement): mpz_set_si(ans.value, self.absprec - self.valuation_c()) return ans - cpdef pAdicTemplateElement unit_part(CAElement self): + cpdef pAdicTemplateElement unit_part(CAElement self) noexcept: r""" Return the unit part of this element. @@ -1015,7 +1015,7 @@ cdef class CAElement(pAdicTemplateElement): ans.absprec = (self).absprec - val return ans - cdef long valuation_c(self): + cdef long valuation_c(self) noexcept: """ Return the valuation of this element. @@ -1043,7 +1043,7 @@ cdef class CAElement(pAdicTemplateElement): """ return cvaluation(self.value, self.absprec, self.prime_pow) - cpdef val_unit(self): + cpdef val_unit(self) noexcept: r""" Return a 2-tuple, the first element set to the valuation of this element, and the second to the unit part of this element. @@ -1112,7 +1112,7 @@ cdef class pAdicCoercion_ZZ_CA(RingHomomorphism): self._zero = R.element_class(R, 0) self._section = pAdicConvert_CA_ZZ(R) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1132,7 +1132,7 @@ cdef class pAdicCoercion_ZZ_CA(RingHomomorphism): _slots['_section'] = self.section() # use method since it copies coercion-internal sections. return _slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1151,7 +1151,7 @@ cdef class pAdicCoercion_ZZ_CA(RingHomomorphism): self._section = _slots['_section'] RingHomomorphism._update_slots(self, _slots) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Evaluation. @@ -1170,7 +1170,7 @@ cdef class pAdicCoercion_ZZ_CA(RingHomomorphism): cconv_mpz_t(ans.value, (x).value, ans.absprec, True, ans.prime_pow) return ans - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ This function is used when some precision cap is passed in (relative or absolute or both). @@ -1265,7 +1265,7 @@ cdef class pAdicConvert_CA_ZZ(RingMap): else: RingMap.__init__(self, Hom(R, ZZ, Sets())) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: """ Evaluation. @@ -1306,7 +1306,7 @@ cdef class pAdicConvert_QQ_CA(Morphism): Morphism.__init__(self, Hom(QQ, R, SetsWithPartialMaps())) self._zero = R.element_class(R, 0) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1325,7 +1325,7 @@ cdef class pAdicConvert_QQ_CA(Morphism): _slots['_zero'] = self._zero return _slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1343,7 +1343,7 @@ cdef class pAdicConvert_QQ_CA(Morphism): self._zero = _slots['_zero'] Morphism._update_slots(self, _slots) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Evaluation. @@ -1362,7 +1362,7 @@ cdef class pAdicConvert_QQ_CA(Morphism): ans.absprec = ans.prime_pow.ram_prec_cap return ans - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ This function is used when some precision cap is passed in (relative or absolute or both). @@ -1443,7 +1443,7 @@ cdef class pAdicCoercion_CA_frac_field(RingHomomorphism): self._zero = K(0) self._section = pAdicConvert_CA_frac_field(K, R) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: """ Evaluation. @@ -1467,7 +1467,7 @@ cdef class pAdicCoercion_CA_frac_field(RingHomomorphism): ans._normalize() return ans - cpdef Element _call_with_args(self, _x, args=(), kwds={}): + cpdef Element _call_with_args(self, _x, args=(), kwds={}) noexcept: """ This function is used when some precision cap is passed in (relative or absolute or both). @@ -1543,7 +1543,7 @@ cdef class pAdicCoercion_CA_frac_field(RingHomomorphism): self._section = copy.copy(self._section) return self._section - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1572,7 +1572,7 @@ cdef class pAdicCoercion_CA_frac_field(RingHomomorphism): _slots['_section'] = self.section() # use method since it copies coercion-internal sections. return _slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1658,7 +1658,7 @@ cdef class pAdicConvert_CA_frac_field(Morphism): Morphism.__init__(self, Hom(K, R, SetsWithPartialMaps())) self._zero = R(0) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: """ Evaluation. @@ -1689,7 +1689,7 @@ cdef class pAdicConvert_CA_frac_field(Morphism): ans.value._coeffs = [R(c) for c in ans.value._coeffs] return ans - cpdef Element _call_with_args(self, _x, args=(), kwds={}): + cpdef Element _call_with_args(self, _x, args=(), kwds={}) noexcept: """ This function is used when some precision cap is passed in (relative or absolute or both). @@ -1744,7 +1744,7 @@ cdef class pAdicConvert_CA_frac_field(Morphism): ans.value._coeffs = [R(c) for c in ans.value._coeffs] return ans - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1772,7 +1772,7 @@ cdef class pAdicConvert_CA_frac_field(Morphism): _slots['_zero'] = self._zero return _slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. diff --git a/src/sage/rings/padics/CA_template_header.pxi b/src/sage/rings/padics/CA_template_header.pxi index d15a055cb4d..87194617daa 100644 --- a/src/sage/rings/padics/CA_template_header.pxi +++ b/src/sage/rings/padics/CA_template_header.pxi @@ -31,7 +31,7 @@ cdef class CAElement(pAdicTemplateElement): cdef celement value cdef long absprec - cdef CAElement _new_c(self) + cdef CAElement _new_c(self) noexcept cdef class pAdicCoercion_ZZ_CA(RingHomomorphism): cdef CAElement _zero diff --git a/src/sage/rings/padics/CR_template.pxi b/src/sage/rings/padics/CR_template.pxi index 57ab352a66f..7c74f5ecc61 100644 --- a/src/sage/rings/padics/CR_template.pxi +++ b/src/sage/rings/padics/CR_template.pxi @@ -42,7 +42,7 @@ from sage.categories.sets_cat import Sets from sage.categories.sets_with_partial_maps import SetsWithPartialMaps from sage.categories.homset import Hom -cdef inline bint exactzero(long ordp): +cdef inline bint exactzero(long ordp) noexcept: """ Whether a given valuation represents an exact zero. """ @@ -176,7 +176,7 @@ cdef class CRElement(pAdicTemplateElement): self.ordp = absprec self.relprec = 0 - cdef CRElement _new_c(self): + cdef CRElement _new_c(self) noexcept: """ Creates a new element with the same basic info. @@ -203,7 +203,7 @@ cdef class CRElement(pAdicTemplateElement): cconstruct(ans.unit, ans.prime_pow) return ans - cdef pAdicTemplateElement _new_with_value(self, celement value, long absprec): + cdef pAdicTemplateElement _new_with_value(self, celement value, long absprec) noexcept: """ Creates a new element with a given value and absolute precision. @@ -305,7 +305,7 @@ cdef class CRElement(pAdicTemplateElement): """ return unpickle_cre_v2, (self.__class__, self.parent(), cpickle(self.unit, self.prime_pow), self.ordp, self.relprec) - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ Return the additive inverse of this element. @@ -329,7 +329,7 @@ cdef class CRElement(pAdicTemplateElement): creduce(ans.unit, ans.unit, ans.relprec, ans.prime_pow) return ans - cpdef _add_(self, _right): + cpdef _add_(self, _right) noexcept: """ Return the sum of this element and ``_right``. @@ -373,7 +373,7 @@ cdef class CRElement(pAdicTemplateElement): creduce(ans.unit, ans.unit, ans.relprec, ans.prime_pow) return ans - cpdef _sub_(self, _right): + cpdef _sub_(self, _right) noexcept: """ Return the difference of this element and ``_right``. @@ -447,7 +447,7 @@ cdef class CRElement(pAdicTemplateElement): cinvert(ans.unit, self.unit, ans.relprec, ans.prime_pow) return ans - cpdef _mul_(self, _right): + cpdef _mul_(self, _right) noexcept: r""" Return the product of this element and ``_right``. @@ -478,7 +478,7 @@ cdef class CRElement(pAdicTemplateElement): check_ordp(ans.ordp) return ans - cpdef _div_(self, _right): + cpdef _div_(self, _right) noexcept: """ Return the quotient of this element and ``right``. @@ -731,7 +731,7 @@ cdef class CRElement(pAdicTemplateElement): ans.ordp = 0 return ans - cdef pAdicTemplateElement _lshift_c(self, long shift): + cdef pAdicTemplateElement _lshift_c(self, long shift) noexcept: r""" Multiplies by `\pi^{\mbox{shift}}`. @@ -762,7 +762,7 @@ cdef class CRElement(pAdicTemplateElement): ccopy(ans.unit, self.unit, ans.prime_pow) return ans - cdef pAdicTemplateElement _rshift_c(self, long shift): + cdef pAdicTemplateElement _rshift_c(self, long shift) noexcept: r""" Divides by ``\pi^{\mbox{shift}}``. @@ -1192,7 +1192,7 @@ cdef class CRElement(pAdicTemplateElement): return 0 return ccmp(self.unit, right.unit, rprec, rprec < self.relprec, rprec < right.relprec, self.prime_pow) - cdef pAdicTemplateElement lift_to_precision_c(self, long absprec): + cdef pAdicTemplateElement lift_to_precision_c(self, long absprec) noexcept: """ Lifts this element to another with precision at least ``absprec``. @@ -1415,7 +1415,7 @@ cdef class CRElement(pAdicTemplateElement): mpz_set_si(ans.value, self.relprec) return ans - cpdef pAdicTemplateElement unit_part(self): + cpdef pAdicTemplateElement unit_part(self) noexcept: r""" Return `u`, where this element is `\pi^v u`. @@ -1459,7 +1459,7 @@ cdef class CRElement(pAdicTemplateElement): ccopy(ans.unit, (self).unit, ans.prime_pow) return ans - cdef long valuation_c(self): + cdef long valuation_c(self) noexcept: """ Return the valuation of this element. @@ -1478,7 +1478,7 @@ cdef class CRElement(pAdicTemplateElement): """ return self.ordp - cpdef val_unit(self, p=None): + cpdef val_unit(self, p=None) noexcept: """ Return a pair ``(self.valuation(), self.unit_part())``. @@ -1568,7 +1568,7 @@ cdef class pAdicCoercion_ZZ_CR(RingHomomorphism): self._zero = R.element_class(R, 0) self._section = pAdicConvert_CR_ZZ(R) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1594,7 +1594,7 @@ cdef class pAdicCoercion_ZZ_CR(RingHomomorphism): _slots['_section'] = self.section() # use method since it copies coercion-internal sections. return _slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1620,7 +1620,7 @@ cdef class pAdicCoercion_ZZ_CR(RingHomomorphism): self._section = _slots['_section'] RingHomomorphism._update_slots(self, _slots) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Evaluation. @@ -1639,7 +1639,7 @@ cdef class pAdicCoercion_ZZ_CR(RingHomomorphism): ans.ordp = cconv_mpz_t(ans.unit, (x).value, ans.relprec, False, ans.prime_pow) return ans - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ This function is used when some precision cap is passed in (relative or absolute or both), or an empty element is @@ -1735,7 +1735,7 @@ cdef class pAdicConvert_CR_ZZ(RingMap): else: RingMap.__init__(self, Hom(R, ZZ, Sets())) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: """ Evaluation. @@ -1786,7 +1786,7 @@ cdef class pAdicCoercion_QQ_CR(RingHomomorphism): self._zero = R.element_class(R, 0) self._section = pAdicConvert_CR_QQ(R) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1812,7 +1812,7 @@ cdef class pAdicCoercion_QQ_CR(RingHomomorphism): _slots['_section'] = self.section() # use method since it copies coercion-internal sections. return _slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1838,7 +1838,7 @@ cdef class pAdicCoercion_QQ_CR(RingHomomorphism): self._section = _slots['_section'] RingHomomorphism._update_slots(self, _slots) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Evaluation. @@ -1859,7 +1859,7 @@ cdef class pAdicCoercion_QQ_CR(RingHomomorphism): ans.ordp = cconv_mpq_t(ans.unit, (x).value, ans.relprec, False, self._zero.prime_pow) return ans - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ This function is used when some precision cap is passed in (relative or absolute or both), or an empty element is @@ -1953,7 +1953,7 @@ cdef class pAdicConvert_CR_QQ(RingMap): else: RingMap.__init__(self, Hom(R, QQ, Sets())) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: """ Evaluation. @@ -2000,7 +2000,7 @@ cdef class pAdicConvert_QQ_CR(Morphism): self._zero = R.element_class(R, 0) self._section = pAdicConvert_CR_QQ(R) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -2020,7 +2020,7 @@ cdef class pAdicConvert_QQ_CR(Morphism): _slots['_section'] = self.section() # use method since it copies coercion-internal sections. return _slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -2039,7 +2039,7 @@ cdef class pAdicConvert_QQ_CR(Morphism): self._section = _slots['_section'] Morphism._update_slots(self, _slots) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Evaluation. @@ -2060,7 +2060,7 @@ cdef class pAdicConvert_QQ_CR(Morphism): raise ValueError("p divides the denominator") return ans - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ This function is used when some precision cap is passed in (relative or absolute or both), or an empty element is @@ -2162,7 +2162,7 @@ cdef class pAdicCoercion_CR_frac_field(RingHomomorphism): self._zero = K(0) self._section = pAdicConvert_CR_frac_field(K, R) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: """ Evaluation. @@ -2187,7 +2187,7 @@ cdef class pAdicCoercion_CR_frac_field(RingHomomorphism): ans.unit._coeffs = [K(c) for c in ans.unit._coeffs] return ans - cpdef Element _call_with_args(self, _x, args=(), kwds={}): + cpdef Element _call_with_args(self, _x, args=(), kwds={}) noexcept: """ This function is used when some precision cap is passed in (relative or absolute or both). @@ -2267,7 +2267,7 @@ cdef class pAdicCoercion_CR_frac_field(RingHomomorphism): self._section = copy.copy(self._section) return self._section - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -2296,7 +2296,7 @@ cdef class pAdicCoercion_CR_frac_field(RingHomomorphism): _slots['_section'] = self.section() # use method since it copies coercion-internal sections. return _slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -2382,7 +2382,7 @@ cdef class pAdicConvert_CR_frac_field(Morphism): Morphism.__init__(self, Hom(K, R, SetsWithPartialMaps())) self._zero = R(0) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: """ Evaluation. @@ -2407,7 +2407,7 @@ cdef class pAdicConvert_CR_frac_field(Morphism): ans.unit._coeffs = [K(c) for c in ans.unit._coeffs] return ans - cpdef Element _call_with_args(self, _x, args=(), kwds={}): + cpdef Element _call_with_args(self, _x, args=(), kwds={}) noexcept: """ This function is used when some precision cap is passed in (relative or absolute or both). @@ -2466,7 +2466,7 @@ cdef class pAdicConvert_CR_frac_field(Morphism): ans.unit._coeffs = [K(c) for c in ans.unit._coeffs] return ans - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -2494,7 +2494,7 @@ cdef class pAdicConvert_CR_frac_field(Morphism): _slots['_zero'] = self._zero return _slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. diff --git a/src/sage/rings/padics/CR_template_header.pxi b/src/sage/rings/padics/CR_template_header.pxi index 54c482f7ff2..b969463bc72 100644 --- a/src/sage/rings/padics/CR_template_header.pxi +++ b/src/sage/rings/padics/CR_template_header.pxi @@ -32,9 +32,9 @@ cdef class CRElement(pAdicTemplateElement): cdef long ordp cdef long relprec - cdef CRElement _new_c(self) + cdef CRElement _new_c(self) noexcept cdef int _normalize(self) except -1 - cpdef val_unit(self, p=*) + cpdef val_unit(self, p=*) noexcept cdef class pAdicCoercion_ZZ_CR(RingHomomorphism): cdef CRElement _zero diff --git a/src/sage/rings/padics/FM_template.pxi b/src/sage/rings/padics/FM_template.pxi index e319255a85c..3e4a9fdc4cb 100644 --- a/src/sage/rings/padics/FM_template.pxi +++ b/src/sage/rings/padics/FM_template.pxi @@ -89,7 +89,7 @@ cdef class FMElement(pAdicTemplateElement): else: cconv(self.value, x, self.prime_pow.ram_prec_cap, 0, self.prime_pow) - cdef FMElement _new_c(self): + cdef FMElement _new_c(self) noexcept: """ Creates a new element with the same basic info. @@ -108,7 +108,7 @@ cdef class FMElement(pAdicTemplateElement): cconstruct(ans.value, ans.prime_pow) return ans - cdef pAdicTemplateElement _new_with_value(self, celement value, long absprec): + cdef pAdicTemplateElement _new_with_value(self, celement value, long absprec) noexcept: """ Creates a new element with a given value and absolute precision. @@ -179,7 +179,7 @@ cdef class FMElement(pAdicTemplateElement): """ return unpickle_fme_v2, (self.__class__, self.parent(), cpickle(self.value, self.prime_pow)) - cpdef _neg_(self): + cpdef _neg_(self) noexcept: r""" Return the additive inverse of this element. @@ -194,7 +194,7 @@ cdef class FMElement(pAdicTemplateElement): creduce_small(ans.value, ans.value, ans.prime_pow.ram_prec_cap, ans.prime_pow) return ans - cpdef _add_(self, _right): + cpdef _add_(self, _right) noexcept: r""" Return the sum of this element and ``_right``. @@ -214,7 +214,7 @@ cdef class FMElement(pAdicTemplateElement): creduce_small(ans.value, ans.value, ans.prime_pow.ram_prec_cap, ans.prime_pow) return ans - cpdef _sub_(self, _right): + cpdef _sub_(self, _right) noexcept: r""" Return the difference of this element and ``_right``. @@ -259,7 +259,7 @@ cdef class FMElement(pAdicTemplateElement): cinvert(ans.value, self.value, ans.prime_pow.ram_prec_cap, ans.prime_pow) return ans - cpdef _mul_(self, _right): + cpdef _mul_(self, _right) noexcept: r""" Return the product of this element and ``_right``. @@ -277,7 +277,7 @@ cdef class FMElement(pAdicTemplateElement): creduce(ans.value, ans.value, ans.prime_pow.ram_prec_cap, ans.prime_pow) return ans - cpdef _div_(self, _right): + cpdef _div_(self, _right) noexcept: r""" Return the quotient of this element and ``right``. ``right`` must have valuation zero. @@ -379,7 +379,7 @@ cdef class FMElement(pAdicTemplateElement): cpow(ans.value, self.value, right.value, self.prime_pow.ram_prec_cap, self.prime_pow) return ans - cdef pAdicTemplateElement _lshift_c(self, long shift): + cdef pAdicTemplateElement _lshift_c(self, long shift) noexcept: r""" Multiplies self by `\pi^{shift}`. @@ -426,7 +426,7 @@ cdef class FMElement(pAdicTemplateElement): cshift_notrunc(ans.value, self.value, shift, ans.prime_pow.ram_prec_cap, ans.prime_pow, True) return ans - cdef pAdicTemplateElement _rshift_c(self, long shift): + cdef pAdicTemplateElement _rshift_c(self, long shift) noexcept: r""" Divides by `\pi^{shift}`, and truncates. @@ -647,7 +647,7 @@ cdef class FMElement(pAdicTemplateElement): cdef FMElement right = _right return ccmp(self.value, right.value, self.prime_pow.ram_prec_cap, False, False, self.prime_pow) - cdef pAdicTemplateElement lift_to_precision_c(self, long absprec): + cdef pAdicTemplateElement lift_to_precision_c(self, long absprec) noexcept: """ Lifts this element to another with precision at least absprec. @@ -777,7 +777,7 @@ cdef class FMElement(pAdicTemplateElement): mpz_set_si(ans.value, self.prime_pow.ram_prec_cap - self.valuation_c()) return ans - cpdef pAdicTemplateElement unit_part(FMElement self): + cpdef pAdicTemplateElement unit_part(FMElement self) noexcept: r""" Return the unit part of ``self``. @@ -802,7 +802,7 @@ cdef class FMElement(pAdicTemplateElement): cremove(ans.value, (self).value, (self).prime_pow.ram_prec_cap, (self).prime_pow) return ans - cdef long valuation_c(self): + cdef long valuation_c(self) noexcept: """ Return the valuation of this element. @@ -833,7 +833,7 @@ cdef class FMElement(pAdicTemplateElement): # for backward compatibility return cvaluation(self.value, self.prime_pow.ram_prec_cap, self.prime_pow) - cpdef val_unit(self): + cpdef val_unit(self) noexcept: """ Return a 2-tuple, the first element set to the valuation of ``self``, and the second to the unit part of ``self``. @@ -895,7 +895,7 @@ cdef class pAdicCoercion_ZZ_FM(RingHomomorphism): self._zero = R.element_class(R, 0) self._section = pAdicConvert_FM_ZZ(R) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -915,7 +915,7 @@ cdef class pAdicCoercion_ZZ_FM(RingHomomorphism): _slots['_section'] = self.section() # use method since it copies coercion-internal sections. return _slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -934,7 +934,7 @@ cdef class pAdicCoercion_ZZ_FM(RingHomomorphism): self._section = _slots['_section'] RingHomomorphism._update_slots(self, _slots) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Evaluation. @@ -952,7 +952,7 @@ cdef class pAdicCoercion_ZZ_FM(RingHomomorphism): cconv_mpz_t(ans.value, (x).value, ans.prime_pow.ram_prec_cap, True, ans.prime_pow) return ans - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ This function is used when some precision cap is passed in (relative or absolute or both). @@ -1038,7 +1038,7 @@ cdef class pAdicConvert_FM_ZZ(RingMap): else: RingMap.__init__(self, Hom(R, ZZ, Sets())) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: """ Evaluation. @@ -1079,7 +1079,7 @@ cdef class pAdicConvert_QQ_FM(Morphism): Morphism.__init__(self, Hom(QQ, R, SetsWithPartialMaps())) self._zero = R.element_class(R, 0) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1098,7 +1098,7 @@ cdef class pAdicConvert_QQ_FM(Morphism): _slots['_zero'] = self._zero return _slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1116,7 +1116,7 @@ cdef class pAdicConvert_QQ_FM(Morphism): self._zero = _slots['_zero'] Morphism._update_slots(self, _slots) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Evaluation. @@ -1134,7 +1134,7 @@ cdef class pAdicConvert_QQ_FM(Morphism): cconv_mpq_t(ans.value, (x).value, ans.prime_pow.ram_prec_cap, True, ans.prime_pow) return ans - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ This function is used when some precision cap is passed in (relative or absolute or both). @@ -1206,7 +1206,7 @@ cdef class pAdicCoercion_FM_frac_field(RingHomomorphism): self._zero = K(0) self._section = pAdicConvert_FM_frac_field(K, R) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: """ Evaluation. @@ -1229,7 +1229,7 @@ cdef class pAdicCoercion_FM_frac_field(RingHomomorphism): ans.unit._coeffs = [K(c) for c in ans.unit._coeffs] return ans - cpdef Element _call_with_args(self, _x, args=(), kwds={}): + cpdef Element _call_with_args(self, _x, args=(), kwds={}) noexcept: """ This function is used when some precision cap is passed in (relative or absolute or both). @@ -1298,7 +1298,7 @@ cdef class pAdicCoercion_FM_frac_field(RingHomomorphism): self._section = copy.copy(self._section) return self._section - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1326,7 +1326,7 @@ cdef class pAdicCoercion_FM_frac_field(RingHomomorphism): _slots['_section'] = self.section() # use method since it copies coercion-internal sections. return _slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1412,7 +1412,7 @@ cdef class pAdicConvert_FM_frac_field(Morphism): Morphism.__init__(self, Hom(K, R, SetsWithPartialMaps())) self._zero = R(0) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: """ Evaluation. @@ -1437,7 +1437,7 @@ cdef class pAdicConvert_FM_frac_field(Morphism): ans.value._coeffs = [R(c) for c in ans.value._coeffs] return ans - cpdef Element _call_with_args(self, _x, args=(), kwds={}): + cpdef Element _call_with_args(self, _x, args=(), kwds={}) noexcept: """ This function is used when some precision cap is passed in (relative or absolute or both). @@ -1485,7 +1485,7 @@ cdef class pAdicConvert_FM_frac_field(Morphism): ans.value._coeffs = [R(c) for c in ans.value._coeffs] return ans - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1513,7 +1513,7 @@ cdef class pAdicConvert_FM_frac_field(Morphism): _slots['_zero'] = self._zero return _slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. diff --git a/src/sage/rings/padics/FM_template_header.pxi b/src/sage/rings/padics/FM_template_header.pxi index bd651167622..d9ecc7d0715 100644 --- a/src/sage/rings/padics/FM_template_header.pxi +++ b/src/sage/rings/padics/FM_template_header.pxi @@ -31,7 +31,7 @@ cdef class FMElement(pAdicTemplateElement): cdef celement value cdef long absprec - cdef FMElement _new_c(self) + cdef FMElement _new_c(self) noexcept cdef class pAdicCoercion_ZZ_FM(RingHomomorphism): cdef FMElement _zero diff --git a/src/sage/rings/padics/FP_template.pxi b/src/sage/rings/padics/FP_template.pxi index 695e66e2712..e4950778756 100644 --- a/src/sage/rings/padics/FP_template.pxi +++ b/src/sage/rings/padics/FP_template.pxi @@ -45,7 +45,7 @@ from sage.categories.sets_cat import Sets from sage.categories.sets_with_partial_maps import SetsWithPartialMaps from sage.categories.homset import Hom -cdef inline bint overunderflow(long* ordp, celement unit, PowComputer_ prime_pow): +cdef inline bint overunderflow(long* ordp, celement unit, PowComputer_ prime_pow) noexcept: """ Check for over and underflow. If detected, sets ordp and unit appropriately, and returns True. If not, returns False. @@ -60,7 +60,7 @@ cdef inline bint overunderflow(long* ordp, celement unit, PowComputer_ prime_pow return False return True -cdef inline bint overunderflow_mpz(long* ordp, mpz_t ordp_mpz, celement unit, PowComputer_ prime_pow): +cdef inline bint overunderflow_mpz(long* ordp, mpz_t ordp_mpz, celement unit, PowComputer_ prime_pow) noexcept: """ Check for over and underflow with an mpz_t ordp. If detected, sets ordp and unit appropriately, and returns True. If not, returns False. @@ -75,13 +75,13 @@ cdef inline bint overunderflow_mpz(long* ordp, mpz_t ordp_mpz, celement unit, Po return True return False -cdef inline bint very_pos_val(long ordp): +cdef inline bint very_pos_val(long ordp) noexcept: return ordp >= maxordp -cdef inline bint very_neg_val(long ordp): +cdef inline bint very_neg_val(long ordp) noexcept: return ordp <= minusmaxordp -cdef inline bint huge_val(long ordp): +cdef inline bint huge_val(long ordp) noexcept: return very_pos_val(ordp) or very_neg_val(ordp) cdef class FPElement(pAdicTemplateElement): @@ -171,7 +171,7 @@ cdef class FPElement(pAdicTemplateElement): csetone(self.unit, self.prime_pow) self.ordp = minusmaxordp - cdef FPElement _new_c(self): + cdef FPElement _new_c(self) noexcept: """ Creates a new element with the same basic info. @@ -196,7 +196,7 @@ cdef class FPElement(pAdicTemplateElement): cconstruct(ans.unit, ans.prime_pow) return ans - cdef pAdicTemplateElement _new_with_value(self, celement value, long absprec): + cdef pAdicTemplateElement _new_with_value(self, celement value, long absprec) noexcept: """ Creates a new element with a given value and absolute precision. @@ -312,7 +312,7 @@ cdef class FPElement(pAdicTemplateElement): # """ # return (self)._richcmp(right, op) - cpdef _neg_(self): + cpdef _neg_(self) noexcept: r""" Return the additive inverse of this element. @@ -331,7 +331,7 @@ cdef class FPElement(pAdicTemplateElement): creduce_small(ans.unit, ans.unit, ans.prime_pow.ram_prec_cap, ans.prime_pow) return ans - cpdef _add_(self, _right): + cpdef _add_(self, _right) noexcept: r""" Return the sum of this element and ``_right``. @@ -375,7 +375,7 @@ cdef class FPElement(pAdicTemplateElement): creduce(ans.unit, ans.unit, ans.prime_pow.ram_prec_cap, ans.prime_pow) return ans - cpdef _sub_(self, _right): + cpdef _sub_(self, _right) noexcept: r""" Return the difference of this element and ``_right``. @@ -454,7 +454,7 @@ cdef class FPElement(pAdicTemplateElement): cinvert(ans.unit, self.unit, ans.prime_pow.ram_prec_cap, ans.prime_pow) return ans - cpdef _mul_(self, _right): + cpdef _mul_(self, _right) noexcept: r""" Return the product of this element and ``_right``. @@ -487,7 +487,7 @@ cdef class FPElement(pAdicTemplateElement): creduce(ans.unit, ans.unit, ans.prime_pow.ram_prec_cap, ans.prime_pow) return ans - cpdef _div_(self, _right): + cpdef _div_(self, _right) noexcept: r""" Return the quotient of this element and ``right``. @@ -663,7 +663,7 @@ cdef class FPElement(pAdicTemplateElement): ans.ordp = 0 return ans - cdef pAdicTemplateElement _lshift_c(self, long shift): + cdef pAdicTemplateElement _lshift_c(self, long shift) noexcept: r""" Multiplies self by `\pi^{shift}`. @@ -716,7 +716,7 @@ cdef class FPElement(pAdicTemplateElement): ccopy(ans.unit, self.unit, ans.prime_pow) return ans - cdef pAdicTemplateElement _rshift_c(self, long shift): + cdef pAdicTemplateElement _rshift_c(self, long shift) noexcept: r""" Divides by `\pi^{shift}`. @@ -985,7 +985,7 @@ cdef class FPElement(pAdicTemplateElement): cdef FPElement right = _right return ccmp(self.unit, right.unit, self.prime_pow.ram_prec_cap, False, False, self.prime_pow) - cdef pAdicTemplateElement lift_to_precision_c(self, long absprec): + cdef pAdicTemplateElement lift_to_precision_c(self, long absprec) noexcept: """ Lift this element to another with precision at least absprec. @@ -1134,7 +1134,7 @@ cdef class FPElement(pAdicTemplateElement): mpz_set_si(ans.value, self.prime_pow.ram_prec_cap) return ans - cpdef pAdicTemplateElement unit_part(FPElement self): + cpdef pAdicTemplateElement unit_part(FPElement self) noexcept: r""" Return the unit part of this element. @@ -1164,7 +1164,7 @@ cdef class FPElement(pAdicTemplateElement): ccopy(ans.unit, (self).unit, ans.prime_pow) return ans - cdef long valuation_c(self): + cdef long valuation_c(self) noexcept: """ Return the valuation of this element. @@ -1201,7 +1201,7 @@ cdef class FPElement(pAdicTemplateElement): """ return self.ordp - cpdef val_unit(self, p=None): + cpdef val_unit(self, p=None) noexcept: """ Return a 2-tuple, the first element set to the valuation of this element, and the second to the unit part. @@ -1275,7 +1275,7 @@ cdef class pAdicCoercion_ZZ_FP(RingHomomorphism): self._zero = R.element_class(R, 0) self._section = pAdicConvert_FP_ZZ(R) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1295,7 +1295,7 @@ cdef class pAdicCoercion_ZZ_FP(RingHomomorphism): _slots['_section'] = self.section() # use method since it copies coercion-internal sections. return _slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1314,7 +1314,7 @@ cdef class pAdicCoercion_ZZ_FP(RingHomomorphism): self._section = _slots['_section'] RingHomomorphism._update_slots(self, _slots) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Evaluation. @@ -1332,7 +1332,7 @@ cdef class pAdicCoercion_ZZ_FP(RingHomomorphism): ans.ordp = cconv_mpz_t(ans.unit, (x).value, ans.prime_pow.ram_prec_cap, False, ans.prime_pow) return ans - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ This function is used when some precision cap is passed in (relative or absolute or both). @@ -1426,7 +1426,7 @@ cdef class pAdicConvert_FP_ZZ(RingMap): else: RingMap.__init__(self, Hom(R, ZZ, Sets())) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: """ Evaluation. @@ -1487,7 +1487,7 @@ cdef class pAdicCoercion_QQ_FP(RingHomomorphism): self._zero = R.element_class(R, 0) self._section = pAdicConvert_FP_QQ(R) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1513,7 +1513,7 @@ cdef class pAdicCoercion_QQ_FP(RingHomomorphism): _slots['_section'] = self.section() # use method since it copies coercion-internal sections. return _slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1538,7 +1538,7 @@ cdef class pAdicCoercion_QQ_FP(RingHomomorphism): self._section = _slots['_section'] RingHomomorphism._update_slots(self, _slots) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Evaluation. @@ -1560,7 +1560,7 @@ cdef class pAdicCoercion_QQ_FP(RingHomomorphism): ans.ordp = cconv_mpq_t(ans.unit, (x).value, ans.prime_pow.ram_prec_cap, False, self._zero.prime_pow) return ans - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ This function is used when some precision cap is passed in (relative or absolute or both). @@ -1643,7 +1643,7 @@ cdef class pAdicConvert_FP_QQ(RingMap): """ RingMap.__init__(self, Hom(R, QQ, SetsWithPartialMaps())) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: """ Evaluation. @@ -1690,7 +1690,7 @@ cdef class pAdicConvert_QQ_FP(Morphism): Morphism.__init__(self, Hom(QQ, R, SetsWithPartialMaps())) self._zero = R.element_class(R, 0) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -1709,7 +1709,7 @@ cdef class pAdicConvert_QQ_FP(Morphism): _slots['_zero'] = self._zero return _slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -1727,7 +1727,7 @@ cdef class pAdicConvert_QQ_FP(Morphism): self._zero = _slots['_zero'] Morphism._update_slots(self, _slots) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Evaluation. @@ -1747,7 +1747,7 @@ cdef class pAdicConvert_QQ_FP(Morphism): raise ValueError("p divides the denominator") return ans - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ This function is used when some precision cap is passed in (relative or absolute or both). @@ -1827,7 +1827,7 @@ cdef class pAdicCoercion_FP_frac_field(RingHomomorphism): self._zero = K(0) self._section = pAdicConvert_FP_frac_field(K, R) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: r""" Evaluation. @@ -1851,7 +1851,7 @@ cdef class pAdicCoercion_FP_frac_field(RingHomomorphism): ans.unit._coeffs = [K(c) for c in ans.unit._coeffs] return ans - cpdef Element _call_with_args(self, _x, args=(), kwds={}): + cpdef Element _call_with_args(self, _x, args=(), kwds={}) noexcept: r""" This function is used when some precision cap is passed in (relative or absolute or both). @@ -1920,7 +1920,7 @@ cdef class pAdicCoercion_FP_frac_field(RingHomomorphism): """ return self._section - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: r""" Helper for copying and pickling. @@ -1948,7 +1948,7 @@ cdef class pAdicCoercion_FP_frac_field(RingHomomorphism): _slots['_section'] = self.section() # use method since it copies coercion-internal sections. return _slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: r""" Helper for copying and pickling. @@ -2003,7 +2003,7 @@ cdef class pAdicConvert_FP_frac_field(Morphism): Morphism.__init__(self, Hom(K, R, SetsWithPartialMaps())) self._zero = R(0) - cpdef Element _call_(self, _x): + cpdef Element _call_(self, _x) noexcept: r""" Evaluation. @@ -2027,7 +2027,7 @@ cdef class pAdicConvert_FP_frac_field(Morphism): ans.unit._coeffs = [K(c) for c in ans.unit._coeffs] return ans - cpdef Element _call_with_args(self, _x, args=(), kwds={}): + cpdef Element _call_with_args(self, _x, args=(), kwds={}) noexcept: r""" This function is used when some precision cap is passed in (relative or absolute or both). @@ -2083,7 +2083,7 @@ cdef class pAdicConvert_FP_frac_field(Morphism): ans.unit._coeffs = [K(c) for c in ans.unit._coeffs] return ans - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: r""" Helper for copying and pickling. @@ -2111,7 +2111,7 @@ cdef class pAdicConvert_FP_frac_field(Morphism): _slots['_zero'] = self._zero return _slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: r""" Helper for copying and pickling. diff --git a/src/sage/rings/padics/FP_template_header.pxi b/src/sage/rings/padics/FP_template_header.pxi index fde598e05fd..108d8042850 100644 --- a/src/sage/rings/padics/FP_template_header.pxi +++ b/src/sage/rings/padics/FP_template_header.pxi @@ -31,10 +31,10 @@ cdef class FPElement(pAdicTemplateElement): cdef celement unit cdef long ordp - cdef FPElement _new_c(self) + cdef FPElement _new_c(self) noexcept cdef int _normalize(self) except -1 cdef int _set_infinity(self) except -1 - cpdef val_unit(self, p=*) + cpdef val_unit(self, p=*) noexcept cdef class pAdicCoercion_ZZ_FP(RingHomomorphism): cdef FPElement _zero diff --git a/src/sage/rings/padics/local_generic_element.pyx b/src/sage/rings/padics/local_generic_element.pyx index 0db91750eca..6177f74c047 100644 --- a/src/sage/rings/padics/local_generic_element.pyx +++ b/src/sage/rings/padics/local_generic_element.pyx @@ -32,7 +32,7 @@ cdef class LocalGenericElement(CommutativeRingElement): #cpdef _add_(self, right): # raise NotImplementedError - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: r""" Returns the quotient of ``self`` by ``right``. @@ -433,7 +433,7 @@ cdef class LocalGenericElement(CommutativeRingElement): #def __pow__(self, right): # raise NotImplementedError - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: r""" Returns the difference between ``self`` and ``right``. diff --git a/src/sage/rings/padics/morphism.pxd b/src/sage/rings/padics/morphism.pxd index b6afedd2377..a904ba14ca0 100644 --- a/src/sage/rings/padics/morphism.pxd +++ b/src/sage/rings/padics/morphism.pxd @@ -7,4 +7,4 @@ cdef class FrobeniusEndomorphism_padics(RingHomomorphism): cdef long _power cdef long _order - cpdef Element _call_(self, x) + cpdef Element _call_(self, x) noexcept diff --git a/src/sage/rings/padics/morphism.pyx b/src/sage/rings/padics/morphism.pyx index b29fc204b43..87aa8fef1a7 100644 --- a/src/sage/rings/padics/morphism.pyx +++ b/src/sage/rings/padics/morphism.pyx @@ -85,7 +85,7 @@ cdef class FrobeniusEndomorphism_padics(RingHomomorphism): self._order = self._degree / domain.absolute_f().gcd(self._power) RingHomomorphism.__init__(self, Hom(domain, domain)) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -104,7 +104,7 @@ cdef class FrobeniusEndomorphism_padics(RingHomomorphism): slots['_order'] = self._order return slots - cdef _update_slots(self, dict slots): + cdef _update_slots(self, dict slots) noexcept: """ Helper for copying and pickling. @@ -165,7 +165,7 @@ cdef class FrobeniusEndomorphism_padics(RingHomomorphism): s = "Frob^%s" % self._power return s - cpdef Element _call_ (self, x): + cpdef Element _call_ (self, x) noexcept: """ TESTS:: @@ -329,7 +329,7 @@ cdef class FrobeniusEndomorphism_padics(RingHomomorphism): codomain = self.codomain() return hash((domain, codomain, ('Frob', self._power))) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Compare ``left`` and ``right`` diff --git a/src/sage/rings/padics/padic_ZZ_pX_CA_element.pxd b/src/sage/rings/padics/padic_ZZ_pX_CA_element.pxd index 7afe94b1bf3..2bcb237be77 100644 --- a/src/sage/rings/padics/padic_ZZ_pX_CA_element.pxd +++ b/src/sage/rings/padics/padic_ZZ_pX_CA_element.pxd @@ -13,12 +13,12 @@ cdef class pAdicZZpXCAElement(pAdicZZpXElement): cdef int _set(self, ZZ_pX_c* value, long absprec) except -1 cdef int _set_from_mpq_part2(self, mpq_t x) except -1 - cpdef pAdicZZpXCRElement to_fraction_field(self) - cdef pAdicZZpXCAElement _new_c(self, long absprec) - cdef pAdicZZpXCAElement _lshift_c(self, long n) - cdef pAdicZZpXCAElement _rshift_c(self, long n) - cpdef pAdicZZpXCAElement unit_part(self) - cpdef _ntl_rep_abs(self) - cpdef ntl_ZZ_pX _ntl_rep(self) + cpdef pAdicZZpXCRElement to_fraction_field(self) noexcept + cdef pAdicZZpXCAElement _new_c(self, long absprec) noexcept + cdef pAdicZZpXCAElement _lshift_c(self, long n) noexcept + cdef pAdicZZpXCAElement _rshift_c(self, long n) noexcept + cpdef pAdicZZpXCAElement unit_part(self) noexcept + cpdef _ntl_rep_abs(self) noexcept + cpdef ntl_ZZ_pX _ntl_rep(self) noexcept - cpdef pAdicZZpXCAElement lift_to_precision(self, absprec=*) + cpdef pAdicZZpXCAElement lift_to_precision(self, absprec=*) noexcept diff --git a/src/sage/rings/padics/padic_ZZ_pX_CA_element.pyx b/src/sage/rings/padics/padic_ZZ_pX_CA_element.pyx index 0f5270a9980..b13f79ea6f2 100644 --- a/src/sage/rings/padics/padic_ZZ_pX_CA_element.pyx +++ b/src/sage/rings/padics/padic_ZZ_pX_CA_element.pyx @@ -836,7 +836,7 @@ cdef class pAdicZZpXCAElement(pAdicZZpXElement): else: self._set_prec_abs(ordp + relprec) - cdef pAdicZZpXCAElement _new_c(self, long absprec): + cdef pAdicZZpXCAElement _new_c(self, long absprec) noexcept: """ Returns a new element with the same parent as ``self`` and absolute precision ``absprec``. @@ -934,7 +934,7 @@ cdef class pAdicZZpXCAElement(pAdicZZpXElement): """ return ~self.to_fraction_field() - cpdef pAdicZZpXCRElement to_fraction_field(self): + cpdef pAdicZZpXCRElement to_fraction_field(self) noexcept: """ Returns ``self`` cast into the fraction field of ``self.parent()``. @@ -961,7 +961,7 @@ cdef class pAdicZZpXCAElement(pAdicZZpXElement): ans.unit = self.value return ans - cdef pAdicZZpXCAElement _lshift_c(self, long n): + cdef pAdicZZpXCAElement _lshift_c(self, long n) noexcept: """ Multiplies ``self`` by the uniformizer raised to the power ``n``. If ``n`` is negative, right shifts by ``-n``. @@ -1012,7 +1012,7 @@ cdef class pAdicZZpXCAElement(pAdicZZpXElement): return ans return self._rshift_c(-mpz_get_si((shift).value)) - cdef pAdicZZpXCAElement _rshift_c(self, long n): + cdef pAdicZZpXCAElement _rshift_c(self, long n) noexcept: """ Divides ``self`` by the uniformizer raised to the power ``n``. If parent is not a field, throws away the non-positive part of @@ -1110,7 +1110,7 @@ cdef class pAdicZZpXCAElement(pAdicZZpXElement): return ans return self._rshift_c(mpz_get_si((shift).value)) - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ Returns ``-self``. @@ -1376,7 +1376,7 @@ cdef class pAdicZZpXCAElement(pAdicZZpXElement): sig_off() return ans - cpdef _add_(self, _right): + cpdef _add_(self, _right) noexcept: """ Computes the sum of ``self`` and ``right``. @@ -1414,7 +1414,7 @@ cdef class pAdicZZpXCAElement(pAdicZZpXElement): ZZ_pX_add(ans.value, tmpP, right.value) return ans - cpdef _sub_(self, _right): + cpdef _sub_(self, _right) noexcept: """ Returns the difference of ``self`` and ``right``. @@ -1455,7 +1455,7 @@ cdef class pAdicZZpXCAElement(pAdicZZpXElement): ZZ_pX_sub(ans.value, tmpP, right.value) return ans - cpdef _mul_(self, _right): + cpdef _mul_(self, _right) noexcept: """ Returns the product of ``self`` and ``right``. @@ -1508,7 +1508,7 @@ cdef class pAdicZZpXCAElement(pAdicZZpXElement): ZZ_pX_MulMod_pre(ans.value, self_adapted, right_adapted, self.prime_pow.get_modulus_capdiv(ans_absprec)[0]) return ans - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Returns the quotient of ``self`` by ``right``. @@ -1640,7 +1640,7 @@ cdef class pAdicZZpXCAElement(pAdicZZpXElement): ans = (self.valuation_c() >= aprec) return ans - cpdef ntl_ZZ_pX _ntl_rep(self): + cpdef ntl_ZZ_pX _ntl_rep(self) noexcept: """ Return an ``ntl_ZZ_pX`` that holds the value of ``self``. @@ -1662,7 +1662,7 @@ cdef class pAdicZZpXCAElement(pAdicZZpXElement): ans.x = self.value return ans - cpdef _ntl_rep_abs(self): + cpdef _ntl_rep_abs(self) noexcept: """ Return a pair ``(f, 0)`` where ``f = self._ntl_rep()``. @@ -1742,7 +1742,7 @@ cdef class pAdicZZpXCAElement(pAdicZZpXElement): S = R[var] return S(self._polynomial_list()) - cdef ZZ_p_c _const_term(self): + cdef ZZ_p_c _const_term(self) noexcept: """ Returns the constant term of ``self.value``. @@ -1781,7 +1781,7 @@ cdef class pAdicZZpXCAElement(pAdicZZpXElement): # Should be sped up later return (self - right).is_zero(absprec) - cpdef pAdicZZpXCAElement lift_to_precision(self, absprec=None): + cpdef pAdicZZpXCAElement lift_to_precision(self, absprec=None) noexcept: """ Returns a ``pAdicZZpXCAElement`` congruent to ``self`` but with absolute precision at least ``absprec``. @@ -2215,7 +2215,7 @@ cdef class pAdicZZpXCAElement(pAdicZZpXElement): # """ # raise NotImplementedError - cdef long valuation_c(self): + cdef long valuation_c(self) noexcept: """ Returns the valuation of ``self``. @@ -2252,7 +2252,7 @@ cdef class pAdicZZpXCAElement(pAdicZZpXElement): else: return self.absprec - cpdef pAdicZZpXCAElement unit_part(self): + cpdef pAdicZZpXCAElement unit_part(self) noexcept: """ Returns the unit part of ``self``, ie ``self / uniformizer^(self.valuation())`` @@ -2275,7 +2275,7 @@ cdef class pAdicZZpXCAElement(pAdicZZpXElement): """ return self._rshift_c(self.valuation_c()) - cdef ext_p_list(self, bint pos): + cdef ext_p_list(self, bint pos) noexcept: """ Returns a list of integers (in the Eisenstein case) or a list of lists of integers (in the unramified case). ``self`` can diff --git a/src/sage/rings/padics/padic_ZZ_pX_CR_element.pxd b/src/sage/rings/padics/padic_ZZ_pX_CR_element.pxd index 9744b2a3f62..4d458507ee0 100644 --- a/src/sage/rings/padics/padic_ZZ_pX_CR_element.pxd +++ b/src/sage/rings/padics/padic_ZZ_pX_CR_element.pxd @@ -19,14 +19,14 @@ cdef class pAdicZZpXCRElement(pAdicZZpXElement): cdef int _set_from_ZZ_pX_part1(self, ZZ_pX_c* poly) except -1 cdef int _set_from_ZZ_pX_part2(self, ZZ_pX_c* poly) except -1 - cdef pAdicZZpXCRElement _new_c(self, long relprec) + cdef pAdicZZpXCRElement _new_c(self, long relprec) noexcept cdef int _internal_lshift(self, long shift) except -1 cdef int _normalize(self) except -1 - cdef pAdicZZpXCRElement _lshift_c(self, long n) - cdef pAdicZZpXCRElement _rshift_c(self, long n) - cpdef pAdicZZpXCRElement unit_part(self) - cpdef ntl_ZZ_pX _ntl_rep_unnormalized(self) - cpdef _ntl_rep_abs(self) - cpdef ntl_ZZ_pX _ntl_rep(self) + cdef pAdicZZpXCRElement _lshift_c(self, long n) noexcept + cdef pAdicZZpXCRElement _rshift_c(self, long n) noexcept + cpdef pAdicZZpXCRElement unit_part(self) noexcept + cpdef ntl_ZZ_pX _ntl_rep_unnormalized(self) noexcept + cpdef _ntl_rep_abs(self) noexcept + cpdef ntl_ZZ_pX _ntl_rep(self) noexcept - cpdef pAdicZZpXCRElement lift_to_precision(self, absprec=*) + cpdef pAdicZZpXCRElement lift_to_precision(self, absprec=*) noexcept diff --git a/src/sage/rings/padics/padic_ZZ_pX_CR_element.pyx b/src/sage/rings/padics/padic_ZZ_pX_CR_element.pyx index 8a8828a5712..f0406955abe 100644 --- a/src/sage/rings/padics/padic_ZZ_pX_CR_element.pyx +++ b/src/sage/rings/padics/padic_ZZ_pX_CR_element.pyx @@ -1468,7 +1468,7 @@ cdef class pAdicZZpXCRElement(pAdicZZpXElement): shift = shift >> 1 i += 1 - cdef pAdicZZpXCRElement _new_c(self, long relprec): + cdef pAdicZZpXCRElement _new_c(self, long relprec) noexcept: """ Return a new element with the same parent as ``self`` and relative precision ``relprec`` @@ -1593,7 +1593,7 @@ cdef class pAdicZZpXCRElement(pAdicZZpXElement): sig_off() return ans - cdef pAdicZZpXCRElement _lshift_c(self, long n): + cdef pAdicZZpXCRElement _lshift_c(self, long n) noexcept: """ Multiplies ``self`` by the uniformizer raised to the power ``n``. If ``n`` is negative, right shifts by ``-n``. @@ -1660,7 +1660,7 @@ cdef class pAdicZZpXCRElement(pAdicZZpXElement): return ans return self._lshift_c(mpz_get_si((shift).value)) - cdef pAdicZZpXCRElement _rshift_c(self, long n): + cdef pAdicZZpXCRElement _rshift_c(self, long n) noexcept: """ Divides self by the uniformizer raised to the power ``n``. If parent is not a field, throws away the non-positive part of @@ -1763,7 +1763,7 @@ cdef class pAdicZZpXCRElement(pAdicZZpXElement): return ans return self._rshift_c(mpz_get_si((shift).value)) - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ Negation @@ -2043,7 +2043,7 @@ cdef class pAdicZZpXCRElement(pAdicZZpXElement): sig_off() return ans - cpdef _add_(self, _right): + cpdef _add_(self, _right) noexcept: """ Compute the sum of ``self`` and ``right``. @@ -2160,7 +2160,7 @@ cdef class pAdicZZpXCRElement(pAdicZZpXElement): ans.relprec = -ans.relprec return ans - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Return the difference of two elements @@ -2186,7 +2186,7 @@ cdef class pAdicZZpXCRElement(pAdicZZpXElement): # For now, a simple implementation return self + (-right) - cpdef _mul_(self, _right): + cpdef _mul_(self, _right) noexcept: """ Return the product of two elements @@ -2239,7 +2239,7 @@ cdef class pAdicZZpXCRElement(pAdicZZpXElement): sig_off() return ans - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Return the quotient of two elements @@ -2383,7 +2383,7 @@ cdef class pAdicZZpXCRElement(pAdicZZpXElement): ans = (self.ordp >= aprec) return ans - cpdef ntl_ZZ_pX _ntl_rep_unnormalized(self): + cpdef ntl_ZZ_pX _ntl_rep_unnormalized(self) noexcept: """ Return an ``ntl_ZZ_pX`` holding the current unit part of this element @@ -2412,7 +2412,7 @@ cdef class pAdicZZpXCRElement(pAdicZZpXElement): ans.x = self.unit return ans - cpdef ntl_ZZ_pX _ntl_rep(self): + cpdef ntl_ZZ_pX _ntl_rep(self) noexcept: """ Return an ``ntl_ZZ_pX`` that holds the unit part of this element @@ -2433,7 +2433,7 @@ cdef class pAdicZZpXCRElement(pAdicZZpXElement): self._normalize() return self._ntl_rep_unnormalized() - cpdef _ntl_rep_abs(self): + cpdef _ntl_rep_abs(self) noexcept: """ Return a pair ``(f, k)`` where ``f`` is an ``ntl_ZZ_pX`` and ``k`` is a non-positive integer such that ``self = f(self.parent.gen())*p^k`` @@ -2571,7 +2571,7 @@ cdef class pAdicZZpXCRElement(pAdicZZpXElement): S = R[var] return S(self._polynomial_list()) - cdef ZZ_p_c _const_term(self): + cdef ZZ_p_c _const_term(self) noexcept: """ Return the constant term of ``self.unit``. @@ -2619,7 +2619,7 @@ cdef class pAdicZZpXCRElement(pAdicZZpXElement): # """ # raise NotImplementedError - cpdef pAdicZZpXCRElement lift_to_precision(self, absprec=None): + cpdef pAdicZZpXCRElement lift_to_precision(self, absprec=None) noexcept: """ Return a ``pAdicZZpXCRElement`` congruent to this element but with absolute precision at least ``absprec``. @@ -3143,7 +3143,7 @@ cdef class pAdicZZpXCRElement(pAdicZZpXElement): # """ # raise NotImplementedError - cdef long valuation_c(self): + cdef long valuation_c(self) noexcept: """ Return the valuation of this element. @@ -3167,7 +3167,7 @@ cdef class pAdicZZpXCRElement(pAdicZZpXElement): self._normalize() return self.ordp - cpdef pAdicZZpXCRElement unit_part(self): + cpdef pAdicZZpXCRElement unit_part(self) noexcept: """ Return the unit part of this element, ie ``self / uniformizer^(self.valuation())``. @@ -3205,7 +3205,7 @@ cdef class pAdicZZpXCRElement(pAdicZZpXElement): ans.unit = self.unit return ans - cdef ext_p_list(self, bint pos): + cdef ext_p_list(self, bint pos) noexcept: """ Return a list of integers (in the Eisenstein case) or a list of lists of integers (in the unramified case). ``self`` can be diff --git a/src/sage/rings/padics/padic_ZZ_pX_FM_element.pxd b/src/sage/rings/padics/padic_ZZ_pX_FM_element.pxd index 90626089442..33754581e48 100644 --- a/src/sage/rings/padics/padic_ZZ_pX_FM_element.pxd +++ b/src/sage/rings/padics/padic_ZZ_pX_FM_element.pxd @@ -4,8 +4,8 @@ from sage.structure.element cimport RingElement, ModuleElement cdef class pAdicZZpXFMElement(pAdicZZpXElement): cdef ZZ_pX_c value - cdef pAdicZZpXFMElement _new_c(self) - cdef pAdicZZpXFMElement _lshift_c(self, long n) - cdef pAdicZZpXFMElement _rshift_c(self, long n) + cdef pAdicZZpXFMElement _new_c(self) noexcept + cdef pAdicZZpXFMElement _lshift_c(self, long n) noexcept + cdef pAdicZZpXFMElement _rshift_c(self, long n) noexcept - cpdef pAdicZZpXFMElement unit_part(self) + cpdef pAdicZZpXFMElement unit_part(self) noexcept diff --git a/src/sage/rings/padics/padic_ZZ_pX_FM_element.pyx b/src/sage/rings/padics/padic_ZZ_pX_FM_element.pyx index ec5e833662f..70d09266445 100644 --- a/src/sage/rings/padics/padic_ZZ_pX_FM_element.pyx +++ b/src/sage/rings/padics/padic_ZZ_pX_FM_element.pyx @@ -415,7 +415,7 @@ cdef class pAdicZZpXFMElement(pAdicZZpXElement): holder.x = self.value return make_ZZpXFMElement, (self.parent(), holder) - cdef pAdicZZpXFMElement _new_c(self): + cdef pAdicZZpXFMElement _new_c(self) noexcept: """ Return a new element with the same parent as ``self``. @@ -434,7 +434,7 @@ cdef class pAdicZZpXFMElement(pAdicZZpXElement): ans.prime_pow = self.prime_pow return ans - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ First compare valuations, then compare the values. @@ -504,7 +504,7 @@ cdef class pAdicZZpXFMElement(pAdicZZpXElement): sig_off() return ans - cdef pAdicZZpXFMElement _lshift_c(self, long n): + cdef pAdicZZpXFMElement _lshift_c(self, long n) noexcept: """ Multiply ``self`` by the uniformizer raised to the power ``n``. @@ -565,7 +565,7 @@ cdef class pAdicZZpXFMElement(pAdicZZpXElement): return ans return self._lshift_c(mpz_get_si((shift).value)) - cdef pAdicZZpXFMElement _rshift_c(self, long n): + cdef pAdicZZpXFMElement _rshift_c(self, long n) noexcept: """ Divide ``self`` by the uniformizer raised to the power ``n``. @@ -656,7 +656,7 @@ cdef class pAdicZZpXFMElement(pAdicZZpXElement): return ans return self._rshift_c(mpz_get_si((shift).value)) - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ Returns ``-self``. @@ -747,7 +747,7 @@ cdef class pAdicZZpXFMElement(pAdicZZpXElement): sig_off() return ans - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Return ``self`` + ``right``. @@ -766,7 +766,7 @@ cdef class pAdicZZpXFMElement(pAdicZZpXElement): ZZ_pX_add(ans.value, self.value, (right).value) return ans - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Return the product of ``self`` and ``right``. @@ -790,7 +790,7 @@ cdef class pAdicZZpXFMElement(pAdicZZpXElement): ZZ_pX_MulMod_pre(ans.value, self.value, (right).value, self.prime_pow.get_top_modulus()[0]) return ans - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Return the difference of ``self`` and ``right``. @@ -813,7 +813,7 @@ cdef class pAdicZZpXFMElement(pAdicZZpXElement): ZZ_pX_sub(ans.value, self.value, (right).value) return ans - cpdef _div_(self, _right): + cpdef _div_(self, _right) noexcept: """ Returns the quotient of ``self`` by ``right``. @@ -1205,7 +1205,7 @@ cdef class pAdicZZpXFMElement(pAdicZZpXElement): S = R[var] return S(self._polynomial_list()) - cdef ZZ_p_c _const_term(self): + cdef ZZ_p_c _const_term(self) noexcept: """ Return the constant term of ``self.unit``. @@ -1591,7 +1591,7 @@ cdef class pAdicZZpXFMElement(pAdicZZpXElement): mpz_set_ui(ans.value, self.prime_pow.ram_prec_cap - self.valuation_c()) return ans - cpdef pAdicZZpXFMElement unit_part(self): + cpdef pAdicZZpXFMElement unit_part(self) noexcept: """ Return the unit part of ``self``, ie ``self / uniformizer^(self.valuation())`` @@ -1629,7 +1629,7 @@ cdef class pAdicZZpXFMElement(pAdicZZpXElement): """ return self._rshift_c(self.valuation_c()) - cdef long valuation_c(self): + cdef long valuation_c(self) noexcept: """ Return the valuation of ``self``. @@ -1663,7 +1663,7 @@ cdef class pAdicZZpXFMElement(pAdicZZpXElement): else: return index + valuation * self.prime_pow.e - cdef ext_p_list(self, bint pos): + cdef ext_p_list(self, bint pos) noexcept: r""" Return a list giving a series representation of ``self``. diff --git a/src/sage/rings/padics/padic_ZZ_pX_element.pyx b/src/sage/rings/padics/padic_ZZ_pX_element.pyx index b23f010edde..81a6cd1e28c 100644 --- a/src/sage/rings/padics/padic_ZZ_pX_element.pyx +++ b/src/sage/rings/padics/padic_ZZ_pX_element.pyx @@ -227,7 +227,7 @@ cdef class pAdicZZpXElement(pAdicExtElement): else: raise ValueError("context must be a power of the appropriate prime") - cdef ext_p_list_precs(self, bint pos, long prec): + cdef ext_p_list_precs(self, bint pos, long prec) noexcept: """ Returns a list giving a series representation of ``self``. @@ -621,7 +621,7 @@ def _test_preprocess_list(R, L): return preprocess_list(R(0), L) -cdef preprocess_list(pAdicZZpXElement elt, L): +cdef preprocess_list(pAdicZZpXElement elt, L) noexcept: """ See the documentation for :func:`_test_preprocess_list`. """ @@ -736,7 +736,7 @@ def _find_val_aprec_test(R, L): """ return find_val_aprec(R.prime_pow, L) -cdef find_val_aprec(PowComputer_ext pp, L): +cdef find_val_aprec(PowComputer_ext pp, L) noexcept: r""" Given a list ``L``, finds the minimum valuation, minimum absolute precision and minimum common type of the elements. @@ -841,7 +841,7 @@ def _test_get_val_prec(R, a): """ return get_val_prec(R.prime_pow, a) -cdef get_val_prec(PowComputer_ext pp, a): +cdef get_val_prec(PowComputer_ext pp, a) noexcept: r""" Return valuation, absolute precision and type of an input element. diff --git a/src/sage/rings/padics/padic_capped_absolute_element.pxd b/src/sage/rings/padics/padic_capped_absolute_element.pxd index 48c8500a678..b80b6593bf6 100644 --- a/src/sage/rings/padics/padic_capped_absolute_element.pxd +++ b/src/sage/rings/padics/padic_capped_absolute_element.pxd @@ -6,8 +6,8 @@ ctypedef mpz_t celement include "CA_template_header.pxi" cdef class pAdicCappedAbsoluteElement(CAElement): - cdef lift_c(self) - cdef pari_gen _to_gen(self) + cdef lift_c(self) noexcept + cdef pari_gen _to_gen(self) noexcept from sage.rings.padics.pow_computer cimport PowComputer_base cdef class PowComputer_(PowComputer_base): diff --git a/src/sage/rings/padics/padic_capped_absolute_element.pyx b/src/sage/rings/padics/padic_capped_absolute_element.pyx index 69d5b474f20..061d36fd309 100644 --- a/src/sage/rings/padics/padic_capped_absolute_element.pyx +++ b/src/sage/rings/padics/padic_capped_absolute_element.pyx @@ -97,7 +97,7 @@ cdef class pAdicCappedAbsoluteElement(CAElement): """ return self.lift_c() - cdef lift_c(self): + cdef lift_c(self) noexcept: """ Implementation of lift. @@ -124,7 +124,7 @@ cdef class pAdicCappedAbsoluteElement(CAElement): """ return self._to_gen() - cdef pari_gen _to_gen(self): + cdef pari_gen _to_gen(self) noexcept: """ Converts this element to an equivalent pari element. diff --git a/src/sage/rings/padics/padic_capped_relative_element.pxd b/src/sage/rings/padics/padic_capped_relative_element.pxd index 2cf6d5276f5..5c929be226d 100644 --- a/src/sage/rings/padics/padic_capped_relative_element.pxd +++ b/src/sage/rings/padics/padic_capped_relative_element.pxd @@ -5,8 +5,8 @@ ctypedef mpz_t celement include "CR_template_header.pxi" cdef class pAdicCappedRelativeElement(CRElement): - cdef lift_c(self) - cdef pari_gen _to_gen(self) + cdef lift_c(self) noexcept + cdef pari_gen _to_gen(self) noexcept from sage.rings.padics.pow_computer cimport PowComputer_base cdef class PowComputer_(PowComputer_base): diff --git a/src/sage/rings/padics/padic_capped_relative_element.pyx b/src/sage/rings/padics/padic_capped_relative_element.pyx index 10db90d1342..c32b882ff8e 100644 --- a/src/sage/rings/padics/padic_capped_relative_element.pyx +++ b/src/sage/rings/padics/padic_capped_relative_element.pyx @@ -160,7 +160,7 @@ cdef class pAdicCappedRelativeElement(CRElement): """ return self.lift_c() - cdef lift_c(self): + cdef lift_c(self) noexcept: """ Implementation of lift. @@ -210,7 +210,7 @@ cdef class pAdicCappedRelativeElement(CRElement): """ return self._to_gen() - cdef pari_gen _to_gen(self): + cdef pari_gen _to_gen(self) noexcept: """ Convert this element to an equivalent pari element. diff --git a/src/sage/rings/padics/padic_ext_element.pxd b/src/sage/rings/padics/padic_ext_element.pxd index b3e4a37ab1f..e267f0129c7 100644 --- a/src/sage/rings/padics/padic_ext_element.pxd +++ b/src/sage/rings/padics/padic_ext_element.pxd @@ -32,6 +32,6 @@ cdef class pAdicExtElement(pAdicGenericElement): cdef long _check_ZZ_pContext(self, ntl_ZZ_pContext_class ctx) except -1 cdef long _check_ZZ_pEContext(self, ntl_ZZ_pEContext_class ctx) except -1 - cdef ext_p_list(self, bint pos) - cdef ext_p_list_precs(self, bint pos, long prec) - cdef ZZ_p_c _const_term(self) + cdef ext_p_list(self, bint pos) noexcept + cdef ext_p_list_precs(self, bint pos, long prec) noexcept + cdef ZZ_p_c _const_term(self) noexcept diff --git a/src/sage/rings/padics/padic_ext_element.pyx b/src/sage/rings/padics/padic_ext_element.pyx index 94a7d93c727..0b5bc0f1249 100644 --- a/src/sage/rings/padics/padic_ext_element.pyx +++ b/src/sage/rings/padics/padic_ext_element.pyx @@ -262,10 +262,10 @@ cdef class pAdicExtElement(pAdicGenericElement): cdef long _check_ZZ_pEContext(self, ntl_ZZ_pEContext_class ctx) except -1: raise NotImplementedError - cdef ext_p_list(self, bint pos): + cdef ext_p_list(self, bint pos) noexcept: raise NotImplementedError - cdef ext_p_list_precs(self, bint pos, long prec): + cdef ext_p_list_precs(self, bint pos, long prec) noexcept: raise NotImplementedError def _const_term_test(self): @@ -290,7 +290,7 @@ cdef class pAdicExtElement(pAdicGenericElement): ans.x = self._const_term() return ans - cdef ZZ_p_c _const_term(self): + cdef ZZ_p_c _const_term(self) noexcept: raise NotImplementedError def _ext_p_list(self, pos): diff --git a/src/sage/rings/padics/padic_extension_generic.py b/src/sage/rings/padics/padic_extension_generic.py index dc80e998bcd..59264f4f0f4 100644 --- a/src/sage/rings/padics/padic_extension_generic.py +++ b/src/sage/rings/padics/padic_extension_generic.py @@ -632,7 +632,7 @@ def free_module(self, base=None, basis=None, map=True): from_V = MapFreeModuleToTwoStep to_V = MapTwoStepToFreeModule elif base is self: - return super(pAdicExtensionGeneric, self).free_module(base=base, basis=basis, map=map) + return super().free_module(base=base, basis=basis, map=map) else: raise NotImplementedError FromV = Hom(V, self) diff --git a/src/sage/rings/padics/padic_extension_leaves.py b/src/sage/rings/padics/padic_extension_leaves.py index bf5599f7c59..44156a85075 100644 --- a/src/sage/rings/padics/padic_extension_leaves.py +++ b/src/sage/rings/padics/padic_extension_leaves.py @@ -483,7 +483,7 @@ def _coerce_map_from_(self, R): from sage.rings.padics.qadic_flint_FP import pAdicCoercion_FP_frac_field return pAdicCoercion_FP_frac_field(R, self) - return super(UnramifiedExtensionFieldFloatingPoint, self)._coerce_map_from_(R) + return super()._coerce_map_from_(R) class EisensteinExtensionRingCappedRelative(EisensteinExtensionGeneric, pAdicCappedRelativeRingGeneric): """ diff --git a/src/sage/rings/padics/padic_fixed_mod_element.pxd b/src/sage/rings/padics/padic_fixed_mod_element.pxd index cd619a1bcb2..4d9bff415d0 100644 --- a/src/sage/rings/padics/padic_fixed_mod_element.pxd +++ b/src/sage/rings/padics/padic_fixed_mod_element.pxd @@ -6,8 +6,8 @@ ctypedef mpz_t celement include "FM_template_header.pxi" cdef class pAdicFixedModElement(FMElement): - cdef lift_c(self) - cdef pari_gen _to_gen(self) + cdef lift_c(self) noexcept + cdef pari_gen _to_gen(self) noexcept from sage.rings.padics.pow_computer cimport PowComputer_base cdef class PowComputer_(PowComputer_base): diff --git a/src/sage/rings/padics/padic_fixed_mod_element.pyx b/src/sage/rings/padics/padic_fixed_mod_element.pyx index 2e9e9a1ed3b..d538b10475d 100644 --- a/src/sage/rings/padics/padic_fixed_mod_element.pyx +++ b/src/sage/rings/padics/padic_fixed_mod_element.pyx @@ -156,7 +156,7 @@ cdef class pAdicFixedModElement(FMElement): """ return self.lift_c() - cdef lift_c(self): + cdef lift_c(self) noexcept: r""" Returns an integer congruent to this element modulo the precision. @@ -188,7 +188,7 @@ cdef class pAdicFixedModElement(FMElement): """ return self._to_gen() - cdef pari_gen _to_gen(self): + cdef pari_gen _to_gen(self) noexcept: """ Convert ``self`` to an equivalent pari element. diff --git a/src/sage/rings/padics/padic_floating_point_element.pxd b/src/sage/rings/padics/padic_floating_point_element.pxd index 721c471d253..816a9fce705 100644 --- a/src/sage/rings/padics/padic_floating_point_element.pxd +++ b/src/sage/rings/padics/padic_floating_point_element.pxd @@ -5,8 +5,8 @@ ctypedef mpz_t celement include "FP_template_header.pxi" cdef class pAdicFloatingPointElement(FPElement): - cdef lift_c(self) - cdef pari_gen _to_gen(self) + cdef lift_c(self) noexcept + cdef pari_gen _to_gen(self) noexcept from sage.rings.padics.pow_computer cimport PowComputer_base cdef class PowComputer_(PowComputer_base): diff --git a/src/sage/rings/padics/padic_floating_point_element.pyx b/src/sage/rings/padics/padic_floating_point_element.pyx index 32c8e25cde2..70f5ce806af 100644 --- a/src/sage/rings/padics/padic_floating_point_element.pyx +++ b/src/sage/rings/padics/padic_floating_point_element.pyx @@ -158,7 +158,7 @@ cdef class pAdicFloatingPointElement(FPElement): """ return self.lift_c() - cdef lift_c(self): + cdef lift_c(self) noexcept: r""" Implementation of lift. @@ -204,7 +204,7 @@ cdef class pAdicFloatingPointElement(FPElement): """ return self._to_gen() - cdef pari_gen _to_gen(self): + cdef pari_gen _to_gen(self) noexcept: """ Convert this element to an equivalent pari element. diff --git a/src/sage/rings/padics/padic_generic_element.pxd b/src/sage/rings/padics/padic_generic_element.pxd index 780aa4655bf..091d56bb912 100644 --- a/src/sage/rings/padics/padic_generic_element.pxd +++ b/src/sage/rings/padics/padic_generic_element.pxd @@ -8,11 +8,11 @@ from sage.rings.padics.pow_computer cimport PowComputer_class from sage.rings.integer cimport Integer from sage.rings.rational cimport Rational -cpdef gauss_table(long long p, int f, int prec, bint use_longs) +cpdef gauss_table(long long p, int f, int prec, bint use_longs) noexcept cdef class pAdicGenericElement(LocalGenericElement): - cdef long valuation_c(self) - cpdef val_unit(self) + cdef long valuation_c(self) noexcept + cpdef val_unit(self) noexcept cdef int _set_from_Integer(self, Integer x, absprec, relprec) except -1 cdef int _set_from_mpz(self, mpz_t x) except -1 @@ -41,7 +41,7 @@ cdef class pAdicGenericElement(LocalGenericElement): cdef bint _set_prec_rel(self, long relprec) except -1 cdef bint _set_prec_both(self, long absprec, long relprec) except -1 - cpdef abs(self, prec=*) - cpdef _mod_(self, right) - cpdef _floordiv_(self, right) + cpdef abs(self, prec=*) noexcept + cpdef _mod_(self, right) noexcept + cpdef _floordiv_(self, right) noexcept cpdef bint _is_base_elt(self, p) except -1 diff --git a/src/sage/rings/padics/padic_generic_element.pyx b/src/sage/rings/padics/padic_generic_element.pyx index f68405dcc6f..c54005de2f7 100644 --- a/src/sage/rings/padics/padic_generic_element.pyx +++ b/src/sage/rings/padics/padic_generic_element.pyx @@ -43,7 +43,7 @@ from sage.structure.richcmp cimport rich_to_bool cdef long maxordp = (1L << (sizeof(long) * 8 - 2)) - 1 cdef class pAdicGenericElement(LocalGenericElement): - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: r""" First compare valuations, then compare normalized residue of unit part. @@ -354,7 +354,7 @@ cdef class pAdicGenericElement(LocalGenericElement): raise ZeroDivisionError("cannot divide by zero") return self._floordiv_(right) - cpdef _floordiv_(self, right): + cpdef _floordiv_(self, right) noexcept: """ Implements floor division. @@ -464,7 +464,7 @@ cdef class pAdicGenericElement(LocalGenericElement): """ return ~self.parent().fraction_field()(self, relprec = self.precision_relative()) - cpdef _mod_(self, right): + cpdef _mod_(self, right) noexcept: """ If self is in a field, returns 0. If in a ring, returns a p-adic integer such that @@ -2093,7 +2093,7 @@ cdef class pAdicGenericElement(LocalGenericElement): mpz_set_si(ans.value, v) return ans - cdef long valuation_c(self): + cdef long valuation_c(self) noexcept: """ This function is overridden in subclasses to provide an actual implementation of valuation. @@ -2112,7 +2112,7 @@ cdef class pAdicGenericElement(LocalGenericElement): """ raise NotImplementedError - cpdef val_unit(self): + cpdef val_unit(self) noexcept: r""" Return ``(self.valuation(), self.unit_part())``. To be overridden in derived classes. @@ -3995,7 +3995,7 @@ cdef class pAdicGenericElement(LocalGenericElement): """ return self.abs() - cpdef abs(self, prec=None): + cpdef abs(self, prec=None) noexcept: """ Return the `p`-adic absolute value of ``self``. @@ -4486,7 +4486,7 @@ def _compute_g(p, n, prec, terms): g[i+1] = -(g[i]/(v-v**2)).integral() return [x.truncate(terms) for x in g] -cpdef dwork_mahler_coeffs(R, int bd=20): +cpdef dwork_mahler_coeffs(R, int bd=20) noexcept: r""" Compute Dwork's formula for Mahler coefficients of `p`-adic Gamma. @@ -4534,7 +4534,7 @@ cpdef dwork_mahler_coeffs(R, int bd=20): v.append(R(x << i)) return v -cpdef evaluate_dwork_mahler(v, x, long long p, int bd, long long a): +cpdef evaluate_dwork_mahler(v, x, long long p, int bd, long long a) noexcept: """ Evaluate Dwork's Mahler series for `p`-adic Gamma. @@ -4564,7 +4564,7 @@ cpdef evaluate_dwork_mahler(v, x, long long p, int bd, long long a): return -s cdef long long evaluate_dwork_mahler_long(array.array v, long long x, long long p, int bd, - long long a, long long q): + long long a, long long q) noexcept: cdef int k cdef long long a1, s, u bd -= 1 @@ -4578,7 +4578,7 @@ cdef long long evaluate_dwork_mahler_long(array.array v, long long x, long long s = s % q return -s -cpdef gauss_table(long long p, int f, int prec, bint use_longs): +cpdef gauss_table(long long p, int f, int prec, bint use_longs) noexcept: r""" Compute a table of Gauss sums using the Gross-Koblitz formula. diff --git a/src/sage/rings/padics/padic_printing.pxd b/src/sage/rings/padics/padic_printing.pxd index 44698b3d73d..e0ce12540c6 100644 --- a/src/sage/rings/padics/padic_printing.pxd +++ b/src/sage/rings/padics/padic_printing.pxd @@ -22,16 +22,16 @@ cdef class pAdicPrinter_class(SageObject): cdef long max_terse_terms cdef object show_prec - cdef base_p_list(self, value, bint pos) - cdef _repr_gen(self, pAdicGenericElement elt, bint do_latex, bint pos, int mode, pname) - cdef _repr_spec(self, pAdicGenericElement elt, bint do_latex, bint pos, int _mode, bint paren, pname) - cdef _print_list_as_poly(self, L, bint do_latex, polyname, long expshift, bint increasing) - cdef _truncate_list(self, L, max_terms, zero) - cdef _var(self, x, exp, do_latex) - cdef _dot_var(self, x, exp, do_latex) - cdef _co_dot_var(self, co, x, exp, do_latex) - cdef _plus_ellipsis(self, bint do_latex) - cdef _ellipsis(self, bint do_latex) - cdef _terse_frac(self, a, v, u, ram_name, bint do_latex) - cdef _print_unram_term(self, L, bint do_latex, polyname, long max_unram_terms, long expshift, bint increasing) - cdef _print_term_of_poly(self, s, coeff, bint do_latex, polyname, long exp) + cdef base_p_list(self, value, bint pos) noexcept + cdef _repr_gen(self, pAdicGenericElement elt, bint do_latex, bint pos, int mode, pname) noexcept + cdef _repr_spec(self, pAdicGenericElement elt, bint do_latex, bint pos, int _mode, bint paren, pname) noexcept + cdef _print_list_as_poly(self, L, bint do_latex, polyname, long expshift, bint increasing) noexcept + cdef _truncate_list(self, L, max_terms, zero) noexcept + cdef _var(self, x, exp, do_latex) noexcept + cdef _dot_var(self, x, exp, do_latex) noexcept + cdef _co_dot_var(self, co, x, exp, do_latex) noexcept + cdef _plus_ellipsis(self, bint do_latex) noexcept + cdef _ellipsis(self, bint do_latex) noexcept + cdef _terse_frac(self, a, v, u, ram_name, bint do_latex) noexcept + cdef _print_unram_term(self, L, bint do_latex, polyname, long max_unram_terms, long expshift, bint increasing) noexcept + cdef _print_term_of_poly(self, s, coeff, bint do_latex, polyname, long exp) noexcept diff --git a/src/sage/rings/padics/padic_printing.pyx b/src/sage/rings/padics/padic_printing.pyx index aef767034a8..a75f85b4cf0 100644 --- a/src/sage/rings/padics/padic_printing.pyx +++ b/src/sage/rings/padics/padic_printing.pyx @@ -816,7 +816,7 @@ cdef class pAdicPrinter_class(SageObject): """ return self.base_p_list(value, pos) - cdef base_p_list(self, value, bint pos): + cdef base_p_list(self, value, bint pos) noexcept: """ Returns a list of integers forming the base p expansion of value. @@ -894,7 +894,7 @@ cdef class pAdicPrinter_class(SageObject): pprint = latex_variable_name(pprint) return self._repr_gen(elt, do_latex, _pos, _mode, pprint) - cdef _repr_gen(self, pAdicGenericElement elt, bint do_latex, bint pos, int mode, ram_name): + cdef _repr_gen(self, pAdicGenericElement elt, bint do_latex, bint pos, int mode, ram_name) noexcept: r""" Prints a string representation of the element. See __init__ for more details on print modes. @@ -1054,7 +1054,7 @@ cdef class pAdicPrinter_class(SageObject): if s == "": s = "0" return s - cdef _repr_spec(self, pAdicGenericElement elt, bint do_latex, bint pos, int mode, bint paren, ram_name): + cdef _repr_spec(self, pAdicGenericElement elt, bint do_latex, bint pos, int mode, bint paren, ram_name) noexcept: """ A function used by repr_gen for terse and series printing. @@ -1271,7 +1271,7 @@ cdef class pAdicPrinter_class(SageObject): s = "(" + s + ")" return s - cdef _var(self, x, exp, do_latex): + cdef _var(self, x, exp, do_latex) noexcept: """ Returns a representation of 'x^exp', latexed if necessary. """ @@ -1284,7 +1284,7 @@ cdef class pAdicPrinter_class(SageObject): else: return "%s^%s"%(x, exp) - cdef _dot_var(self, x, exp, do_latex): + cdef _dot_var(self, x, exp, do_latex) noexcept: """ Returns a representation of '*x^exp', latexed if necessary. """ @@ -1300,7 +1300,7 @@ cdef class pAdicPrinter_class(SageObject): else: return "*%s^%s"%(x, exp) - cdef _co_dot_var(self, co, x, exp, do_latex): + cdef _co_dot_var(self, co, x, exp, do_latex) noexcept: """ Returns a representation of 'co*x^exp', latexed if necessary. @@ -1325,7 +1325,7 @@ cdef class pAdicPrinter_class(SageObject): else: return "%s*%s^%s"%(co, x, exp) - cdef _plus_ellipsis(self, bint do_latex): + cdef _plus_ellipsis(self, bint do_latex) noexcept: """ Returns a representation of '+ ...', latexed if necessary. """ @@ -1334,7 +1334,7 @@ cdef class pAdicPrinter_class(SageObject): else: return " + ..." - cdef _ellipsis(self, bint do_latex): + cdef _ellipsis(self, bint do_latex) noexcept: """ Returns a representation of '...', latexed if necessary. """ @@ -1343,7 +1343,7 @@ cdef class pAdicPrinter_class(SageObject): else: return "..." - cdef _truncate_list(self, L, max_terms, zero): + cdef _truncate_list(self, L, max_terms, zero) noexcept: """ Takes a list L of coefficients and returns a list with at most max_terms nonzero terms. @@ -1375,7 +1375,7 @@ cdef class pAdicPrinter_class(SageObject): ans.append(c) return ans, False - cdef _print_unram_term(self, L, bint do_latex, polyname, long max_unram_terms, long expshift, bint increasing): + cdef _print_unram_term(self, L, bint do_latex, polyname, long max_unram_terms, long expshift, bint increasing) noexcept: """ Returns a string representation of L when considered as a polynomial, truncating to at most max_unram_terms nonzero terms. @@ -1448,7 +1448,7 @@ cdef class pAdicPrinter_class(SageObject): s = self._print_term_of_poly(s, L[j], do_latex, polyname, exp) return s - cdef _terse_frac(self, a, v, u, ram_name, bint do_latex): + cdef _terse_frac(self, a, v, u, ram_name, bint do_latex) noexcept: """ Returns a representation of a=u/ram_name^v, latexed if necessary. """ @@ -1468,7 +1468,7 @@ cdef class pAdicPrinter_class(SageObject): arep = "%s/%s^%s"%(u, ram_name, -v) return arep - cdef _print_list_as_poly(self, L, bint do_latex, polyname, long expshift, bint increasing): + cdef _print_list_as_poly(self, L, bint do_latex, polyname, long expshift, bint increasing) noexcept: """ Prints a list L as a polynomial. @@ -1499,7 +1499,7 @@ cdef class pAdicPrinter_class(SageObject): s = self._print_term_of_poly(s, L[j], do_latex, polyname, exp) return s - cdef _print_term_of_poly(self, s, coeff, bint do_latex, polyname, long exp): + cdef _print_term_of_poly(self, s, coeff, bint do_latex, polyname, long exp) noexcept: """ Appends +coeff*polyname^exp to s, latexed if necessary. """ diff --git a/src/sage/rings/padics/padic_template_element.pxi b/src/sage/rings/padics/padic_template_element.pxi index 06d65d1672c..4ca0356774f 100644 --- a/src/sage/rings/padics/padic_template_element.pxi +++ b/src/sage/rings/padics/padic_template_element.pxi @@ -187,7 +187,7 @@ cdef class pAdicTemplateElement(pAdicGenericElement): """ raise NotImplementedError - cdef pAdicTemplateElement _new_with_value(self, celement value, long absprec): + cdef pAdicTemplateElement _new_with_value(self, celement value, long absprec) noexcept: """ Creates a new element with a given value and absolute precision. @@ -263,7 +263,7 @@ cdef class pAdicTemplateElement(pAdicGenericElement): check_ordp(s) return self._lshift_c(s) - cdef pAdicTemplateElement _lshift_c(self, long shift): + cdef pAdicTemplateElement _lshift_c(self, long shift) noexcept: raise NotImplementedError def __rshift__(pAdicTemplateElement self, shift): @@ -311,7 +311,7 @@ cdef class pAdicTemplateElement(pAdicGenericElement): check_ordp(s) return self._rshift_c(s) - cdef pAdicTemplateElement _rshift_c(self, long shift): + cdef pAdicTemplateElement _rshift_c(self, long shift) noexcept: """ Divides by ``p^shift`` and truncates (if the parent is not a field). """ @@ -379,7 +379,7 @@ cdef class pAdicTemplateElement(pAdicGenericElement): ans.check_preccap() return ans - cdef pAdicTemplateElement lift_to_precision_c(self, long absprec): + cdef pAdicTemplateElement lift_to_precision_c(self, long absprec) noexcept: """ Lift this element to another with precision at least ``absprec``. """ @@ -623,7 +623,7 @@ cdef class pAdicTemplateElement(pAdicGenericElement): else: return trim_zeros(list(self.unit_part().expansion(lift_mode='smallest'))) - cpdef pAdicTemplateElement unit_part(self): + cpdef pAdicTemplateElement unit_part(self) noexcept: r""" Returns the unit part of this element. @@ -753,7 +753,7 @@ cdef class pAdicTemplateElement(pAdicGenericElement): else: raise NotImplementedError("reduction modulo p^n with n>1") -cdef Integer exact_pow_helper(long *ansrelprec, long relprec, _right, PowComputer_ prime_pow): +cdef Integer exact_pow_helper(long *ansrelprec, long relprec, _right, PowComputer_ prime_pow) noexcept: """ This function is used by exponentiation in both ``CR_template.pxi`` and ``CA_template.pxi`` to determine the extra precision gained from @@ -867,7 +867,7 @@ cdef long padic_pow_helper(celement result, celement base, long base_val, long b cpow(result, prime_pow.powhelper_oneunit, right.value, bloga_aprec, prime_pow) return bloga_aprec -cdef _zero(expansion_mode mode, teich_ring): +cdef _zero(expansion_mode mode, teich_ring) noexcept: """ Return an appropriate zero for a given expansion mode. diff --git a/src/sage/rings/padics/padic_template_element_header.pxi b/src/sage/rings/padics/padic_template_element_header.pxi index 11e1cc7fab7..4cd07b8c4bd 100644 --- a/src/sage/rings/padics/padic_template_element_header.pxi +++ b/src/sage/rings/padics/padic_template_element_header.pxi @@ -39,11 +39,11 @@ cdef enum expansion_mode: cdef class pAdicTemplateElement(pAdicGenericElement): cdef PowComputer_ prime_pow cdef int _set(self, x, long val, long xprec, absprec, relprec) except -1 - cdef pAdicTemplateElement _new_with_value(self, celement value, long absprec) + cdef pAdicTemplateElement _new_with_value(self, celement value, long absprec) noexcept cdef int _get_unit(self, celement value) except -1 - cdef pAdicTemplateElement _lshift_c(self, long shift) - cdef pAdicTemplateElement _rshift_c(self, long shift) + cdef pAdicTemplateElement _lshift_c(self, long shift) noexcept + cdef pAdicTemplateElement _rshift_c(self, long shift) noexcept #cpdef RingElement _floordiv_c_impl(self, RingElement right) cdef int check_preccap(self) except -1 - cdef pAdicTemplateElement lift_to_precision_c(self, long absprec) - cpdef pAdicTemplateElement unit_part(self) + cdef pAdicTemplateElement lift_to_precision_c(self, long absprec) noexcept + cpdef pAdicTemplateElement unit_part(self) noexcept diff --git a/src/sage/rings/padics/padic_valuation.py b/src/sage/rings/padics/padic_valuation.py index 90e9d205ac5..ec85d00c3f2 100644 --- a/src/sage/rings/padics/padic_valuation.py +++ b/src/sage/rings/padics/padic_valuation.py @@ -1428,7 +1428,7 @@ def extensions(self, ring): G = ring.relative_polynomial() approximant = self._base_valuation.change_domain(G.parent())._initial_approximation return [pAdicValuation(ring, approximant)] - return super(pAdicFromLimitValuation, self).extensions(ring) + return super().extensions(ring) def _fraction_field(ring): r""" diff --git a/src/sage/rings/padics/pow_computer.pxd b/src/sage/rings/padics/pow_computer.pxd index 8766725882e..b70553b77e0 100644 --- a/src/sage/rings/padics/pow_computer.pxd +++ b/src/sage/rings/padics/pow_computer.pxd @@ -22,8 +22,8 @@ cdef class PowComputer_class(SageObject): cdef unsigned long cache_limit cdef unsigned long prec_cap - cdef Integer pow_Integer(self, long n) - cdef mpz_srcptr pow_mpz_t_top(self) + cdef Integer pow_Integer(self, long n) noexcept + cdef mpz_srcptr pow_mpz_t_top(self) noexcept cdef mpz_srcptr pow_mpz_t_tmp(self, long n) except NULL cdef mpz_t temp_m diff --git a/src/sage/rings/padics/pow_computer.pyx b/src/sage/rings/padics/pow_computer.pyx index 4c05f1886b5..4753be2c6ee 100644 --- a/src/sage/rings/padics/pow_computer.pyx +++ b/src/sage/rings/padics/pow_computer.pyx @@ -146,7 +146,7 @@ cdef class PowComputer_class(SageObject): return richcmp(s.in_field, o.in_field, op) - cdef Integer pow_Integer(self, long n): + cdef Integer pow_Integer(self, long n) noexcept: """ Returns self.prime^n @@ -280,7 +280,7 @@ cdef class PowComputer_class(SageObject): mpz_set(ans.value, self.pow_mpz_t_tmp(mpz_get_si(_n.value))) return ans - cdef mpz_srcptr pow_mpz_t_top(self): + cdef mpz_srcptr pow_mpz_t_top(self) noexcept: """ Returns a pointer to self.prime^self.prec_cap as an ``mpz_srcptr``. @@ -549,7 +549,7 @@ cdef class PowComputer_base(PowComputer_class): """ return PowComputer, (self.prime, self.cache_limit, self.prec_cap, self.in_field) - cdef mpz_srcptr pow_mpz_t_top(self): + cdef mpz_srcptr pow_mpz_t_top(self) noexcept: """ Returns a pointer to self.prime^self.prec_cap as an ``mpz_srcptr``. @@ -594,7 +594,7 @@ cdef class PowComputer_base(PowComputer_class): return self.temp_m pow_comp_cache = {} -cdef PowComputer_base PowComputer_c(Integer m, Integer cache_limit, Integer prec_cap, in_field, prec_type=None): +cdef PowComputer_base PowComputer_c(Integer m, Integer cache_limit, Integer prec_cap, in_field, prec_type=None) noexcept: """ Returns a PowComputer. diff --git a/src/sage/rings/padics/pow_computer_ext.pxd b/src/sage/rings/padics/pow_computer_ext.pxd index 114696b34fa..e4eca660bb3 100644 --- a/src/sage/rings/padics/pow_computer_ext.pxd +++ b/src/sage/rings/padics/pow_computer_ext.pxd @@ -16,23 +16,23 @@ cdef class PowComputer_ext(PowComputer_class): cdef object _ext_type cdef ZZ_c* pow_ZZ_tmp(self, long n) except NULL - cdef ZZ_c* pow_ZZ_top(self) + cdef ZZ_c* pow_ZZ_top(self) noexcept - cdef void cleanup_ext(self) + cdef void cleanup_ext(self) noexcept cdef class PowComputer_ZZ_pX(PowComputer_ext): - cdef ntl_ZZ_pContext_class get_context(self, long n) - cdef ntl_ZZ_pContext_class get_context_capdiv(self, long n) - cdef ntl_ZZ_pContext_class get_top_context(self) - cdef restore_context(self, long n) - cdef restore_context_capdiv(self, long n) - cdef void restore_top_context(self) - cdef ZZ_pX_Modulus_c* get_modulus(self, long n) - cdef ZZ_pX_Modulus_c* get_modulus_capdiv(self, long n) - cdef ZZ_pX_Modulus_c* get_top_modulus(self) + cdef ntl_ZZ_pContext_class get_context(self, long n) noexcept + cdef ntl_ZZ_pContext_class get_context_capdiv(self, long n) noexcept + cdef ntl_ZZ_pContext_class get_top_context(self) noexcept + cdef restore_context(self, long n) noexcept + cdef restore_context_capdiv(self, long n) noexcept + cdef void restore_top_context(self) noexcept + cdef ZZ_pX_Modulus_c* get_modulus(self, long n) noexcept + cdef ZZ_pX_Modulus_c* get_modulus_capdiv(self, long n) noexcept + cdef ZZ_pX_Modulus_c* get_top_modulus(self) noexcept cdef int eis_shift(self, ZZ_pX_c* x, ZZ_pX_c* a, long n, long finalprec) except -1 cdef int eis_shift_capdiv(self, ZZ_pX_c* x, ZZ_pX_c* a, long n, long finalprec) except -1 - cdef long capdiv(self, long n) + cdef long capdiv(self, long n) noexcept cdef int teichmuller_set_c (self, ZZ_pX_c* x, ZZ_pX_c* a, long absprec) except -1 cdef class PowComputer_ZZ_pX_FM(PowComputer_ZZ_pX): @@ -45,13 +45,13 @@ cdef class PowComputer_ZZ_pX_FM_Eis(PowComputer_ZZ_pX_FM): cdef ZZ_pX_Multiplier_c* low_shifter cdef ZZ_pX_Multiplier_c* high_shifter - cdef void cleanup_ZZ_pX_FM_Eis(self) + cdef void cleanup_ZZ_pX_FM_Eis(self) noexcept cdef class PowComputer_ZZ_pX_small(PowComputer_ZZ_pX): cdef object c # using a python list so that we can store ntl_ZZ_pContext_class objects cdef ZZ_pX_Modulus_c *mod - cdef void cleanup_ZZ_pX_small(self) + cdef void cleanup_ZZ_pX_small(self) noexcept cdef class PowComputer_ZZ_pX_small_Eis(PowComputer_ZZ_pX_small): cdef int low_length @@ -59,7 +59,7 @@ cdef class PowComputer_ZZ_pX_small_Eis(PowComputer_ZZ_pX_small): cdef ZZ_pX_c* low_shifter cdef ZZ_pX_c* high_shifter - cdef void cleanup_ZZ_pX_small_Eis(self) + cdef void cleanup_ZZ_pX_small_Eis(self) noexcept cdef class PowComputer_ZZ_pX_big(PowComputer_ZZ_pX): cdef object context_list # using a python list so that we can store ntl_ZZ_pContext_class objects @@ -71,7 +71,7 @@ cdef class PowComputer_ZZ_pX_big(PowComputer_ZZ_pX): cdef object context_dict #currently using a dict, optimize for speed later cdef object modulus_dict #currently using a dict, optimize for speed later - cdef void cleanup_ZZ_pX_big(self) + cdef void cleanup_ZZ_pX_big(self) noexcept cdef class PowComputer_ZZ_pX_big_Eis(PowComputer_ZZ_pX_big): cdef int low_length @@ -79,7 +79,7 @@ cdef class PowComputer_ZZ_pX_big_Eis(PowComputer_ZZ_pX_big): cdef ZZ_pX_c* low_shifter cdef ZZ_pX_c* high_shifter - cdef void cleanup_ZZ_pX_big_Eis(self) + cdef void cleanup_ZZ_pX_big_Eis(self) noexcept #cdef class PowComputer_ZZ_pEX(PowComputer_ext): # cdef ntl_ZZ_pEContext get_context(self, long n) diff --git a/src/sage/rings/padics/pow_computer_ext.pyx b/src/sage/rings/padics/pow_computer_ext.pyx index 3d47d3af2f9..742464a492d 100644 --- a/src/sage/rings/padics/pow_computer_ext.pyx +++ b/src/sage/rings/padics/pow_computer_ext.pyx @@ -537,7 +537,7 @@ cdef class PowComputer_ext(PowComputer_class): mpz_set_si(ram_prec_cap.value, self.ram_prec_cap) return PowComputer_ext_maker, (self.prime, cache_limit, prec_cap, ram_prec_cap, self.in_field, self._poly, self._prec_type, self._ext_type, self._shift_seed) - cdef void cleanup_ext(self): + cdef void cleanup_ext(self) noexcept: """ Frees memory allocated in PowComputer_ext. @@ -674,7 +674,7 @@ cdef class PowComputer_ext(PowComputer_class): return ans - cdef mpz_srcptr pow_mpz_t_top(self): + cdef mpz_srcptr pow_mpz_t_top(self) noexcept: """ Returns self.prime^self.prec_cap as an ``mpz_srcptr``. @@ -687,7 +687,7 @@ cdef class PowComputer_ext(PowComputer_class): ZZ_to_mpz(self.temp_m, &self.top_power) return self.temp_m - cdef ZZ_c* pow_ZZ_top(self): + cdef ZZ_c* pow_ZZ_top(self) noexcept: """ Returns self.prime^self.prec_cap as a ZZ_c. @@ -759,7 +759,7 @@ cdef class PowComputer_ZZ_pX(PowComputer_ext): r.x = (self.get_top_modulus()[0]).val() return r - cdef ntl_ZZ_pContext_class get_context(self, long n): + cdef ntl_ZZ_pContext_class get_context(self, long n) noexcept: """ Returns a ZZ_pContext for self.prime^(abs(n)). @@ -792,7 +792,7 @@ cdef class PowComputer_ZZ_pX(PowComputer_ext): cdef Integer _n = Integer(n) return self.get_context(mpz_get_si(_n.value)) - cdef ntl_ZZ_pContext_class get_context_capdiv(self, long n): + cdef ntl_ZZ_pContext_class get_context_capdiv(self, long n) noexcept: """ Returns a ZZ_pContext for self.prime^((n-1) // self.e + 1) @@ -852,7 +852,7 @@ cdef class PowComputer_ZZ_pX(PowComputer_ext): self.get_modulus(_n) return cputime(t) - cdef ntl_ZZ_pContext_class get_top_context(self): + cdef ntl_ZZ_pContext_class get_top_context(self) noexcept: """ Returns a ZZ_pContext for self.prime^self.prec_cap @@ -876,7 +876,7 @@ cdef class PowComputer_ZZ_pX(PowComputer_ext): """ return self.get_top_context() - cdef restore_context(self, long n): + cdef restore_context(self, long n) noexcept: """ Restores the contest corresponding to self.prime^n @@ -899,7 +899,7 @@ cdef class PowComputer_ZZ_pX(PowComputer_ext): cdef Integer _n = Integer(n) self.restore_context(mpz_get_si(_n.value)) - cdef restore_context_capdiv(self, long n): + cdef restore_context_capdiv(self, long n) noexcept: """ Restores the context for self.prime^((n-1) // self.e + 1) @@ -922,7 +922,7 @@ cdef class PowComputer_ZZ_pX(PowComputer_ext): cdef Integer _n = Integer(n) self.restore_context_capdiv(mpz_get_si(_n.value)) - cdef void restore_top_context(self): + cdef void restore_top_context(self) noexcept: """ Restores the context corresponding to self.prime^self.prec_cap @@ -944,7 +944,7 @@ cdef class PowComputer_ZZ_pX(PowComputer_ext): """ self.restore_top_context() - cdef ZZ_pX_Modulus_c* get_modulus(self, long n): + cdef ZZ_pX_Modulus_c* get_modulus(self, long n) noexcept: """ Returns the modulus corresponding to self.polynomial() (mod self.prime^n) @@ -987,14 +987,14 @@ cdef class PowComputer_ZZ_pX(PowComputer_ext): ZZ_pX_MulMod_pre(r.x, aa.x, bb.x, self.get_modulus(mpz_get_si(n.value))[0]) return r - cdef ZZ_pX_Modulus_c* get_modulus_capdiv(self, long n): + cdef ZZ_pX_Modulus_c* get_modulus_capdiv(self, long n) noexcept: """ Returns the modulus corresponding to self.polynomial() (mod self.prime^((n-1) // self.e + 1) """ return self.get_modulus(self.capdiv(n)) - cdef ZZ_pX_Modulus_c* get_top_modulus(self): + cdef ZZ_pX_Modulus_c* get_top_modulus(self) noexcept: """ Returns the modulus corresponding to self.polynomial() (mod self.prime^self.prec_cap) @@ -1031,7 +1031,7 @@ cdef class PowComputer_ZZ_pX(PowComputer_ext): ZZ_pX_MulMod_pre(ans.x, a.x, b.x, self.get_top_modulus()[0]) return ans - cdef long capdiv(self, long n): + cdef long capdiv(self, long n) noexcept: """ If n >= 0 returns ceil(n / self.e) @@ -1248,7 +1248,7 @@ cdef class PowComputer_ZZ_pX_FM(PowComputer_ZZ_pX): else: raise NotImplementedError("NOT IMPLEMENTED IN PowComputer_ZZ_pX_FM") - cdef ntl_ZZ_pContext_class get_top_context(self): + cdef ntl_ZZ_pContext_class get_top_context(self) noexcept: """ Returns a ZZ_pContext for self.prime^self.prec_cap @@ -1260,7 +1260,7 @@ cdef class PowComputer_ZZ_pX_FM(PowComputer_ZZ_pX): """ return self.c - cdef void restore_top_context(self): + cdef void restore_top_context(self) noexcept: """ Restores the context corresponding to self.prime^self.prec_cap @@ -1271,7 +1271,7 @@ cdef class PowComputer_ZZ_pX_FM(PowComputer_ZZ_pX): """ self.c.restore_c() - cdef ZZ_pX_Modulus_c* get_top_modulus(self): + cdef ZZ_pX_Modulus_c* get_top_modulus(self) noexcept: """ Returns the modulus corresponding to self.polynomial() (mod self.prime^self.prec_cap) @@ -1285,7 +1285,7 @@ cdef class PowComputer_ZZ_pX_FM(PowComputer_ZZ_pX): """ return &self.mod - cdef ZZ_pX_Modulus_c* get_modulus(self, long n): + cdef ZZ_pX_Modulus_c* get_modulus(self, long n) noexcept: """ Duplicates functionality of get_top_modulus if n == self.prec_cap. @@ -1421,7 +1421,7 @@ cdef class PowComputer_ZZ_pX_FM_Eis(PowComputer_ZZ_pX_FM): if self._initialized: self.cleanup_ZZ_pX_FM_Eis() - cdef void cleanup_ZZ_pX_FM_Eis(self): + cdef void cleanup_ZZ_pX_FM_Eis(self) noexcept: """ Does the actual work of deallocating low_shifter and high_shifter. @@ -1609,7 +1609,7 @@ cdef class PowComputer_ZZ_pX_small(PowComputer_ZZ_pX): if self._initialized: self.cleanup_ZZ_pX_small() - cdef void cleanup_ZZ_pX_small(self): + cdef void cleanup_ZZ_pX_small(self) noexcept: """ Deallocates cache of contexts, moduli. @@ -1620,7 +1620,7 @@ cdef class PowComputer_ZZ_pX_small(PowComputer_ZZ_pX): """ Delete_ZZ_pX_Modulus_array(self.mod) - cdef ntl_ZZ_pContext_class get_context(self, long n): + cdef ntl_ZZ_pContext_class get_context(self, long n) noexcept: """ Return the context for p^n. This will use the cache if ``abs(n) <= self.cache_limit``. @@ -1646,7 +1646,7 @@ cdef class PowComputer_ZZ_pX_small(PowComputer_ZZ_pX): except IndexError: return PowComputer_ZZ_pX.get_context(self, n) - cdef restore_context(self, long n): + cdef restore_context(self, long n) noexcept: """ Restore the context for p^n. This will use the cache if ``abs(n) <= self.cache_limit``. @@ -1667,7 +1667,7 @@ cdef class PowComputer_ZZ_pX_small(PowComputer_ZZ_pX): except IndexError: (PowComputer_ZZ_pX.get_context(self, n)).restore_c() - cdef ntl_ZZ_pContext_class get_top_context(self): + cdef ntl_ZZ_pContext_class get_top_context(self) noexcept: """ Returns a ZZ_pContext for self.prime^self.prec_cap @@ -1679,7 +1679,7 @@ cdef class PowComputer_ZZ_pX_small(PowComputer_ZZ_pX): """ return self.c[self.prec_cap] - cdef void restore_top_context(self): + cdef void restore_top_context(self) noexcept: """ Restores the context corresponding to self.prime^self.prec_cap @@ -1690,7 +1690,7 @@ cdef class PowComputer_ZZ_pX_small(PowComputer_ZZ_pX): """ (self.c[self.prec_cap]).restore_c() - cdef ZZ_pX_Modulus_c* get_modulus(self, long n): + cdef ZZ_pX_Modulus_c* get_modulus(self, long n) noexcept: """ Returns the modulus corresponding to self.polynomial() (mod self.prime^n). @@ -1718,7 +1718,7 @@ cdef class PowComputer_ZZ_pX_small(PowComputer_ZZ_pX): ZZ_pX_Modulus_build(self.mod[self.prec_cap+1], tmp) return &(self.mod[self.prec_cap+1]) - cdef ZZ_pX_Modulus_c* get_top_modulus(self): + cdef ZZ_pX_Modulus_c* get_top_modulus(self) noexcept: """ Returns the modulus corresponding to self.polynomial() (mod self.prime^self.prec_cap) @@ -1853,7 +1853,7 @@ cdef class PowComputer_ZZ_pX_small_Eis(PowComputer_ZZ_pX_small): if self._initialized: self.cleanup_ZZ_pX_small_Eis() - cdef void cleanup_ZZ_pX_small_Eis(self): + cdef void cleanup_ZZ_pX_small_Eis(self) noexcept: """ Does the actual work of deallocating low_shifter and high_shifter. @@ -1976,7 +1976,7 @@ cdef class PowComputer_ZZ_pX_big(PowComputer_ZZ_pX): if self._initialized: self.cleanup_ZZ_pX_big() - cdef void cleanup_ZZ_pX_big(self): + cdef void cleanup_ZZ_pX_big(self) noexcept: """ Deallocates the stored moduli and contexts. @@ -2043,7 +2043,7 @@ cdef class PowComputer_ZZ_pX_big(PowComputer_ZZ_pX): """ return self.modulus_dict - cdef ntl_ZZ_pContext_class get_context(self, long n): + cdef ntl_ZZ_pContext_class get_context(self, long n) noexcept: """ Returns the context for p^n. @@ -2079,7 +2079,7 @@ cdef class PowComputer_ZZ_pX_big(PowComputer_ZZ_pX): self.context_dict[n] = PowComputer_ZZ_pX.get_context(self, n) return self.context_dict[n] - cdef ntl_ZZ_pContext_class get_top_context(self): + cdef ntl_ZZ_pContext_class get_top_context(self) noexcept: """ Returns a ZZ_pContext for self.prime^self.prec_cap @@ -2091,7 +2091,7 @@ cdef class PowComputer_ZZ_pX_big(PowComputer_ZZ_pX): """ return self.top_context - cdef void restore_top_context(self): + cdef void restore_top_context(self) noexcept: """ Restores the context corresponding to self.prime^self.prec_cap @@ -2102,7 +2102,7 @@ cdef class PowComputer_ZZ_pX_big(PowComputer_ZZ_pX): """ self.top_context.restore_c() - cdef ZZ_pX_Modulus_c* get_modulus(self, long n): + cdef ZZ_pX_Modulus_c* get_modulus(self, long n) noexcept: """ Returns the modulus corresponding to self.polynomial() (mod self.prime^n). @@ -2149,7 +2149,7 @@ cdef class PowComputer_ZZ_pX_big(PowComputer_ZZ_pX): self.modulus_dict[n] = holder return &(holder.x) - cdef ZZ_pX_Modulus_c* get_top_modulus(self): + cdef ZZ_pX_Modulus_c* get_top_modulus(self) noexcept: """ Returns the modulus corresponding to self.polynomial() (mod self.prime^self.prec_cap) @@ -2284,7 +2284,7 @@ cdef class PowComputer_ZZ_pX_big_Eis(PowComputer_ZZ_pX_big): if self._initialized: self.cleanup_ZZ_pX_big_Eis() - cdef void cleanup_ZZ_pX_big_Eis(self): + cdef void cleanup_ZZ_pX_big_Eis(self) noexcept: """ Does the actual work of deallocating low_shifter and high_shifter. diff --git a/src/sage/rings/padics/pow_computer_flint.pxd b/src/sage/rings/padics/pow_computer_flint.pxd index eb89afae07d..83185ec9cc9 100644 --- a/src/sage/rings/padics/pow_computer_flint.pxd +++ b/src/sage/rings/padics/pow_computer_flint.pxd @@ -11,7 +11,7 @@ cdef class PowComputer_flint(PowComputer_class): cdef mpz_t top_power cdef fmpz_t* pow_fmpz_t_tmp(self, unsigned long n) except NULL - cdef unsigned long capdiv(self, unsigned long n) + cdef unsigned long capdiv(self, unsigned long n) noexcept cdef fmpz_t tfmpz @@ -21,9 +21,9 @@ cdef class PowComputer_flint_1step(PowComputer_flint): cdef fmpz_poly_t powhelper_oneunit cdef fmpz_poly_t powhelper_teichdiff cdef fmpz_poly_t* _moduli - cdef fmpz_poly_t* get_modulus(self, unsigned long n) - cdef fmpz_poly_t* get_modulus_capdiv(self, unsigned long n) - cdef _new_fmpz_poly(self, fmpz_poly_t value, var=*) + cdef fmpz_poly_t* get_modulus(self, unsigned long n) noexcept + cdef fmpz_poly_t* get_modulus_capdiv(self, unsigned long n) noexcept + cdef _new_fmpz_poly(self, fmpz_poly_t value, var=*) noexcept cdef class PowComputer_flint_unram(PowComputer_flint_1step): # WARNING: diff --git a/src/sage/rings/padics/pow_computer_flint.pyx b/src/sage/rings/padics/pow_computer_flint.pyx index e521ea6e078..2525a8bd040 100644 --- a/src/sage/rings/padics/pow_computer_flint.pyx +++ b/src/sage/rings/padics/pow_computer_flint.pyx @@ -149,14 +149,14 @@ cdef class PowComputer_flint(PowComputer_class): fmpz_get_mpz(self.temp_m, self.pow_fmpz_t_tmp(n)[0]) return self.temp_m - cdef mpz_srcptr pow_mpz_t_top(self): + cdef mpz_srcptr pow_mpz_t_top(self) noexcept: """ Returns a pointer to an ``mpz_t`` holding `p^N`, where `N` is the precision cap. """ return self.top_power - cdef unsigned long capdiv(self, unsigned long n): + cdef unsigned long capdiv(self, unsigned long n) noexcept: """ Returns ceil(n / e). """ @@ -367,7 +367,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint): return NotImplemented return False - cdef fmpz_poly_t* get_modulus(self, unsigned long k): + cdef fmpz_poly_t* get_modulus(self, unsigned long k) noexcept: """ Return the defining polynomial reduced modulo `p^k`. @@ -385,7 +385,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint): self.pow_fmpz_t_tmp(k)[0]) return &(self._moduli[c]) - cdef fmpz_poly_t* get_modulus_capdiv(self, unsigned long k): + cdef fmpz_poly_t* get_modulus_capdiv(self, unsigned long k) noexcept: """ Returns the defining polynomial reduced modulo `p^a`, where `a` is the ceiling of `k/e`. @@ -432,7 +432,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint): fmpz_poly_set(ans._poly, self.get_modulus(_n)[0]) return ans - cdef _new_fmpz_poly(self, fmpz_poly_t value, var='x'): + cdef _new_fmpz_poly(self, fmpz_poly_t value, var='x') noexcept: """ Returns a polynomial with the value stored in ``value`` and variable name ``var``. diff --git a/src/sage/rings/padics/pow_computer_relative.pxd b/src/sage/rings/padics/pow_computer_relative.pxd index e0e5aa5600e..9bc6f1b487a 100644 --- a/src/sage/rings/padics/pow_computer_relative.pxd +++ b/src/sage/rings/padics/pow_computer_relative.pxd @@ -20,10 +20,10 @@ cdef class PowComputer_relative(PowComputer_class): # allow cached methods cdef public dict _cached_methods - cdef unsigned long capdiv(self, unsigned long n) + cdef unsigned long capdiv(self, unsigned long n) noexcept cdef class PowComputer_relative_eis(PowComputer_relative): # (x^e - modulus)/p cdef public Polynomial_generic_dense _shift_seed cdef public Polynomial_generic_dense _inv_shift_seed - cpdef Polynomial_generic_dense invert(self, Polynomial_generic_dense element, long prec) + cpdef Polynomial_generic_dense invert(self, Polynomial_generic_dense element, long prec) noexcept diff --git a/src/sage/rings/padics/pow_computer_relative.pyx b/src/sage/rings/padics/pow_computer_relative.pyx index fc51eb3410f..88f39e6ffe6 100644 --- a/src/sage/rings/padics/pow_computer_relative.pyx +++ b/src/sage/rings/padics/pow_computer_relative.pyx @@ -152,7 +152,7 @@ cdef class PowComputer_relative(PowComputer_class): """ return "Relative PowComputer for modulus %s" % (self.modulus,) - cdef unsigned long capdiv(self, unsigned long n): + cdef unsigned long capdiv(self, unsigned long n) noexcept: r""" Return `\lceil n/e \rceil`. """ @@ -219,7 +219,7 @@ cdef class PowComputer_relative_eis(PowComputer_relative): PowComputer_relative.__init__(self, prime, cache_limit, prec_cap, ram_prec_cap, in_field, poly, shift_seed) self._inv_shift_seed = self.invert(shift_seed, self.ram_prec_cap) - cpdef Polynomial_generic_dense invert(self, Polynomial_generic_dense a, long prec): + cpdef Polynomial_generic_dense invert(self, Polynomial_generic_dense a, long prec) noexcept: r""" Return the inverse of ``a``. diff --git a/src/sage/rings/padics/relaxed_template.pxi b/src/sage/rings/padics/relaxed_template.pxi index 751e42700f0..6e0fd4fac50 100644 --- a/src/sage/rings/padics/relaxed_template.pxi +++ b/src/sage/rings/padics/relaxed_template.pxi @@ -123,7 +123,7 @@ cdef class RelaxedElement(pAdicGenericElement): """ return p == self._parent.prime() - cdef cdigit_ptr _getdigit_relative(self, long i): + cdef cdigit_ptr _getdigit_relative(self, long i) noexcept: r""" Return a pointer on the `i`-th significant digit of this number. @@ -139,7 +139,7 @@ cdef class RelaxedElement(pAdicGenericElement): """ pass - cdef cdigit_ptr _getdigit_absolute(self, long i): + cdef cdigit_ptr _getdigit_absolute(self, long i) noexcept: r""" Return a pointer on the digit in position `i` of this number. @@ -156,7 +156,7 @@ cdef class RelaxedElement(pAdicGenericElement): """ pass - cdef void _getslice_relative(self, celement slice, long start, long length): + cdef void _getslice_relative(self, celement slice, long start, long length) noexcept: r""" Select a slice of the digits of this number. @@ -177,7 +177,7 @@ cdef class RelaxedElement(pAdicGenericElement): """ pass - cdef int _next_c(self): + cdef int _next_c(self) noexcept: r""" Compute the next digit of this number. @@ -197,7 +197,7 @@ cdef class RelaxedElement(pAdicGenericElement): """ raise NotImplementedError("must be implemented in subclasses") - cdef int _jump_c(self, long prec): + cdef int _jump_c(self, long prec) noexcept: r""" Compute the digits of this number until the absolute precision ``prec``. @@ -219,7 +219,7 @@ cdef class RelaxedElement(pAdicGenericElement): return ERROR_PRECISION return 0 - cdef int _jump_relative_c(self, long prec, long halt): + cdef int _jump_relative_c(self, long prec, long halt) noexcept: r""" Compute the digits of this number until the relative precision ``prec``. @@ -1317,7 +1317,7 @@ cdef class RelaxedElement(pAdicGenericElement): ans._init_jump() return ans - cdef long valuation_c(self, long halt=-maxordp): + cdef long valuation_c(self, long halt=-maxordp) noexcept: r""" Return the best lower bound we have on the valuation of this element at the current stage of the computation. @@ -1709,7 +1709,7 @@ cdef class RelaxedElement(pAdicGenericElement): """ return self.__rshift__(-s) - cpdef _add_(self, other): + cpdef _add_(self, other) noexcept: r""" Return the sum of this element with ``other``. @@ -1728,7 +1728,7 @@ cdef class RelaxedElement(pAdicGenericElement): return self return element_class_add(self._parent, self, other) - cpdef _sub_(self, other): + cpdef _sub_(self, other) noexcept: r""" Return the difference of this element and ``other``. @@ -1750,7 +1750,7 @@ cdef class RelaxedElement(pAdicGenericElement): return self return element_class_sub(self._parent, self, other) - cpdef _neg_(self): + cpdef _neg_(self) noexcept: r""" Return the opposite of this element. @@ -1767,7 +1767,7 @@ cdef class RelaxedElement(pAdicGenericElement): return self return element_class_sub(self._parent, self._parent.zero(), self) - cpdef _mul_(self, other): + cpdef _mul_(self, other) noexcept: r""" Return the product of this element with ``other``. @@ -1789,7 +1789,7 @@ cdef class RelaxedElement(pAdicGenericElement): return other return element_class_mul(self._parent, self, other) - cpdef _div_(self, other): + cpdef _div_(self, other) noexcept: r""" Return the quotient if this element by ``other``. @@ -2054,7 +2054,7 @@ cdef class RelaxedElement_abandon(RelaxedElement): """ self._valuation = -maxordp - cdef int _next_c(self): + cdef int _next_c(self) noexcept: r""" Compute the next digit of this element. @@ -2082,21 +2082,21 @@ cdef class RelaxedElementWithDigits(RelaxedElement): """ element_clear(self._digits) - cdef cdigit_ptr _getdigit_relative(self, long i): + cdef cdigit_ptr _getdigit_relative(self, long i) noexcept: r""" Return a pointer on the `i`-th digit of this number in relative precision. """ return element_get_digit(self._digits, i) - cdef cdigit_ptr _getdigit_absolute(self, long i): + cdef cdigit_ptr _getdigit_absolute(self, long i) noexcept: r""" Return a pointer on the `i`-th digit of this number in absolute precision. """ return element_get_digit(self._digits, i - self._valuation) - cdef void _getslice_relative(self, celement slice, long start, long length): + cdef void _getslice_relative(self, celement slice, long start, long length) noexcept: r""" Select a slice of the sequence of digits of this element. @@ -2170,21 +2170,21 @@ cdef class RelaxedElement_zero(RelaxedElement): """ return self.__class__, (self._parent,) - cdef cdigit_ptr _getdigit_relative(self, long i): + cdef cdigit_ptr _getdigit_relative(self, long i) noexcept: r""" Return a pointer on the `i`-th digit of this number in relative precision. """ return digit_zero - cdef cdigit_ptr _getdigit_absolute(self, long i): + cdef cdigit_ptr _getdigit_absolute(self, long i) noexcept: r""" Return a pointer on the `i`-th digit of this number in absolute precision. """ return digit_zero - cdef void _getslice_relative(self, celement slice, long start, long length): + cdef void _getslice_relative(self, celement slice, long start, long length) noexcept: r""" Select a slice of the sequence of digits of this element. @@ -2198,7 +2198,7 @@ cdef class RelaxedElement_zero(RelaxedElement): """ element_init(slice) - cdef int _jump_c(self, long prec): + cdef int _jump_c(self, long prec) noexcept: r""" Compute the digits of this number until the absolute precision ``prec``. @@ -2212,7 +2212,7 @@ cdef class RelaxedElement_zero(RelaxedElement): """ return 0 - cdef int _next_c(self): + cdef int _next_c(self) noexcept: r""" Compute the next digit of this number. @@ -2274,7 +2274,7 @@ cdef class RelaxedElement_one(RelaxedElementWithDigits): """ return self.__class__, (self._parent,) - cdef int _jump_c(self, long prec): + cdef int _jump_c(self, long prec) noexcept: r""" Compute the digits of this number until the absolute precision ``prec``. @@ -2290,7 +2290,7 @@ cdef class RelaxedElement_one(RelaxedElementWithDigits): self._precrel = prec return 0 - cdef int _next_c(self): + cdef int _next_c(self) noexcept: r""" Compute the next digit of this number. @@ -2366,21 +2366,21 @@ cdef class RelaxedElement_bound(RelaxedElement): """ return self.__class__, (self._parent, self._x, self._precbound) - cdef cdigit_ptr _getdigit_relative(self, long i): + cdef cdigit_ptr _getdigit_relative(self, long i) noexcept: r""" Return a pointer on the `i`-th digit of this number in relative precision. """ return self._x._getdigit_relative(i) - cdef cdigit_ptr _getdigit_absolute(self, long i): + cdef cdigit_ptr _getdigit_absolute(self, long i) noexcept: r""" Return a pointer on the `i`-th digit of this number in absolute precision. """ return self._x._getdigit_absolute(i) - cdef void _getslice_relative(self, celement slice, long start, long length): + cdef void _getslice_relative(self, celement slice, long start, long length) noexcept: r""" Select a slice of the digits of this number. @@ -2401,7 +2401,7 @@ cdef class RelaxedElement_bound(RelaxedElement): """ self._x._getslice_relative(slice, start, length) - cdef int _jump_c(self, long prec): + cdef int _jump_c(self, long prec) noexcept: r""" Jump to the absolute precision ``prec``. @@ -2424,7 +2424,7 @@ cdef class RelaxedElement_bound(RelaxedElement): self._precrel = min(x._precrel, self._precbound - self._valuation) return error - cdef int _next_c(self): + cdef int _next_c(self) noexcept: r""" Jump to the next digit. @@ -2507,7 +2507,7 @@ cdef class RelaxedElement_value(RelaxedElementWithDigits): """ return self.__class__, (self._parent, self._value, self._shift, self._precbound) - cdef int _jump_c(self, long prec): + cdef int _jump_c(self, long prec) noexcept: r""" Compute the digits of this number until the absolute precision ``prec``. @@ -2531,7 +2531,7 @@ cdef class RelaxedElement_value(RelaxedElementWithDigits): return ERROR_OVERFLOW return 0 - cdef int _next_c(self): + cdef int _next_c(self) noexcept: r""" Compute the next digit of this number. @@ -2648,7 +2648,7 @@ cdef class RelaxedElement_random(RelaxedElementWithDigits): """ return self.__class__, (self._parent, self._initialvaluation, self._precbound, self._seed) - cdef int _next_c(self): + cdef int _next_c(self) noexcept: r""" Generate the next digit of this number at random. @@ -2746,14 +2746,14 @@ cdef class RelaxedElement_slice(RelaxedElement): """ return self.__class__, (self._parent, self._x, self._start, self._stop, self._shift) - cdef cdigit_ptr _getdigit_relative(self, long i): + cdef cdigit_ptr _getdigit_relative(self, long i) noexcept: r""" Return a pointer on the `i`-th digit of this number in relative precision. """ return self._getdigit_absolute(i + self._valuation) - cdef cdigit_ptr _getdigit_absolute(self, long i): + cdef cdigit_ptr _getdigit_absolute(self, long i) noexcept: r""" Return a pointer on the `i`-th digit of this number in absolute precision. @@ -2764,7 +2764,7 @@ cdef class RelaxedElement_slice(RelaxedElement): else: return self._x._getdigit_absolute(j) - cdef void _getslice_relative(self, celement slice, long start, long length): + cdef void _getslice_relative(self, celement slice, long start, long length) noexcept: r""" Select a slice of the sequence of digits of this element. @@ -2788,7 +2788,7 @@ cdef class RelaxedElement_slice(RelaxedElement): cdef long stop_absolute = min(self._stop, s + length) x._getslice_relative(slice, start_absolute - x._valuation, stop_absolute - start_absolute) - cdef int _jump_c(self, long prec): + cdef int _jump_c(self, long prec) noexcept: r""" Jump to the absolute precision ``prec``. @@ -2820,7 +2820,7 @@ cdef class RelaxedElement_slice(RelaxedElement): self._precrel = prec - self._valuation return error - cdef int _next_c(self): + cdef int _next_c(self) noexcept: r""" Jump to the next digit. @@ -2895,7 +2895,7 @@ cdef class RelaxedElement_add(RelaxedElementWithDigits): """ return self.__class__, (self._parent, self._x, self._y) - cdef int _jump_c(self, long prec): + cdef int _jump_c(self, long prec) noexcept: r""" Compute the digits of this number until the absolute precision ``prec``. @@ -2925,7 +2925,7 @@ cdef class RelaxedElement_add(RelaxedElementWithDigits): n += 1 return error - cdef int _next_c(self): + cdef int _next_c(self) noexcept: r""" Compute the next digit of this number. @@ -3002,7 +3002,7 @@ cdef class RelaxedElement_sub(RelaxedElementWithDigits): """ return self.__class__, (self._parent, self._x, self._y) - cdef int _jump_c(self, long prec): + cdef int _jump_c(self, long prec) noexcept: r""" Compute the digits of this number until the absolute precision ``prec``. @@ -3032,7 +3032,7 @@ cdef class RelaxedElement_sub(RelaxedElementWithDigits): n += 1 return error - cdef int _next_c(self): + cdef int _next_c(self) noexcept: r""" Compute the next digit of this number. @@ -3137,7 +3137,7 @@ cdef class RelaxedElement_mul(RelaxedElementWithDigits): """ return self.__class__, (self._parent, self._x, self._y) - cdef int _next_c(self): + cdef int _next_c(self) noexcept: r""" Compute the next digit of this number. @@ -3191,7 +3191,7 @@ cdef class RelaxedElement_mul(RelaxedElementWithDigits): self._precrel += 1 return 0 - cdef int _update_last_digit(self): + cdef int _update_last_digit(self) noexcept: r""" Redo the computation of the last digit and update carries accordingly. @@ -3259,7 +3259,7 @@ cdef class RelaxedElement_muldigit(RelaxedElementWithDigits): self._valuation = y._valuation self._init_jump() - cdef int _next_c(self): + cdef int _next_c(self) noexcept: r""" Compute the next digit of this number. @@ -3379,7 +3379,7 @@ cdef class RelaxedElement_div(RelaxedElementWithDigits): """ return self.__class__, (self._parent, self._num, self._denom, self._valuation, self._precbound) - cdef int _bootstrap_c(self): + cdef int _bootstrap_c(self) noexcept: r""" Bootstrap the computation of the digits of this element, that is: @@ -3425,7 +3425,7 @@ cdef class RelaxedElement_div(RelaxedElementWithDigits): self._definition = element_class_sub(parent, a, d) return 0 - cdef int _next_c(self): + cdef int _next_c(self) noexcept: r""" Compute the next digit of this number. @@ -3524,7 +3524,7 @@ cdef class RelaxedElement_sqrt(RelaxedElementWithDigits): """ return self.__class__, (self._parent, self._x) - cdef int _bootstrap_c(self): + cdef int _bootstrap_c(self) noexcept: r""" Bootstrap the computation of the digits of this element, that is: @@ -3606,7 +3606,7 @@ cdef class RelaxedElement_sqrt(RelaxedElementWithDigits): self._definition = (y + c - u*u) / d return 0 - cdef int _next_c(self): + cdef int _next_c(self) noexcept: r""" Compute the next digit of this number. @@ -3710,7 +3710,7 @@ cdef class RelaxedElement_teichmuller(RelaxedElementWithDigits): xbar = digit_get_sage(element_get_digit(self._digits, 0)) return self.__class__, (self._parent, xbar) - cdef int _jump_c(self, long prec): + cdef int _jump_c(self, long prec) noexcept: r""" Compute the digits of this number until the absolute precision ``prec``. @@ -3730,7 +3730,7 @@ cdef class RelaxedElement_teichmuller(RelaxedElementWithDigits): return 0 return RelaxedElement._jump_c(self, prec) - cdef int _next_c(self): + cdef int _next_c(self) noexcept: r""" Compute the next digit of this number. @@ -3837,7 +3837,7 @@ cdef class RelaxedElement_unknown(RelaxedElementWithDigits): definition = self._definition return unpickle_unknown, (id(self), self.__class__, self._parent, self._initialvaluation, digits, definition) - cpdef set(self, RelaxedElement definition): + cpdef set(self, RelaxedElement definition) noexcept: r""" Set the recursive definition of this self-referent number. @@ -3901,7 +3901,7 @@ cdef class RelaxedElement_unknown(RelaxedElementWithDigits): self._init_jump() return eq - cdef int _next_c(self): + cdef int _next_c(self) noexcept: r""" Compute the next digit of this number. @@ -3991,20 +3991,20 @@ cdef class RelaxedElement_zeroone(RelaxedElementWithDigits): RelaxedElement.__init__(self, parent) self._valuation = valuation - cdef void _setdigit_to_zero(self): + cdef void _setdigit_to_zero(self) noexcept: r""" Append `0` to the list of digits of this element. """ self._precrel += 1 - cdef void _setdigit_to_one(self): + cdef void _setdigit_to_one(self) noexcept: r""" Append `1` to the list of digits of this element. """ element_set_digit_ui(self._digits, 1, self._precrel) self._precrel += 1 - cdef int _jump_c(self, long prec): + cdef int _jump_c(self, long prec) noexcept: r""" Jump to the absolute precision ``prec``. @@ -4020,7 +4020,7 @@ cdef class RelaxedElement_zeroone(RelaxedElementWithDigits): return ERROR_NOTDEFINED return 0 - cdef int _next_c(self): + cdef int _next_c(self) noexcept: r""" Jump to the next digit. @@ -4154,7 +4154,7 @@ cdef class ExpansionIter(): """ return self - cdef _next_simple(self): + cdef _next_simple(self) noexcept: r""" Return the next digit of this expansion (simple mode). """ @@ -4164,7 +4164,7 @@ cdef class ExpansionIter(): self.current += 1 return digit_get_sage(self.digit) - cdef _next_smallest(self): + cdef _next_smallest(self) noexcept: r""" Return the next digit of this expansion (smallest mode). """ @@ -4175,7 +4175,7 @@ cdef class ExpansionIter(): self.current += 1 return digit_get_sage(self.digit) - cdef _next_teichmuller(self): + cdef _next_teichmuller(self) noexcept: r""" Return the next digit of this expansion (Teichmüller mode). """ diff --git a/src/sage/rings/padics/relaxed_template_header.pxi b/src/sage/rings/padics/relaxed_template_header.pxi index 5425c11c45d..1baa4bfdbe7 100644 --- a/src/sage/rings/padics/relaxed_template_header.pxi +++ b/src/sage/rings/padics/relaxed_template_header.pxi @@ -34,16 +34,16 @@ cdef class RelaxedElement(pAdicGenericElement): cdef long _precbound cdef PowComputer_class prime_pow - cdef cdigit_ptr _getdigit_relative(self, long i) - cdef cdigit_ptr _getdigit_absolute(self, long i) - cdef void _getslice_relative(self, celement slice, long start, long length) + cdef cdigit_ptr _getdigit_relative(self, long i) noexcept + cdef cdigit_ptr _getdigit_absolute(self, long i) noexcept + cdef void _getslice_relative(self, celement slice, long start, long length) noexcept cdef int _init_jump(self) except -1 - cdef int _jump_c(self, long prec) - cdef int _jump_relative_c(self, long prec, long halt) - cdef int _next_c(self) + cdef int _jump_c(self, long prec) noexcept + cdef int _jump_relative_c(self, long prec, long halt) noexcept + cdef int _next_c(self) noexcept - cdef long valuation_c(self, long halt=*) + cdef long valuation_c(self, long halt=*) noexcept cdef bint _is_equal(self, RelaxedElement right, long prec, bint permissive) except -1 cdef class RelaxedElement_abandon(RelaxedElement): @@ -98,7 +98,7 @@ cdef class RelaxedElement_mul(RelaxedElementWithDigits): cdef cdigit _lastdigit_x cdef RelaxedElement _y cdef cdigit _lastdigit_y - cdef int _update_last_digit(self) + cdef int _update_last_digit(self) noexcept cdef class RelaxedElement_muldigit(RelaxedElementWithDigits): cdef cdigit_ptr _x @@ -110,13 +110,13 @@ cdef class RelaxedElement_div(RelaxedElementWithDigits): cdef RelaxedElement _num cdef RelaxedElement _denom cdef RelaxedElement _definition - cdef int _bootstrap_c(self) + cdef int _bootstrap_c(self) noexcept cdef bint _bootstraping cdef class RelaxedElement_sqrt(RelaxedElementWithDigits): cdef RelaxedElement _x cdef RelaxedElement _definition - cdef int _bootstrap_c(self) + cdef int _bootstrap_c(self) noexcept cdef class RelaxedElement_teichmuller(RelaxedElementWithDigits): cdef bint _ready @@ -130,7 +130,7 @@ cdef class RelaxedElement_teichmuller(RelaxedElementWithDigits): cdef class RelaxedElement_unknown(RelaxedElementWithDigits): cdef RelaxedElement _definition cdef long _next - cpdef set(self, RelaxedElement definition) + cpdef set(self, RelaxedElement definition) noexcept # for pickling cdef long _initialvaluation cdef long _initialprecrel @@ -138,8 +138,8 @@ cdef class RelaxedElement_unknown(RelaxedElementWithDigits): # Expansion cdef class RelaxedElement_zeroone(RelaxedElementWithDigits): - cdef void _setdigit_to_zero(self) - cdef void _setdigit_to_one(self) + cdef void _setdigit_to_zero(self) noexcept + cdef void _setdigit_to_one(self) noexcept cdef class ExpansionIter(): cdef RelaxedElement elt @@ -149,11 +149,11 @@ cdef class ExpansionIter(): cdef long current cdef cdigit digit # simple mode - cdef _next_simple(self) + cdef _next_simple(self) noexcept # smallest mode cdef cdigit carry - cdef _next_smallest(self) + cdef _next_smallest(self) noexcept # teichmuller mode cdef RelaxedElement tail cdef dict coefficients - cdef _next_teichmuller(self) + cdef _next_teichmuller(self) noexcept diff --git a/src/sage/rings/polynomial/evaluation_flint.pxd b/src/sage/rings/polynomial/evaluation_flint.pxd index b699871ba0c..4504e8af63c 100644 --- a/src/sage/rings/polynomial/evaluation_flint.pxd +++ b/src/sage/rings/polynomial/evaluation_flint.pxd @@ -2,5 +2,5 @@ from sage.libs.flint.types cimport fmpz_poly_t from sage.libs.mpfr.types cimport mpfr_t from sage.libs.mpfi.types cimport mpfi_t -cdef fmpz_poly_evaluation_mpfr(mpfr_t res, const fmpz_poly_t poly, const mpfr_t a) -cdef fmpz_poly_evaluation_mpfi(mpfi_t res, const fmpz_poly_t poly, const mpfi_t a) +cdef fmpz_poly_evaluation_mpfr(mpfr_t res, const fmpz_poly_t poly, const mpfr_t a) noexcept +cdef fmpz_poly_evaluation_mpfi(mpfi_t res, const fmpz_poly_t poly, const mpfi_t a) noexcept diff --git a/src/sage/rings/polynomial/evaluation_flint.pyx b/src/sage/rings/polynomial/evaluation_flint.pyx index fc75fabd42d..94204c0556b 100644 --- a/src/sage/rings/polynomial/evaluation_flint.pyx +++ b/src/sage/rings/polynomial/evaluation_flint.pyx @@ -34,7 +34,7 @@ from sage.libs.gmp.mpq cimport * from sage.libs.flint.fmpz cimport * from sage.libs.flint.fmpz_poly cimport * -cdef fmpz_poly_evaluation_mpfr(mpfr_t res, const fmpz_poly_t poly, const mpfr_t a): +cdef fmpz_poly_evaluation_mpfr(mpfr_t res, const fmpz_poly_t poly, const mpfr_t a) noexcept: cdef mpz_t c cdef long i @@ -49,7 +49,7 @@ cdef fmpz_poly_evaluation_mpfr(mpfr_t res, const fmpz_poly_t poly, const mpfr_t mpz_clear(c) -cdef fmpz_poly_evaluation_mpfi(mpfi_t res, const fmpz_poly_t poly, const mpfi_t a): +cdef fmpz_poly_evaluation_mpfi(mpfi_t res, const fmpz_poly_t poly, const mpfi_t a) noexcept: cdef mpz_t c cdef long i diff --git a/src/sage/rings/polynomial/evaluation_ntl.pxd b/src/sage/rings/polynomial/evaluation_ntl.pxd index 9af0a0b9d40..4551037ecca 100644 --- a/src/sage/rings/polynomial/evaluation_ntl.pxd +++ b/src/sage/rings/polynomial/evaluation_ntl.pxd @@ -2,5 +2,5 @@ from sage.libs.ntl.types cimport ZZX_c from sage.libs.mpfr.types cimport mpfr_t from sage.libs.mpfi.types cimport mpfi_t -cdef ZZX_evaluation_mpfr(mpfr_t res, ZZX_c poly, const mpfr_t a) -cdef ZZX_evaluation_mpfi(mpfi_t res, ZZX_c poly, const mpfi_t a) +cdef ZZX_evaluation_mpfr(mpfr_t res, ZZX_c poly, const mpfr_t a) noexcept +cdef ZZX_evaluation_mpfi(mpfi_t res, ZZX_c poly, const mpfi_t a) noexcept diff --git a/src/sage/rings/polynomial/evaluation_ntl.pyx b/src/sage/rings/polynomial/evaluation_ntl.pyx index 28b3917d3a1..b6ff4732542 100644 --- a/src/sage/rings/polynomial/evaluation_ntl.pyx +++ b/src/sage/rings/polynomial/evaluation_ntl.pyx @@ -38,7 +38,7 @@ from sage.libs.ntl.ZZ cimport * from sage.libs.ntl.ZZX cimport * -cdef ZZX_evaluation_mpfr(mpfr_t res, ZZX_c poly, const mpfr_t a): +cdef ZZX_evaluation_mpfr(mpfr_t res, ZZX_c poly, const mpfr_t a) noexcept: cdef mpz_t c cdef long i @@ -53,7 +53,7 @@ cdef ZZX_evaluation_mpfr(mpfr_t res, ZZX_c poly, const mpfr_t a): mpz_clear(c) -cdef ZZX_evaluation_mpfi(mpfi_t res, ZZX_c poly, const mpfi_t a): +cdef ZZX_evaluation_mpfi(mpfi_t res, ZZX_c poly, const mpfi_t a) noexcept: cdef mpz_t c cdef long i diff --git a/src/sage/rings/polynomial/groebner_fan.py b/src/sage/rings/polynomial/groebner_fan.py index 7e067a3a087..eb8928d09b5 100644 --- a/src/sage/rings/polynomial/groebner_fan.py +++ b/src/sage/rings/polynomial/groebner_fan.py @@ -1234,7 +1234,7 @@ def homogeneity_space(self): return h def render(self, file=None, larger=False, shift=0, rgbcolor=(0, 0, 0), - polyfill=max_degree, scale_colors=True): + polyfill=True, scale_colors=True): """ Render a Groebner fan as sage graphics or save as an xfig file. @@ -1295,6 +1295,8 @@ def render(self, file=None, larger=False, shift=0, rgbcolor=(0, 0, 0), ... NotImplementedError """ + if polyfill is True: + polyfill = max_degree S = self.__ring if S.ngens() < 3: print("For 2-D fan rendering the polynomial ring must have 3 variables (or more, which are ignored).") diff --git a/src/sage/rings/polynomial/hilbert.pyx b/src/sage/rings/polynomial/hilbert.pyx index d2abf325fd8..754a2bad1b7 100644 --- a/src/sage/rings/polynomial/hilbert.pyx +++ b/src/sage/rings/polynomial/hilbert.pyx @@ -57,7 +57,7 @@ cdef class Node: fmpz_poly_clear(self.RMult) fmpz_poly_clear(self.LeftFHS) -cdef inline size_t median(list v): +cdef inline size_t median(list v) noexcept: """ Specialized version of :func:`from sage.stats.basic_stats.median`. """ @@ -74,7 +74,7 @@ cdef inline size_t median(list v): # cdef functions related with lists of monomials ### -cdef inline bint indivisible_in_list(ETuple m, list L, size_t i): +cdef inline bint indivisible_in_list(ETuple m, list L, size_t i) noexcept: """ Return if ``m`` divisible by any monomial in ``L[:i]``. """ @@ -84,7 +84,7 @@ cdef inline bint indivisible_in_list(ETuple m, list L, size_t i): return False return True -cdef inline list interred(list L): +cdef inline list interred(list L) noexcept: """ Return interreduction of a list of monomials. @@ -116,7 +116,7 @@ cdef inline list interred(list L): result.append(m) return result -cdef list quotient(list L, ETuple m): +cdef list quotient(list L, ETuple m) noexcept: """ Return the quotient of the ideal represented by ``L`` and the monomial represented by ``m``. @@ -127,7 +127,7 @@ cdef list quotient(list L, ETuple m): result.append((PyList_GET_ITEM(L,i)).divide_by_gcd(m)) return interred(result) -cdef list quotient_by_var(list L, size_t index): +cdef list quotient_by_var(list L, size_t index) noexcept: """ Return the quotient of the ideal represented by ``L`` and the variable number ``index``. @@ -140,7 +140,7 @@ cdef list quotient_by_var(list L, size_t index): result.append(( PyList_GET_ITEM(L, i)).divide_by_var(index)) return interred(result) -cdef ETuple sum_from_list(list L, size_t s, size_t l): +cdef ETuple sum_from_list(list L, size_t s, size_t l) noexcept: """ Compute the vector sum of the ETuples in ``L[s:s+l]`` in a balanced way. """ @@ -154,7 +154,7 @@ cdef ETuple sum_from_list(list L, size_t s, size_t l): m2 = sum_from_list(L, s+l2, l-l2) return m1.eadd(m2) -cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w): +cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w) noexcept: """ Try to compute the first Hilbert series of ``D.Id``, or return ``NotImplemented``. @@ -286,7 +286,7 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w): # We are in a truly difficult case and give up for now... return False -cdef make_children(Node D, tuple w): +cdef make_children(Node D, tuple w) noexcept: """ Create child nodes in ``D`` that allow to compute the first Hilbert series of ``D.Id``. diff --git a/src/sage/rings/polynomial/laurent_polynomial.pxd b/src/sage/rings/polynomial/laurent_polynomial.pxd index 8e9107aeb47..d99243aaf3d 100644 --- a/src/sage/rings/polynomial/laurent_polynomial.pxd +++ b/src/sage/rings/polynomial/laurent_polynomial.pxd @@ -2,16 +2,16 @@ from sage.structure.element cimport CommutativeAlgebraElement, ModuleElement, Ri cdef class LaurentPolynomial(CommutativeAlgebraElement): - cdef LaurentPolynomial _new_c(self) - cpdef _add_(self, other) - cpdef _mul_(self, other) - cpdef _floordiv_(self, other) + cdef LaurentPolynomial _new_c(self) noexcept + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept + cpdef _floordiv_(self, other) noexcept cpdef long number_of_terms(self) except -1 - cpdef dict dict(self) + cpdef dict dict(self) noexcept cdef class LaurentPolynomial_univariate(LaurentPolynomial): cdef ModuleElement __u cdef long __n - cpdef _normalize(self) - cpdef _unsafe_mutate(self, i, value) + cpdef _normalize(self) noexcept + cpdef _unsafe_mutate(self, i, value) noexcept diff --git a/src/sage/rings/polynomial/laurent_polynomial.pyx b/src/sage/rings/polynomial/laurent_polynomial.pyx index cf92b0e43d1..9d28ed6a872 100644 --- a/src/sage/rings/polynomial/laurent_polynomial.pyx +++ b/src/sage/rings/polynomial/laurent_polynomial.pyx @@ -21,7 +21,7 @@ cdef class LaurentPolynomial(CommutativeAlgebraElement): """ Base class for Laurent polynomials. """ - cdef LaurentPolynomial _new_c(self): + cdef LaurentPolynomial _new_c(self) noexcept: """ Return a new Laurent polynomial. @@ -37,7 +37,7 @@ cdef class LaurentPolynomial(CommutativeAlgebraElement): ans._parent = self._parent return ans - cpdef _add_(self, other): + cpdef _add_(self, other) noexcept: """ Abstract addition method @@ -52,7 +52,7 @@ cdef class LaurentPolynomial(CommutativeAlgebraElement): """ raise NotImplementedError - cpdef _mul_(self, other): + cpdef _mul_(self, other) noexcept: """ Abstract multiplication method @@ -67,7 +67,7 @@ cdef class LaurentPolynomial(CommutativeAlgebraElement): """ raise NotImplementedError - cpdef _floordiv_(self, other): + cpdef _floordiv_(self, other) noexcept: """ Abstract floor division method @@ -220,7 +220,7 @@ cdef class LaurentPolynomial(CommutativeAlgebraElement): """ return self.number_of_terms() - cpdef dict dict(self): + cpdef dict dict(self) noexcept: """ Abstract ``dict`` method. @@ -531,7 +531,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial): u = u.map_coefficients(base_map) return codomain(u(x) * x**self.__n) - cpdef _normalize(self): + cpdef _normalize(self) noexcept: r""" A Laurent series is a pair `(u(t), n)`, where either `u = 0` (to some precision) or `u` is a unit. This pair corresponds to @@ -840,7 +840,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial): d = {repr(g): R.var(g) for g in self._parent.gens()} return self.subs(**d) - cpdef dict dict(self): + cpdef dict dict(self) noexcept: """ Return a dictionary representing ``self``. @@ -895,7 +895,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial): """ raise IndexError("Laurent polynomials are immutable") - cpdef _unsafe_mutate(self, i, value): + cpdef _unsafe_mutate(self, i, value) noexcept: r""" Sage assumes throughout that commutative ring elements are immutable. This is relevant for caching, etc. But sometimes you @@ -921,7 +921,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial): self.__u = self.__u._parent(coeffs) self._normalize() - cpdef _add_(self, right_m): + cpdef _add_(self, right_m) noexcept: """ Add two Laurent polynomials with the same parent. @@ -975,7 +975,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial): ret._normalize() return ret - cpdef _sub_(self, right_m): + cpdef _sub_(self, right_m) noexcept: """ Subtract two Laurent polynomials with the same parent. @@ -1048,7 +1048,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial): # No need to normalize return ret - cpdef _mul_(self, right_r): + cpdef _mul_(self, right_r) noexcept: """ EXAMPLES:: @@ -1066,7 +1066,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial): ret._normalize() return ret - cpdef _rmul_(self, Element c): + cpdef _rmul_(self, Element c) noexcept: """ EXAMPLES:: @@ -1082,7 +1082,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial): ret._normalize() return ret - cpdef _lmul_(self, Element c): + cpdef _lmul_(self, Element c) noexcept: """ EXAMPLES:: @@ -1152,7 +1152,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial): c = self._parent._R(self.__u.leading_coefficient() ** right) return self._parent.element_class(self._parent, c, self.__n*right) - cpdef _floordiv_(self, rhs): + cpdef _floordiv_(self, rhs) noexcept: """ Perform division with remainder and return the quotient. @@ -1240,7 +1240,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial): # No need to normalize return ret - cpdef _div_(self, rhs): + cpdef _div_(self, rhs) noexcept: """ EXAMPLES:: @@ -1415,7 +1415,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial): qr._normalize() return ql, qr - cpdef _richcmp_(self, right_r, int op): + cpdef _richcmp_(self, right_r, int op) noexcept: r""" Comparison of ``self`` and ``right_r``. diff --git a/src/sage/rings/polynomial/laurent_polynomial_mpair.pxd b/src/sage/rings/polynomial/laurent_polynomial_mpair.pxd index 79f09def6aa..f71ccb57030 100644 --- a/src/sage/rings/polynomial/laurent_polynomial_mpair.pxd +++ b/src/sage/rings/polynomial/laurent_polynomial_mpair.pxd @@ -7,8 +7,8 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): cdef ETuple _mon cdef MPolynomial _poly cdef PolyDict _prod - cdef _compute_polydict(self) - cdef _normalize(self, i=*) - cpdef rescale_vars(self, dict d, h=*, new_ring=*) - cpdef toric_coordinate_change(self, M, h=*, new_ring=*) - cpdef toric_substitute(self, v, v1, a, h=*, new_ring=*) + cdef _compute_polydict(self) noexcept + cdef _normalize(self, i=*) noexcept + cpdef rescale_vars(self, dict d, h=*, new_ring=*) noexcept + cpdef toric_coordinate_change(self, M, h=*, new_ring=*) noexcept + cpdef toric_substitute(self, v, v1, a, h=*, new_ring=*) noexcept diff --git a/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx b/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx index e14f1b36ce5..9c118a97a0f 100644 --- a/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx +++ b/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx @@ -250,7 +250,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): from sage.misc.misc_c import prod return codomain(p(im_gens) * prod(ig**m[im_gens.index(ig)] for ig in im_gens)) - cdef _normalize(self, i=None): + cdef _normalize(self, i=None) noexcept: r""" Remove the common monomials from ``self._poly`` and store them in ``self._mon``. @@ -301,7 +301,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): self._poly = (self._poly // self._poly._parent.gen(i)) self._mon = self._mon.eadd_p(e, i) - cdef _compute_polydict(self): + cdef _compute_polydict(self) noexcept: """ EXAMPLES:: @@ -767,7 +767,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): v.sort() return tuple(v) - cpdef dict dict(self): + cpdef dict dict(self) noexcept: """ Return ``self`` represented as a ``dict``. @@ -809,7 +809,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): denom *= var[i] ** (-j) return (numer, denom) - cpdef _add_(self, _right): + cpdef _add_(self, _right) noexcept: """ Return the Laurent polynomial ``self + right``. @@ -834,7 +834,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): ans._poly += right._poly return ans - cpdef _sub_(self, _right): + cpdef _sub_(self, _right) noexcept: """ Return the Laurent polynomial ``self - right``. @@ -860,7 +860,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): ans._poly -= right._poly return ans - cpdef _div_(self, rhs): + cpdef _div_(self, rhs) noexcept: """ Return the division of ``self`` by ``rhs``. @@ -911,7 +911,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): """ return self._poly.is_monomial() - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ Return ``-self``. @@ -927,7 +927,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): ans._poly = -self._poly return ans - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: """ Return ``self * right`` where ``right`` is in ``self``'s base ring. @@ -943,7 +943,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): ans._poly = self._poly * right return ans - cpdef _rmul_(self, Element left): + cpdef _rmul_(self, Element left) noexcept: """ Return ``left * self`` where ``left`` is in ``self``'s base ring. @@ -959,7 +959,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): ans._poly = left * self._poly return ans - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Return ``self * right``. @@ -976,7 +976,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): ans._poly = self._poly * (right)._poly return ans - cpdef _floordiv_(self, right): + cpdef _floordiv_(self, right) noexcept: """ Perform division with remainder and return the quotient. @@ -1078,7 +1078,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): rl._normalize() return (ql, rl) - cpdef _richcmp_(self, right, int op): + cpdef _richcmp_(self, right, int op) noexcept: """ Compare two polynomials in a `LaurentPolynomialRing` based on the term order from the parent ring. If the parent ring does not specify a term @@ -1645,7 +1645,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): ans._poly = root return (True, ans) - cpdef rescale_vars(self, dict d, h=None, new_ring=None): + cpdef rescale_vars(self, dict d, h=None, new_ring=None) noexcept: r""" Rescale variables in a Laurent polynomial. @@ -1712,7 +1712,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): return new_ring(ans) return ans - cpdef toric_coordinate_change(self, M, h=None, new_ring=None): + cpdef toric_coordinate_change(self, M, h=None, new_ring=None) noexcept: r""" Apply a matrix to the exponents in a Laurent polynomial. @@ -1781,7 +1781,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): return new_ring(ans) return ans - cpdef toric_substitute(self, v, v1, a, h=None, new_ring=None): + cpdef toric_substitute(self, v, v1, a, h=None, new_ring=None) noexcept: r""" Perform a single-variable substitution up to a toric coordinate change. diff --git a/src/sage/rings/polynomial/multi_polynomial.pxd b/src/sage/rings/polynomial/multi_polynomial.pxd index 5dc75e6bd3f..73bde26ab51 100644 --- a/src/sage/rings/polynomial/multi_polynomial.pxd +++ b/src/sage/rings/polynomial/multi_polynomial.pxd @@ -3,8 +3,8 @@ from .commutative_polynomial cimport CommutativePolynomial cdef class MPolynomial(CommutativePolynomial): cdef long _hash_c(self) except -1 - cpdef _mod_(self, right) - cpdef dict _mpoly_dict_recursive(self, tuple vars=*, base_ring=*) + cpdef _mod_(self, right) noexcept + cpdef dict _mpoly_dict_recursive(self, tuple vars=*, base_ring=*) noexcept cdef class MPolynomial_libsingular(MPolynomial): diff --git a/src/sage/rings/polynomial/multi_polynomial.pyx b/src/sage/rings/polynomial/multi_polynomial.pyx index d0a430bbfd8..d680f227210 100644 --- a/src/sage/rings/polynomial/multi_polynomial.pyx +++ b/src/sage/rings/polynomial/multi_polynomial.pyx @@ -433,7 +433,7 @@ cdef class MPolynomial(CommutativePolynomial): z *= var return ring(v) - cpdef dict _mpoly_dict_recursive(self, tuple vars=None, base_ring=None): + cpdef dict _mpoly_dict_recursive(self, tuple vars=None, base_ring=None) noexcept: r""" Return a ``dict`` of coefficient entries suitable for construction of a ``MPolynomial_polydict`` with the given variables. @@ -812,7 +812,7 @@ cdef class MPolynomial(CommutativePolynomial): d[e.unweighted_degree()][e] = c return {k: self._parent(d[k]) for k in d} - cpdef _mod_(self, other): + cpdef _mod_(self, other) noexcept: r""" EXAMPLES:: @@ -2891,7 +2891,7 @@ def _is_M_convex_(points): return True -cdef remove_from_tuple(e, int ind): +cdef remove_from_tuple(e, int ind) noexcept: w = list(e) del w[ind] if len(w) == 1: diff --git a/src/sage/rings/polynomial/multi_polynomial_element.py b/src/sage/rings/polynomial/multi_polynomial_element.py index 0c510df8d59..d4e2b115e39 100644 --- a/src/sage/rings/polynomial/multi_polynomial_element.py +++ b/src/sage/rings/polynomial/multi_polynomial_element.py @@ -1150,7 +1150,7 @@ def local_height(self, v, prec=None): prec = 53 K = FractionField(self.base_ring()) - if not (K in NumberFields() or isinstance(K, (sage.rings.abc.Order, IntegerRing_class))): + if K not in NumberFields(): raise TypeError("must be over a Numberfield or a Numberfield order") return max([K(c).local_height(v, prec=prec) for c in self.coefficients()]) @@ -1199,7 +1199,7 @@ def local_height_arch(self, i, prec=None): prec = 53 K = FractionField(self.base_ring()) - if not (K in NumberFields() or isinstance(K, (sage.rings.abc.Order, IntegerRing_class))): + if K not in NumberFields(): return TypeError("must be over a Numberfield or a Numberfield Order") if K == QQ: diff --git a/src/sage/rings/polynomial/multi_polynomial_ideal_libsingular.pxd b/src/sage/rings/polynomial/multi_polynomial_ideal_libsingular.pxd index 58f853973dc..fefa241523d 100644 --- a/src/sage/rings/polynomial/multi_polynomial_ideal_libsingular.pxd +++ b/src/sage/rings/polynomial/multi_polynomial_ideal_libsingular.pxd @@ -1,4 +1,4 @@ from sage.libs.singular.decl cimport ideal, ring -cdef object singular_ideal_to_sage_sequence(ideal *i, ring *r, object parent) +cdef object singular_ideal_to_sage_sequence(ideal *i, ring *r, object parent) noexcept cdef ideal *sage_ideal_to_singular_ideal(I) except NULL diff --git a/src/sage/rings/polynomial/multi_polynomial_ideal_libsingular.pyx b/src/sage/rings/polynomial/multi_polynomial_ideal_libsingular.pyx index 14820418454..38e251d84ce 100644 --- a/src/sage/rings/polynomial/multi_polynomial_ideal_libsingular.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_ideal_libsingular.pyx @@ -67,7 +67,7 @@ from sage.structure.sequence import Sequence from sage.rings.polynomial.plural cimport NCPolynomialRing_plural, NCPolynomial_plural -cdef object singular_ideal_to_sage_sequence(ideal *i, ring *r, object parent): +cdef object singular_ideal_to_sage_sequence(ideal *i, ring *r, object parent) noexcept: """ convert a SINGULAR ideal to a Sage Sequence (the format Sage stores a Groebner basis in) diff --git a/src/sage/rings/polynomial/multi_polynomial_libsingular.pxd b/src/sage/rings/polynomial/multi_polynomial_libsingular.pxd index c9cec10e2bc..744774ea231 100644 --- a/src/sage/rings/polynomial/multi_polynomial_libsingular.pxd +++ b/src/sage/rings/polynomial/multi_polynomial_libsingular.pxd @@ -8,14 +8,14 @@ cdef class MPolynomialRing_libsingular cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): cdef poly *_poly cdef ring *_parent_ring - cpdef _add_(self, other) - cpdef _mul_(self, other) - cpdef _floordiv_(self, right) - cpdef _repr_short_(self) - cpdef is_constant(self) - cpdef _homogenize(self, int var) - cpdef MPolynomial_libsingular _new_constant_poly(self, x, MPolynomialRing_libsingular P) - cpdef long number_of_terms(self) + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept + cpdef _floordiv_(self, right) noexcept + cpdef _repr_short_(self) noexcept + cpdef is_constant(self) noexcept + cpdef _homogenize(self, int var) noexcept + cpdef MPolynomial_libsingular _new_constant_poly(self, x, MPolynomialRing_libsingular P) noexcept + cpdef long number_of_terms(self) noexcept cdef class MPolynomialRing_libsingular(MPolynomialRing_base): cdef object __singular @@ -26,4 +26,4 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base): cdef ring *_ring # new polynomials -cdef MPolynomial_libsingular new_MP(MPolynomialRing_libsingular parent, poly *p) +cdef MPolynomial_libsingular new_MP(MPolynomialRing_libsingular parent, poly *p) noexcept diff --git a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx index 8b1086714f5..e9787a2e0f7 100644 --- a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx @@ -462,7 +462,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base): memo[id(self)] = self return self - cpdef _coerce_map_from_(self, other): + cpdef _coerce_map_from_(self, other) noexcept: """ Return ``True`` if and only if there exists a coercion map from ``other`` to ``self``. @@ -1974,7 +1974,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): memo[id(self)] = cpy return cpy - cpdef MPolynomial_libsingular _new_constant_poly(self, x, MPolynomialRing_libsingular P): + cpdef MPolynomial_libsingular _new_constant_poly(self, x, MPolynomialRing_libsingular P) noexcept: r""" Quickly create a new constant polynomial with value x in the parent P. @@ -2136,7 +2136,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): """ return self._hash_c() - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Compare left and right. @@ -2194,7 +2194,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): cdef ring *r = (left)._parent_ring return rich_to_bool(op, singular_polynomial_cmp(p, q, r)) - cpdef _add_(left, right): + cpdef _add_(left, right) noexcept: """ Add left and right. @@ -2210,7 +2210,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): (right)._poly, r) return new_MP((left)._parent, _p) - cpdef _sub_(left, right): + cpdef _sub_(left, right) noexcept: """ Subtract left and right. @@ -2227,7 +2227,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): _ring) return new_MP((left)._parent, _p) - cpdef _lmul_(self, Element left): + cpdef _lmul_(self, Element left) noexcept: """ Multiply self with a base ring element. @@ -2251,7 +2251,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): singular_polynomial_rmul(&_p, self._poly, left, _ring) return new_MP((self)._parent, _p) - cpdef _mul_(left, right): + cpdef _mul_(left, right) noexcept: """ Multiply left and right. @@ -2275,7 +2275,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): (left)._parent_ring) return new_MP((left)._parent,_p) - cpdef _div_(left, right_ringelement): + cpdef _div_(left, right_ringelement) noexcept: r""" Divide left by right @@ -2478,7 +2478,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): s = singular_polynomial_str(self._poly, _ring) return s - cpdef _repr_short_(self): + cpdef _repr_short_(self) noexcept: """ This is a faster but less pretty way to print polynomials. If available it uses the short SINGULAR notation. @@ -3029,7 +3029,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): yield (tuple(exp), si2sa(p_GetCoeff(p, r), r, base)) p = pNext(p) - cpdef long number_of_terms(self): + cpdef long number_of_terms(self) noexcept: """ Return the number of non-zero coefficients of this polynomial. @@ -3281,7 +3281,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): rChangeCurrRing(_ring) return bool(p_IsHomogeneous(self._poly,_ring)) - cpdef _homogenize(self, int var): + cpdef _homogenize(self, int var) noexcept: """ Return ``self`` if ``self`` is homogeneous. Otherwise return a homogenized polynomial constructed by modifying the degree @@ -3913,7 +3913,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): """ return len(self._variable_indices_(sort=False)) - cpdef is_constant(self): + cpdef is_constant(self) noexcept: """ Return ``True`` if this polynomial is constant. @@ -4055,7 +4055,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): else: return False - cpdef _floordiv_(self, right): + cpdef _floordiv_(self, right) noexcept: """ Perform division with remainder and return the quotient. @@ -5900,7 +5900,7 @@ def unpickle_MPolynomial_libsingular(MPolynomialRing_libsingular R, d): return new_MP(R, p) -cdef inline poly *addwithcarry(poly *tempvector, poly *maxvector, int pos, ring *_ring): +cdef inline poly *addwithcarry(poly *tempvector, poly *maxvector, int pos, ring *_ring) noexcept: if p_GetExp(tempvector, pos, _ring) < p_GetExp(maxvector, pos, _ring): p_SetExp(tempvector, pos, p_GetExp(tempvector, pos, _ring)+1, _ring) else: @@ -5910,7 +5910,7 @@ cdef inline poly *addwithcarry(poly *tempvector, poly *maxvector, int pos, ring return tempvector -cdef inline MPolynomial_libsingular new_MP(MPolynomialRing_libsingular parent, poly *juice): +cdef inline MPolynomial_libsingular new_MP(MPolynomialRing_libsingular parent, poly *juice) noexcept: """ Construct MPolynomial_libsingular from parent and SINGULAR poly. @@ -5938,5 +5938,5 @@ cdef inline MPolynomial_libsingular new_MP(MPolynomialRing_libsingular parent, p return p -cdef poly *MPolynomial_libsingular_get_element(object self): +cdef poly *MPolynomial_libsingular_get_element(object self) noexcept: return (self)._poly diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd b/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd index eb6f8b70917..a090a15ac34 100644 --- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd +++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd @@ -8,7 +8,7 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing): cdef public object _magma_gens cdef public dict _magma_cache - cdef _coerce_c_impl(self, x) + cdef _coerce_c_impl(self, x) noexcept cdef class BooleanPolynomialRing_base(MPolynomialRing_base): diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx index c8f66508cc2..66ade555385 100644 --- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx @@ -554,7 +554,7 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing): else: return self._generic_coerce_map(self.base_ring()) - cdef _coerce_c_impl(self, x): + cdef _coerce_c_impl(self, x) noexcept: """ Return the canonical coercion of x to this multivariate polynomial ring, if one is defined, or raise a TypeError. diff --git a/src/sage/rings/polynomial/ore_polynomial_element.pxd b/src/sage/rings/polynomial/ore_polynomial_element.pxd index aa36112ab90..86b14f7d213 100644 --- a/src/sage/rings/polynomial/ore_polynomial_element.pxd +++ b/src/sage/rings/polynomial/ore_polynomial_element.pxd @@ -8,38 +8,38 @@ from sage.rings.polynomial.polynomial_element cimport Polynomial_generic_dense cdef class OrePolynomial(AlgebraElement): cdef _is_gen - cdef long _hash_c(self) - cdef OrePolynomial _new_c(self, list coeffs, Parent P, char check=*) - cpdef OrePolynomial _new_constant_poly(self, RingElement a, Parent P, char check=*) - cpdef _neg_(self) - cpdef _floordiv_(self, right) - cpdef _mod_(self, right) - - cpdef bint is_zero(self) - cpdef bint is_one(self) + cdef long _hash_c(self) noexcept + cdef OrePolynomial _new_c(self, list coeffs, Parent P, char check=*) noexcept + cpdef OrePolynomial _new_constant_poly(self, RingElement a, Parent P, char check=*) noexcept + cpdef _neg_(self) noexcept + cpdef _floordiv_(self, right) noexcept + cpdef _mod_(self, right) noexcept + + cpdef bint is_zero(self) noexcept + cpdef bint is_one(self) noexcept - cdef _left_quo_rem(self, OrePolynomial other) - cdef _right_quo_rem(self, OrePolynomial other) - cdef OrePolynomial _left_lcm_cofactor(self, OrePolynomial other) - cdef OrePolynomial _right_lcm_cofactor(self, OrePolynomial other) + cdef _left_quo_rem(self, OrePolynomial other) noexcept + cdef _right_quo_rem(self, OrePolynomial other) noexcept + cdef OrePolynomial _left_lcm_cofactor(self, OrePolynomial other) noexcept + cdef OrePolynomial _right_lcm_cofactor(self, OrePolynomial other) noexcept # Abstract methods - cpdef Integer degree(self) - cpdef list coefficients(self, sparse=*) + cpdef Integer degree(self) noexcept + cpdef list coefficients(self, sparse=*) noexcept -cdef void lmul_gen(list A, Morphism m, d) +cdef void lmul_gen(list A, Morphism m, d) noexcept cdef class OrePolynomial_generic_dense(OrePolynomial): cdef list _coeffs - cdef void _normalize(self) - cpdef _add_(self, other) - cdef list _mul_list(self, list A) - cpdef _mul_(self, other) + cdef void _normalize(self) noexcept + cpdef _add_(self, other) noexcept + cdef list _mul_list(self, list A) noexcept + cpdef _mul_(self, other) noexcept - cpdef dict dict(self) - cpdef list list(self, bint copy=*) + cpdef dict dict(self) noexcept + cpdef list list(self, bint copy=*) noexcept cdef class OrePolynomialBaseringInjection(Morphism): diff --git a/src/sage/rings/polynomial/ore_polynomial_element.pyx b/src/sage/rings/polynomial/ore_polynomial_element.pyx index be154ba8b1a..53c14bbc23f 100644 --- a/src/sage/rings/polynomial/ore_polynomial_element.pyx +++ b/src/sage/rings/polynomial/ore_polynomial_element.pyx @@ -233,7 +233,7 @@ cdef class OrePolynomial(AlgebraElement): """ AlgebraElement.__init__(self, parent) - cdef long _hash_c(self): + cdef long _hash_c(self) noexcept: raise NotImplementedError def __hash__(self): @@ -251,7 +251,7 @@ cdef class OrePolynomial(AlgebraElement): """ return self._hash_c() - cpdef Integer degree(self): + cpdef Integer degree(self) noexcept: r""" Return the degree of ``self``. @@ -272,7 +272,7 @@ cdef class OrePolynomial(AlgebraElement): """ raise NotImplementedError - cdef OrePolynomial _new_c(self, list coeffs, Parent P, char check=0): + cdef OrePolynomial _new_c(self, list coeffs, Parent P, char check=0) noexcept: r""" Fast creation of a new Ore polynomial @@ -283,7 +283,7 @@ cdef class OrePolynomial(AlgebraElement): """ return P(coeffs) - cpdef OrePolynomial _new_constant_poly(self, RingElement a, Parent P, char check=0): + cpdef OrePolynomial _new_constant_poly(self, RingElement a, Parent P, char check=0) noexcept: r""" Fast creation of a new constant Ore polynomial @@ -580,7 +580,7 @@ cdef class OrePolynomial(AlgebraElement): raise NotImplementedError("the leading coefficient is not a unit") return a * self - cpdef _mod_(self, other): + cpdef _mod_(self, other) noexcept: r""" Return the remainder in the *right* Euclidean division of ``self`` by ``other```. @@ -602,7 +602,7 @@ cdef class OrePolynomial(AlgebraElement): """ return self.right_quo_rem(other)[1] - cpdef _floordiv_(self, right): + cpdef _floordiv_(self, right) noexcept: r""" Return the quotient of the *right* Euclidean division of ``self`` by ``right``. @@ -628,7 +628,7 @@ cdef class OrePolynomial(AlgebraElement): q, _ = self.right_quo_rem(right) return q - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: r""" Return the quotient of this Ore polynomial by ``right`` in the fraction field. @@ -940,7 +940,7 @@ cdef class OrePolynomial(AlgebraElement): V = V * lc return G, U, V - cdef _left_quo_rem(self, OrePolynomial other): + cdef _left_quo_rem(self, OrePolynomial other) noexcept: r""" Return the quotient and remainder of the left Euclidean division of ``self`` by ``other`` (C implementation). @@ -1000,7 +1000,7 @@ cdef class OrePolynomial(AlgebraElement): raise ZeroDivisionError("division by zero is not valid") return self._left_quo_rem(other) - cdef _right_quo_rem(self, OrePolynomial other): + cdef _right_quo_rem(self, OrePolynomial other) noexcept: r""" Return the quotient and remainder of the right Euclidean division of ``self`` by ``other`` (C implementation). @@ -1309,7 +1309,7 @@ cdef class OrePolynomial(AlgebraElement): A = A.left_monic() return A - cdef OrePolynomial _left_lcm_cofactor(self, OrePolynomial other): + cdef OrePolynomial _left_lcm_cofactor(self, OrePolynomial other) noexcept: r""" Return an Ore polynomial `U` such that `U P = c L` where `P` is this Ore polynomial (``self``), `L` @@ -1387,7 +1387,7 @@ cdef class OrePolynomial(AlgebraElement): V1 = s * V1 return L, V1, L // other - cdef OrePolynomial _right_lcm_cofactor(self, OrePolynomial other): + cdef OrePolynomial _right_lcm_cofactor(self, OrePolynomial other) noexcept: r""" Return an Ore polynomial `U` such that `P U = L c` where `P` is this Ore polynomial (``self``), `L` @@ -1942,7 +1942,7 @@ cdef class OrePolynomial(AlgebraElement): """ return self.is_term() and self.leading_coefficient() == 1 - cpdef list coefficients(self, sparse=True): + cpdef list coefficients(self, sparse=True) noexcept: r""" Return the coefficients of the monomials appearing in ``self``. @@ -2010,7 +2010,7 @@ cdef class OrePolynomial(AlgebraElement): """ return self - cpdef bint is_zero(self): + cpdef bint is_zero(self) noexcept: r""" Return ``True`` if ``self`` is the zero polynomial. @@ -2028,7 +2028,7 @@ cdef class OrePolynomial(AlgebraElement): """ return self.degree() == -1 - cpdef bint is_one(self): + cpdef bint is_one(self) noexcept: r""" Test whether this polynomial is `1`. @@ -2190,7 +2190,7 @@ cdef class OrePolynomial(AlgebraElement): return self.parent().variable_name() -cdef void lmul_gen(list A, Morphism m, d): +cdef void lmul_gen(list A, Morphism m, d) noexcept: r""" If ``A`` is the list of coefficients of an Ore polynomial ``P``, replace it by the list of coefficients of ``X*P`` (where ``X`` @@ -2323,7 +2323,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): """ return (self._parent, (self._coeffs,)) - cdef long _hash_c(self): + cdef long _hash_c(self) noexcept: r""" This hash incorporates the name of the variable. @@ -2354,7 +2354,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): return -2 return result - cdef OrePolynomial _new_c(self, list coeffs, Parent P, char check=0): + cdef OrePolynomial _new_c(self, list coeffs, Parent P, char check=0) noexcept: r""" Fast creation of a new Ore polynomial given a list of coefficients. @@ -2380,7 +2380,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): f._normalize() return f - cdef void _normalize(self): + cdef void _normalize(self) noexcept: r""" Remove higher order `0`-coefficients from the representation of ``self``. @@ -2397,7 +2397,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): del x[n] n -= 1 - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: r""" Compare the two Ore polynomials ``self`` and ``other``. @@ -2463,7 +2463,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): except IndexError: return self.base_ring().zero() - cpdef list list(self, bint copy=True): + cpdef list list(self, bint copy=True) noexcept: r""" Return a list of the coefficients of ``self``. @@ -2491,7 +2491,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): else: return (self)._coeffs - cpdef dict dict(self): + cpdef dict dict(self) noexcept: r""" Return a dictionary representation of ``self``. @@ -2513,7 +2513,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): X[i] = c return X - cpdef Integer degree(self): + cpdef Integer degree(self) noexcept: r""" Return the degree of ``self``. @@ -2552,7 +2552,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): """ return Integer(len(self._coeffs) - 1) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: r""" Add two polynomials. @@ -2583,7 +2583,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): r = self._new_c([x[i] + y[i] for i in range(dx)], self._parent, 1) return r - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: r""" Subtract polynomial ``right`` from ``self``. @@ -2615,7 +2615,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): r = self._new_c([x[i] - y[i] for i in range(dx)], self._parent, 1) return r - cpdef _neg_(self): + cpdef _neg_(self) noexcept: r""" Return the negative of ``self``. @@ -2678,7 +2678,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): """ return self._new_c(self._coeffs[:n], self._parent, 1) - cdef list _mul_list(self, list A): + cdef list _mul_list(self, list A) noexcept: r""" Return the list of coefficients of the product of this Ore polynomial by that whose coefficients are given by ``A``. @@ -2699,7 +2699,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): BA[j] += coeff * A[j] return BA - cpdef _lmul_(self, Element s): + cpdef _lmul_(self, Element s) noexcept: r""" Return the product ``self * right``. @@ -2718,7 +2718,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): cdef coeffs = self._mul_list([s]) return self._new_c(coeffs, self._parent, 1) - cpdef _rmul_(self, Element s): + cpdef _rmul_(self, Element s) noexcept: r""" Return the product ``left * self``. @@ -2746,7 +2746,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): """ return self._new_c([s * c for c in self._coeffs], self._parent, 1) - cpdef _mul_(self, other): + cpdef _mul_(self, other) noexcept: r""" Return the product ``self * right``. @@ -2785,7 +2785,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): coeffs = self._mul_list(coeffs) return self._new_c(coeffs, self._parent, 1) - cdef _left_quo_rem(self, OrePolynomial other): + cdef _left_quo_rem(self, OrePolynomial other) noexcept: r""" Return the quotient and remainder of the left Euclidean division of ``self`` by ``other`` (C implementation). @@ -2814,7 +2814,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): quo.reverse() return self._new_c(quo, self._parent), self._new_c(A[:degB], self._parent, 1) - cdef _right_quo_rem(self, OrePolynomial other): + cdef _right_quo_rem(self, OrePolynomial other) noexcept: r""" Return the quotient and remainder of the right Euclidean division of ``self`` by ``other`` (C implementation). @@ -2852,7 +2852,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): quo.reverse() return self._new_c(quo, self._parent), self._new_c(A[:degB], self._parent, 1) - cpdef list coefficients(self, sparse=True): + cpdef list coefficients(self, sparse=True) noexcept: r""" Return the coefficients of the monomials appearing in ``self``. @@ -2988,7 +2988,7 @@ cdef class ConstantOrePolynomialSection(Map): over Rational Field twisted by t |--> t + 1 To: Univariate Polynomial Ring in t over Rational Field """ - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: r""" Return the corresponding element of the base ring if ``self`` is a constant Ore polynomial. Otherwise, it fails. @@ -3096,7 +3096,7 @@ cdef class OrePolynomialBaseringInjection(Morphism): """ return self._an_element - cpdef Element _call_(self, e): + cpdef Element _call_(self, e) noexcept: r""" Return the corresponding Ore polynomial to the element from the base ring according to ``self``. diff --git a/src/sage/rings/polynomial/pbori/pbori.pxd b/src/sage/rings/polynomial/pbori/pbori.pxd index ae4ac1353d2..f9083a681a2 100644 --- a/src/sage/rings/polynomial/pbori/pbori.pxd +++ b/src/sage/rings/polynomial/pbori/pbori.pxd @@ -17,12 +17,12 @@ cdef class BooleanPolynomialRing(BooleanPolynomialRing_base): # it is very important to keep this cached, since otherwise the magma interface will break cdef public object __cover_ring - cdef _convert(self, rhs) + cdef _convert(self, rhs) noexcept cdef class BooleanPolynomial(MPolynomial): cdef PBPoly _pbpoly - cpdef _add_(self, other) - cpdef _mul_(self, other) + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept cdef class BooleSet: cdef BooleanPolynomialRing _ring @@ -35,7 +35,7 @@ cdef class CCuddNavigator: cdef class BooleanMonomial(MonoidElement): cdef PBMonom _pbmonom cdef BooleanPolynomialRing _ring - cpdef _mul_(self, other) + cpdef _mul_(self, other) noexcept cdef class BooleanMonomialVariableIterator: cdef object parent diff --git a/src/sage/rings/polynomial/pbori/pbori.pyx b/src/sage/rings/polynomial/pbori/pbori.pyx index 314196faa14..8560837f72e 100644 --- a/src/sage/rings/polynomial/pbori/pbori.pyx +++ b/src/sage/rings/polynomial/pbori/pbori.pyx @@ -607,7 +607,7 @@ cdef class BooleanPolynomialRing(BooleanPolynomialRing_base): return self._repr # Coercion - cpdef _coerce_map_from_(self, S): + cpdef _coerce_map_from_(self, S) noexcept: """ There is coercion from the base ring, from any boolean polynomial ring with compatible variable names, @@ -683,7 +683,7 @@ cdef class BooleanPolynomialRing(BooleanPolynomialRing_base): return False return self._base.has_coerce_map_from(S.base()) - cdef _convert(self, other): + cdef _convert(self, other) noexcept: r""" Canonical conversion of elements from other domains to this boolean polynomial ring. @@ -2269,7 +2269,7 @@ cdef class BooleanMonomial(MonoidElement): gens = self._parent.gens() return self._parent, (tuple(gens.index(x) for x in self.variables()),) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Compare BooleanMonomial objects. @@ -2633,7 +2633,7 @@ cdef class BooleanMonomial(MonoidElement): """ return new_BMI_from_BooleanMonomial(self) - cpdef _mul_(left, right): + cpdef _mul_(left, right) noexcept: """ Multiply this boolean monomial with another boolean monomial. @@ -2805,7 +2805,7 @@ cdef class BooleanMonomial(MonoidElement): # ### -cdef inline BooleanMonomial new_BM(parent, BooleanPolynomialRing ring): +cdef inline BooleanMonomial new_BM(parent, BooleanPolynomialRing ring) noexcept: cdef BooleanMonomial m m = BooleanMonomial.__new__(BooleanMonomial) m._parent = parent @@ -2813,13 +2813,13 @@ cdef inline BooleanMonomial new_BM(parent, BooleanPolynomialRing ring): return m cdef inline BooleanMonomial new_BM_from_PBMonom(parent, - BooleanPolynomialRing ring, PBMonom juice): + BooleanPolynomialRing ring, PBMonom juice) noexcept: cdef BooleanMonomial m = new_BM(parent, ring) m._pbmonom = juice return m cdef inline BooleanMonomial new_BM_from_PBVar(parent, - BooleanPolynomialRing ring, PBVar juice): + BooleanPolynomialRing ring, PBVar juice) noexcept: cdef BooleanMonomial m = new_BM(parent, ring) m._pbmonom = PBMonom(juice) return m @@ -2861,7 +2861,7 @@ cdef class BooleanMonomialVariableIterator: return new_BM_from_PBVar(self.parent, self._ring, value) cdef inline BooleanMonomialVariableIterator new_BMVI_from_BooleanMonomial( - BooleanMonomial monom): + BooleanMonomial monom) noexcept: """ Construct a new iterator over the variable indices of a boolean monomial. @@ -2912,7 +2912,7 @@ cdef class BooleanMonomialIterator: return self.pbind[value] -cdef inline BooleanMonomialIterator new_BMI_from_BooleanMonomial(BooleanMonomial monom): +cdef inline BooleanMonomialIterator new_BMI_from_BooleanMonomial(BooleanMonomial monom) noexcept: """ Construct a new BooleanMonomialIterator """ @@ -3016,7 +3016,7 @@ cdef class BooleanPolynomial(MPolynomial): R = self.parent().cover_ring() return R(self)._latex_() - cpdef _add_(left, right): + cpdef _add_(left, right) noexcept: """ EXAMPLES:: @@ -3031,7 +3031,7 @@ cdef class BooleanPolynomial(MPolynomial): p._pbpoly.iadd((right)._pbpoly) return p - cpdef _sub_(left, right): + cpdef _sub_(left, right) noexcept: """ EXAMPLES:: @@ -3043,7 +3043,7 @@ cdef class BooleanPolynomial(MPolynomial): """ return left._add_(right) - cpdef _lmul_(self, Element left): + cpdef _lmul_(self, Element left) noexcept: """ EXAMPLES:: @@ -3066,7 +3066,7 @@ cdef class BooleanPolynomial(MPolynomial): else: return self._parent.zero() - cpdef _mul_(left, right): + cpdef _mul_(left, right) noexcept: """ EXAMPLES:: @@ -3081,7 +3081,7 @@ cdef class BooleanPolynomial(MPolynomial): p._pbpoly.imul((right)._pbpoly) return p - cpdef _div_(left, right): + cpdef _div_(left, right) noexcept: """ EXAMPLES:: @@ -3117,7 +3117,7 @@ cdef class BooleanPolynomial(MPolynomial): """ return self._pbpoly == right._pbpoly - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Compare left and right. @@ -4794,7 +4794,7 @@ cdef class BooleanPolynomialIterator: self.obj._parent, value) -cdef inline BooleanPolynomialIterator new_BPI_from_BooleanPolynomial(BooleanPolynomial f): +cdef inline BooleanPolynomialIterator new_BPI_from_BooleanPolynomial(BooleanPolynomial f) noexcept: """ Construct a new BooleanMonomialIterator """ @@ -5217,35 +5217,35 @@ class BooleanPolynomialIdeal(MPolynomialIdeal): ## -cdef inline BooleanPolynomial new_BP(BooleanPolynomialRing parent): +cdef inline BooleanPolynomial new_BP(BooleanPolynomialRing parent) noexcept: cdef BooleanPolynomial p p = BooleanPolynomial.__new__(BooleanPolynomial) p._parent = parent return p -cdef inline BooleanPolynomial new_BP_from_PBVar(BooleanPolynomialRing parent, PBVar juice): +cdef inline BooleanPolynomial new_BP_from_PBVar(BooleanPolynomialRing parent, PBVar juice) noexcept: cdef BooleanPolynomial p = new_BP(parent) p._pbpoly = PBBoolePolynomial(juice) return p -cdef inline BooleanPolynomial new_BP_from_PBPoly(BooleanPolynomialRing parent, PBPoly juice): +cdef inline BooleanPolynomial new_BP_from_PBPoly(BooleanPolynomialRing parent, PBPoly juice) noexcept: cdef BooleanPolynomial p = new_BP(parent) p._pbpoly = juice return p -cdef inline BooleanPolynomial new_BP_from_PBMonom(BooleanPolynomialRing parent, PBMonom juice): +cdef inline BooleanPolynomial new_BP_from_PBMonom(BooleanPolynomialRing parent, PBMonom juice) noexcept: cdef BooleanPolynomial p = new_BP(parent) p._pbpoly = PBBoolePolynomial(juice) return p -cdef inline BooleanPolynomial new_BP_from_PBSet(BooleanPolynomialRing parent, PBSet juice): +cdef inline BooleanPolynomial new_BP_from_PBSet(BooleanPolynomialRing parent, PBSet juice) noexcept: cdef BooleanPolynomial p = new_BP(parent) p._pbpoly = PBBoolePolynomial(juice) return p -cdef inline BooleanPolynomial new_BP_from_int(BooleanPolynomialRing parent, int juice): +cdef inline BooleanPolynomial new_BP_from_int(BooleanPolynomialRing parent, int juice) noexcept: cdef BooleanPolynomial p = new_BP(parent) p._pbpoly = PBBoolePolynomial(juice, parent._pbring) return p @@ -5869,7 +5869,7 @@ cdef class BooleSet: return self._pbset.sizeDouble() -cdef inline BooleSet new_BS_from_PBSet(PBSet juice, BooleanPolynomialRing ring): +cdef inline BooleSet new_BS_from_PBSet(PBSet juice, BooleanPolynomialRing ring) noexcept: """ Construct a new BooleSet """ @@ -5917,7 +5917,7 @@ cdef class BooleSetIterator: return new_BM_from_PBMonom(self._parent, self._ring, value) -cdef inline BooleSetIterator new_BSI_from_PBSetIter(BooleSet s): +cdef inline BooleSetIterator new_BSI_from_PBSetIter(BooleSet s) noexcept: """ Construct a new BooleSetIterator """ @@ -6136,7 +6136,7 @@ cdef class BooleanPolynomialVector: self._vec.push_back(p) cdef inline BooleanPolynomialVector new_BPV_from_PBPolyVector( - BooleanPolynomialRing parent, PBPolyVector juice): + BooleanPolynomialRing parent, PBPolyVector juice) noexcept: cdef BooleanPolynomialVector m m = BooleanPolynomialVector.__new__(BooleanPolynomialVector) m._vec = juice @@ -6158,7 +6158,7 @@ cdef class BooleanPolynomialVectorIterator: cdef inline BooleanPolynomialVectorIterator new_BPVI_from_PBPolyVectorIter( - BooleanPolynomialVector vec): + BooleanPolynomialVector vec) noexcept: """ Construct a new BooleanPolynomialVectorIterator """ @@ -7000,7 +7000,7 @@ cdef class GroebnerStrategy: cdef class BooleanMulAction(Action): - cpdef _act_(self, g, x): + cpdef _act_(self, g, x) noexcept: """ EXAMPLES:: @@ -7025,7 +7025,7 @@ cdef class BooleanMulAction(Action): cdef inline CCuddNavigator new_CN_from_PBNavigator(PBNavigator juice, - Py_ssize_t* pbind): + Py_ssize_t* pbind) noexcept: """ Construct a new CCuddNavigator """ @@ -7547,7 +7547,7 @@ def top_index(s): return (s.ring()).pbind[idx] -cdef long PBRing_identifier(PBRing pbring): +cdef long PBRing_identifier(PBRing pbring) noexcept: cdef long _hash = pbring.hash() ^ hash(pbring.ordering().getOrderCode()) @@ -7560,7 +7560,7 @@ cdef long PBRing_identifier(PBRing pbring): return _hash -cdef object TermOrder_from_PBRing(PBRing _ring): +cdef object TermOrder_from_PBRing(PBRing _ring) noexcept: cdef int n = _ring.nVariables() pb_base_order_code = _ring.ordering().getBaseOrderCode() order_str = inv_order_dict[pb_base_order_code] @@ -7582,7 +7582,7 @@ cdef object TermOrder_from_PBRing(PBRing _ring): return T -cdef BooleanPolynomialRing BooleanPolynomialRing_from_PBRing(PBRing _ring): +cdef BooleanPolynomialRing BooleanPolynomialRing_from_PBRing(PBRing _ring) noexcept: """ Get BooleanPolynomialRing from C++-implementation """ @@ -7899,7 +7899,7 @@ cdef class BooleConstant: return self._pbconst.hasConstantPart() -cdef object pb_block_order(n, order_str, blocks): +cdef object pb_block_order(n, order_str, blocks) noexcept: T = [TermOrder(order_str, blockend - blockstart, force=True) for (blockstart, blockend) in zip([0] + blocks, blocks + [n])] if T: @@ -7910,7 +7910,7 @@ cdef object pb_block_order(n, order_str, blocks): return order_str -cpdef object TermOrder_from_pb_order(int n, order, blocks): +cpdef object TermOrder_from_pb_order(int n, order, blocks) noexcept: if not isinstance(order, str): if order == pbblock_dlex: order_str = pb_block_order(n, "deglex", blocks) diff --git a/src/sage/rings/polynomial/plural.pxd b/src/sage/rings/polynomial/plural.pxd index d3a46f6aa0d..06b48c737f3 100644 --- a/src/sage/rings/polynomial/plural.pxd +++ b/src/sage/rings/polynomial/plural.pxd @@ -32,14 +32,14 @@ cdef class ExteriorAlgebra_plural(NCPolynomialRing_plural): cdef class NCPolynomial_plural(RingElement): cdef poly *_poly - cpdef _add_(self, other) - cpdef _mul_(self, other) - cpdef _repr_short_(self) - cdef long _hash_c(self) - cpdef is_constant(self) + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept + cpdef _repr_short_(self) noexcept + cdef long _hash_c(self) noexcept + cpdef is_constant(self) noexcept # cpdef _homogenize(self, int var) -cdef NCPolynomial_plural new_NCP(NCPolynomialRing_plural parent, poly *juice) +cdef NCPolynomial_plural new_NCP(NCPolynomialRing_plural parent, poly *juice) noexcept -cpdef MPolynomialRing_libsingular new_CRing(RingWrap rw, base_ring) -cpdef NCPolynomialRing_plural new_NRing(RingWrap rw, base_ring) +cpdef MPolynomialRing_libsingular new_CRing(RingWrap rw, base_ring) noexcept +cpdef NCPolynomialRing_plural new_NRing(RingWrap rw, base_ring) noexcept diff --git a/src/sage/rings/polynomial/plural.pyx b/src/sage/rings/polynomial/plural.pyx index 16c8c09fbc3..90e3663da5c 100644 --- a/src/sage/rings/polynomial/plural.pyx +++ b/src/sage/rings/polynomial/plural.pyx @@ -573,7 +573,7 @@ cdef class NCPolynomialRing_plural(Ring): " as noncommutative polynomial") # ??? return new_NCP(self, _p) - cpdef _coerce_map_from_(self, S): + cpdef _coerce_map_from_(self, S) noexcept: """ The only things that coerce into this ring are: @@ -1474,7 +1474,7 @@ cdef class NCPolynomial_plural(RingElement): """ return self._hash_c() - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Compare left and right. @@ -1525,7 +1525,7 @@ cdef class NCPolynomial_plural(RingElement): cdef ring *r = (left._parent)._ring return rich_to_bool(op, singular_polynomial_cmp(p, q, r)) - cpdef _add_(left, right): + cpdef _add_(left, right) noexcept: """ Adds left and right. @@ -1544,7 +1544,7 @@ cdef class NCPolynomial_plural(RingElement): (left._parent)._ring) return new_NCP((left._parent), _p) - cpdef _sub_(left, right): + cpdef _sub_(left, right) noexcept: """ Subtract left and right. @@ -1566,7 +1566,7 @@ cdef class NCPolynomial_plural(RingElement): _ring) return new_NCP((left._parent), _p) - cpdef _lmul_(self, Element left): + cpdef _lmul_(self, Element left) noexcept: """ Multiply ``self`` with a base ring element. @@ -1596,7 +1596,7 @@ cdef class NCPolynomial_plural(RingElement): singular_polynomial_rmul(&_p, self._poly, left, _ring) return new_NCP((self._parent),_p) - cpdef _mul_(left, right): + cpdef _mul_(left, right) noexcept: """ Multiply left and right. @@ -1627,7 +1627,7 @@ cdef class NCPolynomial_plural(RingElement): (left._parent)._ring) return new_NCP((left._parent),_p) - cpdef _div_(left, right): + cpdef _div_(left, right) noexcept: """ Divide left by right @@ -1808,7 +1808,7 @@ cdef class NCPolynomial_plural(RingElement): s = singular_polynomial_str(self._poly, _ring) return s - cpdef _repr_short_(self): + cpdef _repr_short_(self) noexcept: """ This is a faster but less pretty way to print polynomials. If available it uses the short SINGULAR notation. @@ -2274,7 +2274,7 @@ cdef class NCPolynomial_plural(RingElement): return sum(prod(im_gens[i]**val for i, val in enumerate(t))*base_map(d[t]) for t in d) - cdef long _hash_c(self): + cdef long _hash_c(self) noexcept: """ See :meth:`__hash__` """ @@ -2586,7 +2586,7 @@ cdef class NCPolynomial_plural(RingElement): else: return (self._parent)._base._zero_element - cpdef is_constant(self): + cpdef is_constant(self) noexcept: """ Return ``True`` if this polynomial is constant. @@ -2811,7 +2811,7 @@ cdef class NCPolynomial_plural(RingElement): cdef inline NCPolynomial_plural new_NCP(NCPolynomialRing_plural parent, - poly *juice): + poly *juice) noexcept: """ Construct NCPolynomial_plural from parent and SINGULAR poly. @@ -2832,7 +2832,7 @@ cdef inline NCPolynomial_plural new_NCP(NCPolynomialRing_plural parent, -cpdef MPolynomialRing_libsingular new_CRing(RingWrap rw, base_ring): +cpdef MPolynomialRing_libsingular new_CRing(RingWrap rw, base_ring) noexcept: """ Construct MPolynomialRing_libsingular from ringWrap, assuming the ground field to be base_ring @@ -2904,7 +2904,7 @@ cpdef MPolynomialRing_libsingular new_CRing(RingWrap rw, base_ring): return self -cpdef NCPolynomialRing_plural new_NRing(RingWrap rw, base_ring): +cpdef NCPolynomialRing_plural new_NRing(RingWrap rw, base_ring) noexcept: """ Construct NCPolynomialRing_plural from ringWrap, assuming the ground field to be base_ring @@ -3127,7 +3127,7 @@ def ExteriorAlgebra(base_ring, names,order='degrevlex'): I = H.ideal([H.gen(i) * H.gen(i) for i in range(n)]).twostd() return H.quotient(I) -cdef poly *addwithcarry(poly *tempvector, poly *maxvector, int pos, ring *_ring): +cdef poly *addwithcarry(poly *tempvector, poly *maxvector, int pos, ring *_ring) noexcept: if p_GetExp(tempvector, pos, _ring) < p_GetExp(maxvector, pos, _ring): p_SetExp(tempvector, pos, p_GetExp(tempvector, pos, _ring)+1, _ring) else: diff --git a/src/sage/rings/polynomial/polydict.pxd b/src/sage/rings/polynomial/polydict.pxd index 6bc1901bd7e..432ae7d8c47 100644 --- a/src/sage/rings/polynomial/polydict.pxd +++ b/src/sage/rings/polynomial/polydict.pxd @@ -1,8 +1,8 @@ cdef class PolyDict: cdef dict __repn - cdef PolyDict _new(self, dict pdict) - cpdef remove_zeros(self, zero_test=*) + cdef PolyDict _new(self, dict pdict) noexcept + cpdef remove_zeros(self, zero_test=*) noexcept cdef class ETuple: @@ -10,33 +10,33 @@ cdef class ETuple: cdef size_t _nonzero cdef int *_data - cdef size_t get_position(self, size_t i, size_t start, size_t end) - cdef ETuple _new(self) - cdef int get_exp(self, size_t i) + cdef size_t get_position(self, size_t i, size_t start, size_t end) noexcept + cdef ETuple _new(self) noexcept + cdef int get_exp(self, size_t i) noexcept cpdef int unweighted_degree(self) except * cpdef int weighted_degree(self, tuple w) except * cpdef int unweighted_quotient_degree(self, ETuple other) except * cpdef int weighted_quotient_degree(self, ETuple other, tuple w) except * - cpdef ETuple eadd(self, ETuple other) - cpdef ETuple esub(self, ETuple other) - cpdef ETuple emul(self, int factor) - cpdef ETuple emin(self, ETuple other) - cpdef ETuple emax(self, ETuple other) - cpdef ETuple eadd_p(self, int other, size_t pos) - cpdef ETuple eadd_scaled(self, ETuple other, int scalar) + cpdef ETuple eadd(self, ETuple other) noexcept + cpdef ETuple esub(self, ETuple other) noexcept + cpdef ETuple emul(self, int factor) noexcept + cpdef ETuple emin(self, ETuple other) noexcept + cpdef ETuple emax(self, ETuple other) noexcept + cpdef ETuple eadd_p(self, int other, size_t pos) noexcept + cpdef ETuple eadd_scaled(self, ETuple other, int scalar) noexcept cpdef int dotprod(self, ETuple other) except * - cpdef ETuple escalar_div(self, int n) - cpdef ETuple divide_by_gcd(self, ETuple other) - cpdef ETuple divide_by_var(self, size_t pos) + cpdef ETuple escalar_div(self, int n) noexcept + cpdef ETuple divide_by_gcd(self, ETuple other) noexcept + cpdef ETuple divide_by_var(self, size_t pos) noexcept cpdef bint divides(self, ETuple other) except * - cpdef bint is_constant(self) + cpdef bint is_constant(self) noexcept cpdef bint is_multiple_of(self, int n) except * - cpdef list nonzero_positions(self, bint sort=*) - cpdef common_nonzero_positions(self, ETuple other, bint sort=*) - cpdef list nonzero_values(self, bint sort=*) - cpdef ETuple reversed(self) + cpdef list nonzero_positions(self, bint sort=*) noexcept + cpdef common_nonzero_positions(self, ETuple other, bint sort=*) noexcept + cpdef list nonzero_values(self, bint sort=*) noexcept + cpdef ETuple reversed(self) noexcept -cpdef int gen_index(PolyDict x) -cpdef ETuple monomial_exponent(PolyDict p) +cpdef int gen_index(PolyDict x) noexcept +cpdef ETuple monomial_exponent(PolyDict p) noexcept diff --git a/src/sage/rings/polynomial/polydict.pyx b/src/sage/rings/polynomial/polydict.pyx index 0c847d125a4..aaefb2d99d2 100644 --- a/src/sage/rings/polynomial/polydict.pyx +++ b/src/sage/rings/polynomial/polydict.pyx @@ -44,7 +44,7 @@ from pprint import pformat from sage.misc.latex import latex -cpdef int gen_index(PolyDict x): +cpdef int gen_index(PolyDict x) noexcept: r""" Return the index of the variable represented by ``x`` or ``-1`` if ``x`` is not a monomial of degree one. @@ -69,7 +69,7 @@ cpdef int gen_index(PolyDict x): return e._data[0] -cpdef ETuple monomial_exponent(PolyDict p): +cpdef ETuple monomial_exponent(PolyDict p) noexcept: r""" Return the unique exponent of ``p`` if it is a monomial or raise a ``ValueError``. @@ -189,12 +189,12 @@ cdef class PolyDict: if remove_zero: self.remove_zeros() - cdef PolyDict _new(self, dict pdict): + cdef PolyDict _new(self, dict pdict) noexcept: cdef PolyDict ans = PolyDict.__new__(PolyDict) ans.__repn = pdict return ans - cpdef remove_zeros(self, zero_test=None): + cpdef remove_zeros(self, zero_test=None) noexcept: r""" Remove the entries with zero coefficients. @@ -1366,7 +1366,7 @@ cdef class PolyDict: else: return None -cdef inline bint dual_etuple_iter(ETuple self, ETuple other, size_t *ind1, size_t *ind2, size_t *index, int *exp1, int *exp2): +cdef inline bint dual_etuple_iter(ETuple self, ETuple other, size_t *ind1, size_t *ind2, size_t *index, int *exp1, int *exp2) noexcept: """ This function is a crucial helper function for a number of methods of the ETuple class. @@ -1428,7 +1428,7 @@ cdef class ETuple: question (although, there is no question that this is much faster than the prior use of python dicts). """ - cdef ETuple _new(self): + cdef ETuple _new(self) noexcept: """ Quickly creates a new initialized ETuple with the same length as self. @@ -1615,7 +1615,7 @@ cdef class ETuple: else: return self.get_exp(i) - cdef size_t get_position(self, size_t i, size_t start, size_t end): + cdef size_t get_position(self, size_t i, size_t start, size_t end) noexcept: r""" Return where to insert ``i`` in the data between ``start`` and ``end``. """ @@ -1640,7 +1640,7 @@ cdef class ETuple: left = mid return right - cdef int get_exp(self, size_t i): + cdef int get_exp(self, size_t i) noexcept: """ Return the exponent for the ``i``-th variable. """ @@ -1973,7 +1973,7 @@ cdef class ETuple: ind1 += 2 return deg - cpdef ETuple eadd(self, ETuple other): + cpdef ETuple eadd(self, ETuple other) noexcept: """ Return the vector addition of ``self`` with ``other``. @@ -2023,7 +2023,7 @@ cdef class ETuple: result._nonzero += 1 return result - cpdef ETuple eadd_p(self, int other, size_t pos): + cpdef ETuple eadd_p(self, int other, size_t pos) noexcept: """ Add ``other`` to ``self`` at position ``pos``. @@ -2111,7 +2111,7 @@ cdef class ETuple: return result - cpdef ETuple eadd_scaled(self, ETuple other, int scalar): + cpdef ETuple eadd_scaled(self, ETuple other, int scalar) noexcept: """ Vector addition of ``self`` with ``scalar * other``. @@ -2150,7 +2150,7 @@ cdef class ETuple: result._nonzero += 1 return result - cpdef ETuple esub(self, ETuple other): + cpdef ETuple esub(self, ETuple other) noexcept: """ Vector subtraction of ``self`` with ``other``. @@ -2188,7 +2188,7 @@ cdef class ETuple: result._nonzero += 1 return result - cpdef ETuple emul(self, int factor): + cpdef ETuple emul(self, int factor) noexcept: """ Scalar Vector multiplication of ``self``. @@ -2212,7 +2212,7 @@ cdef class ETuple: result._data[2 * ind + 1] = self._data[2 * ind + 1] * factor return result - cpdef ETuple emax(self, ETuple other): + cpdef ETuple emax(self, ETuple other) noexcept: """ Vector of maximum of components of ``self`` and ``other``. @@ -2259,7 +2259,7 @@ cdef class ETuple: result._nonzero += 1 return result - cpdef ETuple emin(self, ETuple other): + cpdef ETuple emin(self, ETuple other) noexcept: """ Vector of minimum of components of ``self`` and ``other``. @@ -2329,7 +2329,7 @@ cdef class ETuple: result += exp1 * exp2 return result - cpdef ETuple escalar_div(self, int n): + cpdef ETuple escalar_div(self, int n) noexcept: r""" Divide each exponent by ``n``. @@ -2370,7 +2370,7 @@ cdef class ETuple: result._nonzero += 1 return result - cpdef ETuple divide_by_gcd(self, ETuple other): + cpdef ETuple divide_by_gcd(self, ETuple other) noexcept: """ Return ``self / gcd(self, other)``. @@ -2413,7 +2413,7 @@ cdef class ETuple: ind1 += 2 return result - cpdef ETuple divide_by_var(self, size_t pos): + cpdef ETuple divide_by_var(self, size_t pos) noexcept: """ Return division of ``self`` by the variable with index ``pos``. @@ -2501,7 +2501,7 @@ cdef class ETuple: return True - cpdef bint is_constant(self): + cpdef bint is_constant(self) noexcept: """ Return if all exponents are zero in the tuple. @@ -2540,7 +2540,7 @@ cdef class ETuple: return False return True - cpdef list nonzero_positions(self, bint sort=False): + cpdef list nonzero_positions(self, bint sort=False) noexcept: """ Return the positions of non-zero exponents in the tuple. @@ -2559,7 +2559,7 @@ cdef class ETuple: cdef size_t ind return [self._data[2 * ind] for ind in range(self._nonzero)] - cpdef common_nonzero_positions(self, ETuple other, bint sort=False): + cpdef common_nonzero_positions(self, ETuple other, bint sort=False) noexcept: """ Returns an optionally sorted list of non zero positions either in self or other, i.e. the only positions that need to be @@ -2582,7 +2582,7 @@ cdef class ETuple: else: return res - cpdef list nonzero_values(self, bint sort=True): + cpdef list nonzero_values(self, bint sort=True) noexcept: """ Return the non-zero values of the tuple. @@ -2604,7 +2604,7 @@ cdef class ETuple: cdef size_t ind return [self._data[2 * ind + 1] for ind in range(self._nonzero)] - cpdef ETuple reversed(self): + cpdef ETuple reversed(self) noexcept: """ Return the reversed ETuple of ``self``. diff --git a/src/sage/rings/polynomial/polynomial_compiled.pxd b/src/sage/rings/polynomial/polynomial_compiled.pxd index 9a9818e767c..3e5c9f4611f 100644 --- a/src/sage/rings/polynomial/polynomial_compiled.pxd +++ b/src/sage/rings/polynomial/polynomial_compiled.pxd @@ -8,22 +8,22 @@ cdef class CompiledPolynomialFunction: cdef generic_pd _dag cdef object _coeffs - cdef object _parse_structure(CompiledPolynomialFunction) - cdef generic_pd _get_gap(CompiledPolynomialFunction, BinaryTree, int) - cdef void _fill_gaps_binary(CompiledPolynomialFunction, BinaryTree) - cdef object eval(CompiledPolynomialFunction, object) + cdef object _parse_structure(CompiledPolynomialFunction) noexcept + cdef generic_pd _get_gap(CompiledPolynomialFunction, BinaryTree, int) noexcept + cdef void _fill_gaps_binary(CompiledPolynomialFunction, BinaryTree) noexcept + cdef object eval(CompiledPolynomialFunction, object) noexcept cdef class generic_pd: cdef object value cdef int refs, hits cdef int label cdef int eval(self, vars, coeffs) except -2 - cdef generic_pd nodummies(generic_pd) - cdef void reset(self) + cdef generic_pd nodummies(generic_pd) noexcept + cdef void reset(self) noexcept cdef class dummy_pd(generic_pd): cdef generic_pd link - cdef void fill(dummy_pd self, generic_pd link) + cdef void fill(dummy_pd self, generic_pd link) noexcept cdef class var_pd(generic_pd): cdef int index diff --git a/src/sage/rings/polynomial/polynomial_compiled.pyx b/src/sage/rings/polynomial/polynomial_compiled.pyx index f7568893309..1145dfae7ea 100644 --- a/src/sage/rings/polynomial/polynomial_compiled.pyx +++ b/src/sage/rings/polynomial/polynomial_compiled.pyx @@ -119,7 +119,7 @@ cdef class CompiledPolynomialFunction: def __call__(self, x): return self.eval(x) - cdef object eval(CompiledPolynomialFunction self, object x): + cdef object eval(CompiledPolynomialFunction self, object x) noexcept: cdef object temp try: pd_eval(self._dag, x, self._coeffs) #see further down @@ -130,7 +130,7 @@ cdef class CompiledPolynomialFunction: self._dag.reset() raise TypeError(msg) - cdef object _parse_structure(CompiledPolynomialFunction self): + cdef object _parse_structure(CompiledPolynomialFunction self) noexcept: """ Loop through the coefficients of the polynomial, and collect coefficient gap widths. Meanwhile, construct the evaluation @@ -169,7 +169,7 @@ cdef class CompiledPolynomialFunction: return gaps, s - cdef generic_pd _get_gap(CompiledPolynomialFunction self, BinaryTree gaps, int gap): + cdef generic_pd _get_gap(CompiledPolynomialFunction self, BinaryTree gaps, int gap) noexcept: """ Find an entry in the BinaryTree gaps, identified by the int gap. If such an entry does not exist, create it and put it in the tree. @@ -184,7 +184,7 @@ cdef class CompiledPolynomialFunction: gaps.insert(gap,g) return g - cdef void _fill_gaps_binary(CompiledPolynomialFunction self, BinaryTree gaps): + cdef void _fill_gaps_binary(CompiledPolynomialFunction self, BinaryTree gaps) noexcept: """ The desired gaps come in a tree, filled with dummy nodes (with the exception of the var node, which is not a dummy). The nodes are @@ -352,7 +352,7 @@ cdef inline int pd_eval(generic_pd pd, object vars, object coeffs) except -2: pd.eval(vars, coeffs) pd.hits += 1 -cdef inline void pd_clean(generic_pd pd): +cdef inline void pd_clean(generic_pd pd) noexcept: if pd.hits >= pd.refs: pd.value = None pd.hits = 0 @@ -367,10 +367,10 @@ cdef class generic_pd: cdef int eval(generic_pd self, object vars, object coeffs) except -2: raise NotImplementedError - cdef generic_pd nodummies(generic_pd self): + cdef generic_pd nodummies(generic_pd self) noexcept: return self - cdef void reset(generic_pd self): + cdef void reset(generic_pd self) noexcept: self.hits = 0 self.value = None @@ -378,10 +378,10 @@ cdef class dummy_pd(generic_pd): def __init__(dummy_pd self, int label): self.label = label - cdef void fill(dummy_pd self, generic_pd link): + cdef void fill(dummy_pd self, generic_pd link) noexcept: self.link = link - cdef generic_pd nodummies(dummy_pd self): + cdef generic_pd nodummies(dummy_pd self) noexcept: #sorry guys, this is my stop self.link.refs = self.refs return self.link.nodummies() @@ -417,7 +417,7 @@ cdef class coeff_pd(generic_pd): def __repr__(self): return "a%s" % (self.index) - cdef void reset(self): + cdef void reset(self) noexcept: pass cdef class unary_pd(generic_pd): @@ -426,11 +426,11 @@ cdef class unary_pd(generic_pd): self.operand = operand self.operand.refs += 1 - cdef generic_pd nodummies(self): + cdef generic_pd nodummies(self) noexcept: self.operand = self.operand.nodummies() return self - cdef void reset(self): + cdef void reset(self) noexcept: generic_pd.reset(self) self.operand.reset() @@ -467,12 +467,12 @@ cdef class binary_pd(generic_pd): self.left.refs+= 1 self.right.refs+= 1 - cdef generic_pd nodummies(self): + cdef generic_pd nodummies(self) noexcept: self.left = self.left.nodummies() self.right = self.right.nodummies() return self - cdef void reset(self): + cdef void reset(self) noexcept: generic_pd.reset(self) self.left.reset() self.right.reset() diff --git a/src/sage/rings/polynomial/polynomial_complex_arb.pxd b/src/sage/rings/polynomial/polynomial_complex_arb.pxd index e54d85e961b..29e3cc4fd61 100644 --- a/src/sage/rings/polynomial/polynomial_complex_arb.pxd +++ b/src/sage/rings/polynomial/polynomial_complex_arb.pxd @@ -3,4 +3,4 @@ from sage.rings.polynomial.polynomial_element cimport Polynomial cdef class Polynomial_complex_arb(Polynomial): cdef acb_poly_struct[1] _poly # https://github.com/cython/cython/issues/1984 - cdef Polynomial_complex_arb _new(self) + cdef Polynomial_complex_arb _new(self) noexcept diff --git a/src/sage/rings/polynomial/polynomial_complex_arb.pyx b/src/sage/rings/polynomial/polynomial_complex_arb.pyx index 985f1dec394..3e3482330a6 100644 --- a/src/sage/rings/polynomial/polynomial_complex_arb.pyx +++ b/src/sage/rings/polynomial/polynomial_complex_arb.pyx @@ -33,7 +33,7 @@ from sage.structure.element cimport Element from sage.structure.element import coerce_binop -cdef inline long prec(Polynomial_complex_arb pol): +cdef inline long prec(Polynomial_complex_arb pol) noexcept: return pol._parent._base._prec @@ -87,7 +87,7 @@ cdef class Polynomial_complex_arb(Polynomial): """ acb_poly_clear(self._poly) - cdef Polynomial_complex_arb _new(self): + cdef Polynomial_complex_arb _new(self) noexcept: r""" Return a new polynomial with the same parent as this one. """ @@ -230,13 +230,13 @@ cdef class Polynomial_complex_arb(Polynomial): """ return smallInteger(acb_poly_degree(self._poly)) - cdef get_unsafe(self, Py_ssize_t n): + cdef get_unsafe(self, Py_ssize_t n) noexcept: cdef ComplexBall res = ComplexBall.__new__(ComplexBall) res._parent = self._parent._base acb_poly_get_coeff_acb(res.value, self._poly, n) return res - cpdef list list(self, bint copy=True): + cpdef list list(self, bint copy=True) noexcept: r""" Return the coefficient list of this polynomial. @@ -270,7 +270,7 @@ cdef class Polynomial_complex_arb(Polynomial): # Ring and Euclidean arithmetic - cpdef _add_(self, other): + cpdef _add_(self, other) noexcept: r""" Return the sum of two polynomials. @@ -290,7 +290,7 @@ cdef class Polynomial_complex_arb(Polynomial): sig_off() return res - cpdef _neg_(self): + cpdef _neg_(self) noexcept: r""" Return the opposite of this polynomial. @@ -306,7 +306,7 @@ cdef class Polynomial_complex_arb(Polynomial): sig_off() return res - cpdef _sub_(self, other): + cpdef _sub_(self, other) noexcept: r""" Return the difference of two polynomials. @@ -326,7 +326,7 @@ cdef class Polynomial_complex_arb(Polynomial): sig_off() return res - cpdef _mul_(self, other): + cpdef _mul_(self, other) noexcept: r""" Return the product of two polynomials. @@ -347,7 +347,7 @@ cdef class Polynomial_complex_arb(Polynomial): sig_off() return res - cpdef _lmul_(self, Element a): + cpdef _lmul_(self, Element a) noexcept: r""" TESTS:: @@ -367,7 +367,7 @@ cdef class Polynomial_complex_arb(Polynomial): sig_off() return res - cpdef _rmul_(self, Element a): + cpdef _rmul_(self, Element a) noexcept: r""" TESTS:: @@ -428,7 +428,7 @@ cdef class Polynomial_complex_arb(Polynomial): # Syntactic transformations - cpdef Polynomial truncate(self, long n): + cpdef Polynomial truncate(self, long n) noexcept: r""" Return the truncation to degree `n - 1` of this polynomial. @@ -459,7 +459,7 @@ cdef class Polynomial_complex_arb(Polynomial): sig_off() return res - cdef _inplace_truncate(self, long n): + cdef _inplace_truncate(self, long n) noexcept: if n < 0: n = 0 acb_poly_truncate(self._poly, n) @@ -533,7 +533,7 @@ cdef class Polynomial_complex_arb(Polynomial): # Truncated and power series arithmetic - cpdef Polynomial _mul_trunc_(self, Polynomial other, long n): + cpdef Polynomial _mul_trunc_(self, Polynomial other, long n) noexcept: r""" Return the product of ``self`` and ``other``, truncated before degree `n`. @@ -561,7 +561,7 @@ cdef class Polynomial_complex_arb(Polynomial): sig_off() return res - cpdef Polynomial inverse_series_trunc(self, long n): + cpdef Polynomial inverse_series_trunc(self, long n) noexcept: r""" Return the power series expansion at 0 of the inverse of this polynomial, truncated before degree `n`. @@ -589,7 +589,7 @@ cdef class Polynomial_complex_arb(Polynomial): sig_off() return res - cpdef Polynomial _power_trunc(self, unsigned long expo, long n): + cpdef Polynomial _power_trunc(self, unsigned long expo, long n) noexcept: r""" Return a power of this polynomial, truncated before degree `n`. diff --git a/src/sage/rings/polynomial/polynomial_element.pxd b/src/sage/rings/polynomial/polynomial_element.pxd index 5dcbf4597d0..b337919a807 100644 --- a/src/sage/rings/polynomial/polynomial_element.pxd +++ b/src/sage/rings/polynomial/polynomial_element.pxd @@ -7,58 +7,58 @@ from .polynomial_compiled cimport CompiledPolynomialFunction cdef class Polynomial(CommutativePolynomial): - cdef Polynomial _new_generic(self, list coeffs) + cdef Polynomial _new_generic(self, list coeffs) noexcept cdef char _is_gen cdef CompiledPolynomialFunction _compiled - cpdef Polynomial truncate(self, long n) - cpdef Polynomial inverse_series_trunc(self, long prec) + cpdef Polynomial truncate(self, long n) noexcept + cpdef Polynomial inverse_series_trunc(self, long prec) noexcept cdef long _hash_c(self) except -1 - cpdef constant_coefficient(self) - cpdef Polynomial _new_constant_poly(self, a, Parent P) - cpdef list list(self, bint copy=*) - cpdef _mul_generic(self, right) - cdef _square_generic(self) + cpdef constant_coefficient(self) noexcept + cpdef Polynomial _new_constant_poly(self, a, Parent P) noexcept + cpdef list list(self, bint copy=*) noexcept + cpdef _mul_generic(self, right) noexcept + cdef _square_generic(self) noexcept cpdef bint is_zero(self) except -1 cpdef bint is_one(self) except -1 cpdef bint is_term(self) except -1 - cpdef dict _mpoly_dict_recursive(self, tuple variables=*, base_ring=*) + cpdef dict _mpoly_dict_recursive(self, tuple variables=*, base_ring=*) noexcept - cpdef _add_(self, other) - cpdef _mul_(self, other) - cpdef _floordiv_(self, right) - cpdef Polynomial _mul_trunc_(self, Polynomial right, long n) - cpdef Polynomial _power_trunc(self, unsigned long n, long prec) - cdef Polynomial _mul_term(self, Polynomial term, bint term_on_right) + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept + cpdef _floordiv_(self, right) noexcept + cpdef Polynomial _mul_trunc_(self, Polynomial right, long n) noexcept + cpdef Polynomial _power_trunc(self, unsigned long n, long prec) noexcept + cdef Polynomial _mul_term(self, Polynomial term, bint term_on_right) noexcept # UNSAFE, only call from an inplace operator # may return a new element if not possible to modify inplace - cdef _inplace_truncate(self, long n) + cdef _inplace_truncate(self, long n) noexcept - cdef get_coeff_c(self, Py_ssize_t i) - cdef get_unsafe(self, Py_ssize_t i) - cpdef long number_of_terms(self) + cdef get_coeff_c(self, Py_ssize_t i) noexcept + cdef get_unsafe(self, Py_ssize_t i) noexcept + cpdef long number_of_terms(self) noexcept # See 23227 - cpdef _add_(self, right) - cpdef _mul_(self, right) - cpdef _floordiv_(self, right) + cpdef _add_(self, right) noexcept + cpdef _mul_(self, right) noexcept + cpdef _floordiv_(self, right) noexcept cdef public dict _cached_methods cdef class Polynomial_generic_dense(Polynomial): - cdef Polynomial_generic_dense _new_c(self, list coeffs, Parent P) + cdef Polynomial_generic_dense _new_c(self, list coeffs, Parent P) noexcept cdef list _coeffs cdef int _normalize(self) except -1 - cpdef list list(self, bint copy=*) + cpdef list list(self, bint copy=*) noexcept cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense): pass -cpdef is_Polynomial(f) -cpdef Polynomial generic_power_trunc(Polynomial p, Integer n, long prec) -cpdef list _dict_to_list(dict x, zero) +cpdef is_Polynomial(f) noexcept +cpdef Polynomial generic_power_trunc(Polynomial p, Integer n, long prec) noexcept +cpdef list _dict_to_list(dict x, zero) noexcept -cpdef bint polynomial_is_variable(x) +cpdef bint polynomial_is_variable(x) noexcept diff --git a/src/sage/rings/polynomial/polynomial_element.pyx b/src/sage/rings/polynomial/polynomial_element.pyx index a5b7f937cfe..7eaa195cbfe 100644 --- a/src/sage/rings/polynomial/polynomial_element.pyx +++ b/src/sage/rings/polynomial/polynomial_element.pyx @@ -134,7 +134,7 @@ from sage.misc.superseded import deprecation_cython as deprecation, deprecated_f from sage.misc.cachefunc import cached_method -cpdef is_Polynomial(f): +cpdef is_Polynomial(f) noexcept: """ Return ``True`` if ``f`` is of type univariate polynomial. @@ -244,7 +244,7 @@ cdef class Polynomial(CommutativePolynomial): CommutativeAlgebraElement.__init__(self, parent) self._is_gen = is_gen - cdef Polynomial _new_generic(self, list coeffs): + cdef Polynomial _new_generic(self, list coeffs) noexcept: r""" Quickly construct a new polynomial of the same type as ``self``, bypassing the parent's element constructor. @@ -258,7 +258,7 @@ cdef class Polynomial(CommutativePolynomial): n -= 1 return type(self)(self._parent, coeffs, check=False) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: r""" Add two polynomials. @@ -287,7 +287,7 @@ cdef class Polynomial(CommutativePolynomial): low = [x[i] + y[i] for i in range(min)] return self._new_generic(low + high) - cpdef _neg_(self): + cpdef _neg_(self) noexcept: return self._new_generic([-x for x in self.list(copy=False)]) cpdef bint is_zero(self) except -1: @@ -370,7 +370,7 @@ cdef class Polynomial(CommutativePolynomial): return point(z, *args, **kwds) raise NotImplementedError("plotting of polynomials over %s not implemented"%R) - cpdef _lmul_(self, Element left): + cpdef _lmul_(self, Element left) noexcept: """ Multiply self on the left by a scalar. @@ -390,7 +390,7 @@ cdef class Polynomial(CommutativePolynomial): return self._parent.zero() return self._parent(left) * self - cpdef _rmul_(self, Element right): + cpdef _rmul_(self, Element right) noexcept: """ Multiply self on the right by a scalar. @@ -1010,7 +1010,7 @@ cdef class Polynomial(CommutativePolynomial): expr *= x return expr - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: r""" Compare the two polynomials self and other. @@ -1176,7 +1176,7 @@ cdef class Polynomial(CommutativePolynomial): return self.get_coeff_c(pyobject_to_long(n)) - cdef get_coeff_c(self, Py_ssize_t i): + cdef get_coeff_c(self, Py_ssize_t i) noexcept: """ Return the `i`-th coefficient of ``self``. """ @@ -1186,7 +1186,7 @@ cdef class Polynomial(CommutativePolynomial): else: return self._parent._base.zero() - cdef get_unsafe(self, Py_ssize_t i): + cdef get_unsafe(self, Py_ssize_t i) noexcept: """ Return the `i`-th coefficient of ``self``. @@ -1668,7 +1668,7 @@ cdef class Polynomial(CommutativePolynomial): else: raise ValueError("Impossible inverse modulo") - cpdef Polynomial inverse_series_trunc(self, long prec): + cpdef Polynomial inverse_series_trunc(self, long prec) noexcept: r""" Return a polynomial approximation of precision ``prec`` of the inverse series of this polynomial. @@ -1783,7 +1783,7 @@ cdef class Polynomial(CommutativePolynomial): """ raise NotImplementedError("only implemented for certain base rings") - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ EXAMPLES:: @@ -1839,7 +1839,7 @@ cdef class Polynomial(CommutativePolynomial): else: return self._mul_generic(right) - cpdef Polynomial _mul_trunc_(self, Polynomial right, long n): + cpdef Polynomial _mul_trunc_(self, Polynomial right, long n) noexcept: r""" Return the truncated multiplication of two polynomials up to ``n``. @@ -2630,7 +2630,7 @@ cdef class Polynomial(CommutativePolynomial): return self._power_trunc(mpz_get_ui(ZZn.value), prec) return generic_power_trunc(self, ZZn, pyobject_to_long(prec)) - cpdef Polynomial _power_trunc(self, unsigned long n, long prec): + cpdef Polynomial _power_trunc(self, unsigned long n, long prec) noexcept: r""" Truncated ``n``-th power of this polynomial up to precision ``prec`` @@ -2918,7 +2918,7 @@ cdef class Polynomial(CommutativePolynomial): """ raise IndexError("polynomials are immutable") - cpdef _floordiv_(self, right): + cpdef _floordiv_(self, right) noexcept: r""" Quotient of division of ``self`` by ``other``. This is denoted //. @@ -3002,7 +3002,7 @@ cdef class Polynomial(CommutativePolynomial): return (self.degree() == self.valuation() and self.leading_coefficient()._is_atomic()) - cpdef _mul_generic(self, right): + cpdef _mul_generic(self, right) noexcept: """ Compute the product of ``self`` and ``right`` using the classical quadratic algorithm. This method is the default for inexact rings. @@ -3066,7 +3066,7 @@ cdef class Polynomial(CommutativePolynomial): cdef list y = right.list(copy=False) return self._new_generic(do_schoolbook_product(x, y, -1)) - cdef _square_generic(self): + cdef _square_generic(self) noexcept: cdef list x = self.list(copy=False) cdef Py_ssize_t i, j cdef Py_ssize_t d = len(x)-1 @@ -3333,7 +3333,7 @@ cdef class Polynomial(CommutativePolynomial): @cython.boundscheck(False) @cython.wraparound(False) - cdef Polynomial _mul_term(self, Polynomial term, bint term_on_right): + cdef Polynomial _mul_term(self, Polynomial term, bint term_on_right) noexcept: """ Return the product ``self * term``, where ``term`` is a polynomial with a single term. @@ -3367,7 +3367,7 @@ cdef class Polynomial(CommutativePolynomial): """ return self._parent.base_ring() - cpdef base_extend(self, R): + cpdef base_extend(self, R) noexcept: """ Return a copy of this polynomial but with coefficients in ``R``, if there is a natural map from the coefficient ring of ``self`` to ``R``. @@ -3460,7 +3460,7 @@ cdef class Polynomial(CommutativePolynomial): else: return self._parent.change_ring(R)(self.list(copy=False)) - cpdef dict _mpoly_dict_recursive(self, tuple variables=None, base_ring=None): + cpdef dict _mpoly_dict_recursive(self, tuple variables=None, base_ring=None) noexcept: """ Return a dict of coefficient entries suitable for construction of a MPolynomial_polydict with the given variables. @@ -5448,15 +5448,12 @@ cdef class Polynomial(CommutativePolynomial): if self.degree() <= 1: return R.fraction_field() - from sage.rings.number_field.number_field import is_NumberField, NumberField - if is_IntegerRing(R): from sage.rings.number_field.number_field import NumberField return NumberField(self, names) from sage.rings.number_field.number_field_base import NumberField as NumberField_base - - if sage.rings.rational_field.is_RationalField(R) or isinstance(R, NumberField_base): + if isinstance(R, NumberField_base): from sage.rings.number_field.number_field import NumberField return NumberField(self, names) @@ -5627,7 +5624,7 @@ cdef class Polynomial(CommutativePolynomial): return M - cpdef constant_coefficient(self): + cpdef constant_coefficient(self) noexcept: """ Return the constant coefficient of this polynomial. @@ -5645,7 +5642,7 @@ cdef class Polynomial(CommutativePolynomial): # self.degree() >= 0 return self.get_unsafe(0) - cpdef Polynomial _new_constant_poly(self, a, Parent P): + cpdef Polynomial _new_constant_poly(self, a, Parent P) noexcept: """ Create a new constant polynomial from a in P, which MUST be an element of the base ring of P (this is not checked). @@ -6022,14 +6019,14 @@ cdef class Polynomial(CommutativePolynomial): K = self.base_ring() if K in NumberFields() or isinstance(K, sage.rings.abc.Order) or is_IntegerRing(K): from sage.schemes.projective.projective_space import ProjectiveSpace - P = ProjectiveSpace(K, self.number_of_terms()-1) + P = ProjectiveSpace(K, self.number_of_terms() - 1) return P.point(self.coefficients()).global_height(prec=prec) elif isinstance(K, sage.rings.abc.AlgebraicField): from sage.rings.qqbar import number_field_elements_from_algebraics from sage.schemes.projective.projective_space import ProjectiveSpace K_pre, P, phi = number_field_elements_from_algebraics(self.coefficients()) - Pr = ProjectiveSpace(K_pre, len(P)-1) + Pr = ProjectiveSpace(K_pre, len(P) - 1) return Pr.point(P).global_height(prec=prec) raise TypeError("Must be over a Numberfield or a Numberfield Order.") @@ -6078,7 +6075,7 @@ cdef class Polynomial(CommutativePolynomial): prec = 53 K = FractionField(self.base_ring()) - if not (K in NumberFields() or isinstance(K, sage.rings.abc.Order) or is_IntegerRing(K)): + if K not in NumberFields(): raise TypeError("must be over a Numberfield or a Numberfield order") return max([K(c).local_height(v, prec=prec) for c in self.coefficients()]) @@ -6127,7 +6124,7 @@ cdef class Polynomial(CommutativePolynomial): prec = 53 K = FractionField(self.base_ring()) - if not (K in NumberFields() or isinstance(K, sage.rings.abc.Order) or is_IntegerRing(K)): + if K not in NumberFields(): return TypeError("must be over a Numberfield or a Numberfield Order") if K == QQ: @@ -6154,7 +6151,7 @@ cdef class Polynomial(CommutativePolynomial): cdef Py_ssize_t i return [i for i, c in enumerate(self.list(copy=False)) if c] - cpdef list list(self, bint copy=True): + cpdef list list(self, bint copy=True) noexcept: """ Return a new copy of the list of the underlying elements of ``self``. @@ -9797,7 +9794,7 @@ cdef class Polynomial(CommutativePolynomial): """ return self.shift(-k) - cpdef Polynomial truncate(self, long n): + cpdef Polynomial truncate(self, long n) noexcept: r""" Return the polynomial of degree `< n` which is equivalent to self modulo `x^n`. @@ -9818,7 +9815,7 @@ cdef class Polynomial(CommutativePolynomial): # We must not have check=False, since 0 must not have _coeffs = [0]. return self._parent(self[:n])#, check=False) - cdef _inplace_truncate(self, long prec): + cdef _inplace_truncate(self, long prec) noexcept: return self.truncate(prec) @cached_method @@ -10126,7 +10123,7 @@ cdef class Polynomial(CommutativePolynomial): return RR(sum([abs(i)**p for i in coeffs]))**(1/p) - cpdef long number_of_terms(self): + cpdef long number_of_terms(self) noexcept: """ Return the number of non-zero coefficients of ``self``. @@ -11300,7 +11297,7 @@ cdef class Polynomial(CommutativePolynomial): @cython.boundscheck(False) @cython.wraparound(False) @cython.overflowcheck(False) -cdef list do_schoolbook_product(list x, list y, Py_ssize_t deg): +cdef list do_schoolbook_product(list x, list y, Py_ssize_t deg) noexcept: """ Compute the truncated multiplication of two polynomials represented by lists, using the schoolbook algorithm. @@ -11352,7 +11349,7 @@ cdef list do_schoolbook_product(list x, list y, Py_ssize_t deg): @cython.boundscheck(False) @cython.wraparound(False) @cython.overflowcheck(False) -cdef list do_karatsuba_different_size(list left, list right, Py_ssize_t K_threshold): +cdef list do_karatsuba_different_size(list left, list right, Py_ssize_t K_threshold) noexcept: """ Multiply two polynomials of different degrees by splitting the one of largest degree in chunks that are multiplied with the other using the @@ -11434,7 +11431,7 @@ cdef list do_karatsuba_different_size(list left, list right, Py_ssize_t K_thresh @cython.boundscheck(False) @cython.wraparound(False) @cython.overflowcheck(False) -cdef list do_karatsuba(list left, list right, Py_ssize_t K_threshold,Py_ssize_t start_l, Py_ssize_t start_r,Py_ssize_t num_elts): +cdef list do_karatsuba(list left, list right, Py_ssize_t K_threshold,Py_ssize_t start_l, Py_ssize_t start_r,Py_ssize_t num_elts) noexcept: """ Core routine for Karatsuba multiplication. This function works for two polynomials of the same degree. @@ -11613,14 +11610,14 @@ cdef class Polynomial_generic_dense(Polynomial): else: self._coeffs = x - cdef Polynomial_generic_dense _new_c(self, list coeffs, Parent P): + cdef Polynomial_generic_dense _new_c(self, list coeffs, Parent P) noexcept: cdef type t = type(self) cdef Polynomial_generic_dense f = t.__new__(t) f._parent = P f._coeffs = coeffs return f - cpdef Polynomial _new_constant_poly(self, a, Parent P): + cpdef Polynomial _new_constant_poly(self, a, Parent P) noexcept: """ Create a new constant polynomial in P with value a. @@ -11692,7 +11689,7 @@ cdef class Polynomial_generic_dense(Polynomial): @cython.boundscheck(False) @cython.wraparound(False) - cdef Polynomial _mul_term(self, Polynomial term, bint term_on_right): + cdef Polynomial _mul_term(self, Polynomial term, bint term_on_right) noexcept: """ Return the product ``self * term``, where ``term`` is a polynomial with a single term. @@ -11744,7 +11741,7 @@ cdef class Polynomial_generic_dense(Polynomial): @cython.boundscheck(False) @cython.wraparound(False) - cdef get_unsafe(self, Py_ssize_t n): + cdef get_unsafe(self, Py_ssize_t n) noexcept: """ Return the `n`-th coefficient of ``self``. @@ -11841,7 +11838,7 @@ cdef class Polynomial_generic_dense(Polynomial): res._normalize() return res - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: r""" Add two polynomials. @@ -11872,7 +11869,7 @@ cdef class Polynomial_generic_dense(Polynomial): else: return self._new_c(low + high, self._parent) - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: cdef Polynomial_generic_dense res cdef Py_ssize_t check=0, i, min x = (self)._coeffs @@ -11893,7 +11890,7 @@ cdef class Polynomial_generic_dense(Polynomial): else: return self._new_c(low + high, self._parent) - cpdef _rmul_(self, Element c): + cpdef _rmul_(self, Element c) noexcept: if not self._coeffs: return self if c._parent is not (self._coeffs[0])._parent: @@ -11905,7 +11902,7 @@ cdef class Polynomial_generic_dense(Polynomial): res._normalize() return res - cpdef _lmul_(self, Element c): + cpdef _lmul_(self, Element c) noexcept: if not self._coeffs: return self if c._parent is not (self._coeffs[0])._parent: @@ -11917,7 +11914,7 @@ cdef class Polynomial_generic_dense(Polynomial): res._normalize() return res - cpdef constant_coefficient(self): + cpdef constant_coefficient(self) noexcept: """ Return the constant coefficient of this polynomial. @@ -11936,7 +11933,7 @@ cdef class Polynomial_generic_dense(Polynomial): else: return self._coeffs[0] - cpdef list list(self, bint copy=True): + cpdef list list(self, bint copy=True) noexcept: """ Return a new copy of the list of the underlying elements of ``self``. @@ -12123,7 +12120,7 @@ cdef class Polynomial_generic_dense(Polynomial): return self._new_c(quo,self._parent), self._new_c(x,self._parent)._inplace_truncate(n-1) - cpdef Polynomial truncate(self, long n): + cpdef Polynomial truncate(self, long n) noexcept: r""" Return the polynomial of degree `< n` which is equivalent to self modulo `x^n`. @@ -12157,7 +12154,7 @@ cdef class Polynomial_generic_dense(Polynomial): n -= 1 return self._new_c(self._coeffs[:n], self._parent) - cdef _inplace_truncate(self, long n): + cdef _inplace_truncate(self, long n) noexcept: if n < len(self._coeffs): while n > 0 and not self._coeffs[n-1]: n -= 1 @@ -12208,7 +12205,7 @@ def universal_discriminant(n): return (1 - (n&2))*p.resultant(p.derivative())//pr1.gen(n) -cpdef Polynomial generic_power_trunc(Polynomial p, Integer n, long prec): +cpdef Polynomial generic_power_trunc(Polynomial p, Integer n, long prec) noexcept: r""" Generic truncated power algorithm @@ -12287,7 +12284,7 @@ cpdef Polynomial generic_power_trunc(Polynomial p, Integer n, long prec): return power -cpdef list _dict_to_list(dict x, zero): +cpdef list _dict_to_list(dict x, zero) noexcept: """ Convert a dict to a list. @@ -12465,7 +12462,7 @@ cdef class ConstantPolynomialSection(Map): ... TypeError: not a constant polynomial """ - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ TESTS:: @@ -12577,7 +12574,7 @@ cdef class PolynomialBaseringInjection(Morphism): self._repr_type_str = "Polynomial base injection" self._new_constant_poly_ = self._an_element._new_constant_poly - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ EXAMPLES:: @@ -12595,7 +12592,7 @@ cdef class PolynomialBaseringInjection(Morphism): _new_constant_poly_=self._new_constant_poly_) return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ EXAMPLES:: @@ -12611,7 +12608,7 @@ cdef class PolynomialBaseringInjection(Morphism): self._an_element = _slots['_an_element'] self._new_constant_poly_ = _slots['_new_constant_poly_'] - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ TESTS:: @@ -12627,7 +12624,7 @@ cdef class PolynomialBaseringInjection(Morphism): """ return self._new_constant_poly_(x, self._codomain) - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ TESTS:: @@ -12690,7 +12687,7 @@ cdef class PolynomialBaseringInjection(Morphism): """ return False -cpdef bint polynomial_is_variable(x): +cpdef bint polynomial_is_variable(x) noexcept: r""" Test whether the given polynomial is a variable of its parent ring. diff --git a/src/sage/rings/polynomial/polynomial_gf2x.pyx b/src/sage/rings/polynomial/polynomial_gf2x.pyx index 9dd344ca681..51959a7825c 100644 --- a/src/sage/rings/polynomial/polynomial_gf2x.pyx +++ b/src/sage/rings/polynomial/polynomial_gf2x.pyx @@ -16,7 +16,7 @@ AUTHOR: # to make sure the function get_cparent is found since it is used in # 'polynomial_template.pxi'. -cdef inline cparent get_cparent(parent): +cdef inline cparent get_cparent(parent) noexcept: return 0 # first we include the definitions @@ -70,7 +70,7 @@ cdef class Polynomial_GF2X(Polynomial_template): pass Polynomial_template.__init__(self, parent, x, check, is_gen, construct) - cdef get_unsafe(self, Py_ssize_t i): + cdef get_unsafe(self, Py_ssize_t i) noexcept: """ Return the `i`-th coefficient of ``self``. diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd index b1b593d6a26..b88c2a66a76 100644 --- a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd +++ b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd @@ -7,6 +7,6 @@ from sage.structure.parent cimport Parent cdef class Polynomial_integer_dense_flint(Polynomial): cdef fmpz_poly_t _poly - cdef Polynomial_integer_dense_flint _new(self) - cpdef _unsafe_mutate(self, long n, value) - cpdef Integer content(self) + cdef Polynomial_integer_dense_flint _new(self) noexcept + cpdef _unsafe_mutate(self, long n, value) noexcept + cpdef Integer content(self) noexcept diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx index 7bb023e8452..20a1d75e66c 100644 --- a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx +++ b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx @@ -108,7 +108,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial): """ fmpz_poly_clear(self._poly) - cdef Polynomial_integer_dense_flint _new(self): + cdef Polynomial_integer_dense_flint _new(self) noexcept: r""" Quickly creates a new initialized Polynomial_integer_dense_flint with the correct parent and _is_gen == 0. @@ -118,7 +118,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial): x._is_gen = 0 return x - cpdef Polynomial _new_constant_poly(self, a, Parent P): + cpdef Polynomial _new_constant_poly(self, a, Parent P) noexcept: r""" Quickly creates a new constant polynomial with value a in parent P @@ -473,7 +473,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial): return Polynomial.__call__(self, *x, **kwds) - cpdef Integer content(self): + cpdef Integer content(self) noexcept: r""" Return the greatest common divisor of the coefficients of this polynomial. The sign is the sign of the leading coefficient. The @@ -536,7 +536,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial): return Polynomial_integer_dense_flint, \ (self.parent(), self.list(), False, self.is_gen()) - cdef get_unsafe(self, Py_ssize_t n): + cdef get_unsafe(self, Py_ssize_t n) noexcept: """ Return the `n`-th coefficient of ``self``. @@ -635,7 +635,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial): name = self.parent().latex_variable_names()[0] return self._repr(name=name, latex=True) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: r""" Return ``self`` plus ``right``. @@ -655,7 +655,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial): return x - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: r""" Return ``self`` minus ``right``. @@ -675,7 +675,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial): return x - cpdef _neg_(self): + cpdef _neg_(self) noexcept: r""" Return negative of ``self``. @@ -958,7 +958,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial): return self._parent(rr), ss, tt - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: r""" Return ``self`` multiplied by ``right``. @@ -975,7 +975,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial): sig_off() return x - cpdef Polynomial _mul_trunc_(self, Polynomial right, long n): + cpdef Polynomial _mul_trunc_(self, Polynomial right, long n) noexcept: r""" Truncated multiplication @@ -1006,7 +1006,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial): sig_off() return x - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: r""" Return ``self`` multiplied by ``right``, where ``right`` is a scalar (integer). @@ -1024,7 +1024,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial): sig_off() return x - cpdef _rmul_(self, Element right): + cpdef _rmul_(self, Element right) noexcept: r""" Return ``self`` multiplied by ``right``, where right is a scalar (integer). @@ -1164,7 +1164,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial): sig_off() return res - cpdef Polynomial _power_trunc(self, unsigned long n, long prec): + cpdef Polynomial _power_trunc(self, unsigned long n, long prec) noexcept: r""" Truncated power @@ -1252,7 +1252,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial): sig_off() return res - cpdef Polynomial inverse_series_trunc(self, long prec): + cpdef Polynomial inverse_series_trunc(self, long prec) noexcept: r""" Return a polynomial approximation of precision ``prec`` of the inverse series of this polynomial. @@ -1307,7 +1307,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial): sig_off() return res - cpdef _unsafe_mutate(self, long n, value): + cpdef _unsafe_mutate(self, long n, value) noexcept: r""" Sets coefficient of `x^n` to value. @@ -1730,7 +1730,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial): from sage.rings.polynomial.padics.polynomial_padic import _pari_padic_factorization_to_sage return _pari_padic_factorization_to_sage(G, R, self.leading_coefficient()) - cpdef list list(self, bint copy=True): + cpdef list list(self, bint copy=True) noexcept: """ Return a new copy of the list of the underlying elements of ``self``. diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd index fcd907e1abe..982fafb8ebb 100644 --- a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd +++ b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd @@ -4,4 +4,4 @@ from sage.rings.polynomial.polynomial_element cimport Polynomial cdef class Polynomial_integer_dense_ntl(Polynomial): cdef ZZX_c _poly - cdef Polynomial_integer_dense_ntl _new(self) + cdef Polynomial_integer_dense_ntl _new(self) noexcept diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx index 80a1726bb4e..71234543840 100644 --- a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx +++ b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx @@ -73,7 +73,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial): r""" A dense polynomial over the integers, implemented via NTL. """ - cdef Polynomial_integer_dense_ntl _new(self): + cdef Polynomial_integer_dense_ntl _new(self) noexcept: r""" Quickly creates a new initialized Polynomial_integer_dense_ntl with the correct parent and _is_gen == 0. @@ -338,7 +338,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial): return Polynomial_integer_dense_ntl, \ (self.parent(), self.list(), False, self.is_gen()) - cdef get_unsafe(self, Py_ssize_t n): + cdef get_unsafe(self, Py_ssize_t n) noexcept: """ Return the `n`-th coefficient of ``self``. @@ -428,7 +428,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial): name = self.parent().latex_variable_names()[0] return self._repr(name, latex=True) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: r""" Returns self plus right. @@ -446,7 +446,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial): return x - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: r""" Return self minus right. @@ -464,7 +464,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial): return x - cpdef _neg_(self): + cpdef _neg_(self) noexcept: r""" Returns negative of ``self``. @@ -680,7 +680,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial): return S(rr), ss, tt - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: r""" Returns self multiplied by right. @@ -695,7 +695,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial): (right)._poly) return x - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: r""" Returns self multiplied by right, where right is a scalar (integer). @@ -714,7 +714,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial): ZZX_mul_ZZ(x._poly, self._poly, _right) return x - cpdef _rmul_(self, Element right): + cpdef _rmul_(self, Element right) noexcept: r""" Returns self multiplied by right, where right is a scalar (integer). @@ -1088,7 +1088,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial): from sage.rings.polynomial.padics.polynomial_padic import _pari_padic_factorization_to_sage return _pari_padic_factorization_to_sage(G, R, self.leading_coefficient()) - cpdef list list(self, bint copy=True): + cpdef list list(self, bint copy=True) noexcept: """ Return a new copy of the list of the underlying elements of ``self``. diff --git a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd index 6934acfee8d..f476dc782ce 100644 --- a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd +++ b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd @@ -22,14 +22,14 @@ cdef class Polynomial_dense_mod_n(Polynomial): cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n): cdef zz_pX_c x cdef ntl_zz_pContext_class c - cdef Polynomial_dense_modn_ntl_zz _new(self) - cpdef _mod_(self, right) + cdef Polynomial_dense_modn_ntl_zz _new(self) noexcept + cpdef _mod_(self, right) noexcept cdef class Polynomial_dense_modn_ntl_ZZ(Polynomial_dense_mod_n): cdef ZZ_pX_c x cdef ntl_ZZ_pContext_class c - cdef Polynomial_dense_modn_ntl_ZZ _new(self) - cpdef _mod_(self, right) + cdef Polynomial_dense_modn_ntl_ZZ _new(self) noexcept + cpdef _mod_(self, right) noexcept cdef class Polynomial_dense_mod_p(Polynomial_dense_mod_n): pass diff --git a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx index a8f08f5bc6c..65bd584d9ea 100644 --- a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx +++ b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx @@ -188,7 +188,7 @@ cdef class Polynomial_dense_mod_n(Polynomial): """ return self._poly - cdef get_unsafe(self, Py_ssize_t n): + cdef get_unsafe(self, Py_ssize_t n) noexcept: """ Return the `n`-th coefficient of ``self``. @@ -220,10 +220,10 @@ cdef class Polynomial_dense_mod_n(Polynomial): return (~self)**(-n) return self.parent()(self._poly**n, construct=True) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: return self.parent()(self._poly + (right)._poly, construct=True) - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ EXAMPLES:: @@ -233,7 +233,7 @@ cdef class Polynomial_dense_mod_n(Polynomial): """ return self.parent()(self._poly * (right)._poly, construct=True) - cpdef _lmul_(self, Element c): + cpdef _lmul_(self, Element c) noexcept: try: return self.parent()(ZZ_pX([c], self.parent().modulus()) * self._poly, construct=True) except RuntimeError as msg: # should this really be a TypeError @@ -284,7 +284,7 @@ cdef class Polynomial_dense_mod_n(Polynomial): return self.parent()(self._poly.left_shift(n), construct=True) - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: return self.parent()(self._poly - (right)._poly, construct=True) def __floordiv__(self, right): @@ -316,7 +316,7 @@ cdef class Polynomial_dense_mod_n(Polynomial): """ return smallInteger(max(self._poly.degree(), -1)) - cpdef list list(self, bint copy=True): + cpdef list list(self, bint copy=True) noexcept: """ Return a new copy of the list of the underlying elements of ``self``. @@ -674,7 +674,7 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n): self.x = ntl.x self.c = ntl.c - cdef Polynomial_dense_modn_ntl_zz _new(self): + cdef Polynomial_dense_modn_ntl_zz _new(self) noexcept: cdef Polynomial_dense_modn_ntl_zz y = Polynomial_dense_modn_ntl_zz.__new__(Polynomial_dense_modn_ntl_zz) y.c = self.c y._parent = self._parent @@ -698,7 +698,7 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n): cdef long i return [ zz_p_rep(zz_pX_GetCoeff(self.x, i)) for i from 0 <= i <= zz_pX_deg(self.x) ] - cdef get_unsafe(self, Py_ssize_t n): + cdef get_unsafe(self, Py_ssize_t n) noexcept: """ Return the `n`-th coefficient of ``self``. @@ -720,7 +720,7 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n): self.c.restore_c() zz_pX_SetCoeff_long(self.x, n, value) - cpdef _add_(self, _right): + cpdef _add_(self, _right) noexcept: """ TESTS:: @@ -737,7 +737,7 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n): if do_sig: sig_off() return r - cpdef _sub_(self, _right): + cpdef _sub_(self, _right) noexcept: """ TESTS:: @@ -754,7 +754,7 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n): if do_sig: sig_off() return r - cpdef _mul_(self, _right): + cpdef _mul_(self, _right) noexcept: """ TESTS:: @@ -774,7 +774,7 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n): if do_sig: sig_off() return r - cpdef Polynomial _mul_trunc_(self, Polynomial right, long n): + cpdef Polynomial _mul_trunc_(self, Polynomial right, long n) noexcept: r""" Return the product of ``self`` and ``right`` truncated to the given length `n` @@ -812,7 +812,7 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n): if do_sig: sig_off() return r - cpdef _rmul_(self, Element c): + cpdef _rmul_(self, Element c) noexcept: """ TESTS:: @@ -828,7 +828,7 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n): if do_sig: sig_off() return r - cpdef _lmul_(self, Element c): + cpdef _lmul_(self, Element c) noexcept: """ TESTS:: @@ -938,7 +938,7 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n): sig_off() return q, r - cpdef _floordiv_(self, right): + cpdef _floordiv_(self, right) noexcept: """ Return the whole part of ``self``/``right``, without remainder. @@ -962,7 +962,7 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n): sig_off() return q - cpdef _mod_(self, right): + cpdef _mod_(self, right) noexcept: """ EXAMPLES:: @@ -1169,7 +1169,7 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n): """ return zz_pX_deg(self.x) - cpdef Polynomial truncate(self, long n): + cpdef Polynomial truncate(self, long n) noexcept: """ Return this polynomial mod `x^n`. @@ -1250,17 +1250,17 @@ cdef class Polynomial_dense_modn_ntl_ZZ(Polynomial_dense_mod_n): if self.c is not None: self.c.restore_c() - cdef Polynomial_dense_modn_ntl_ZZ _new(self): + cdef Polynomial_dense_modn_ntl_ZZ _new(self) noexcept: cdef Polynomial_dense_modn_ntl_ZZ y = Polynomial_dense_modn_ntl_ZZ.__new__(Polynomial_dense_modn_ntl_ZZ) y.c = self.c y._parent = self._parent return y - cpdef list list(self, bint copy=True): + cpdef list list(self, bint copy=True) noexcept: return [self.get_unsafe(n) for n from 0 <= n <= self.degree()] - cdef get_unsafe(self, Py_ssize_t n): + cdef get_unsafe(self, Py_ssize_t n) noexcept: """ Return the `n`-th coefficient of ``self``. @@ -1292,7 +1292,7 @@ cdef class Polynomial_dense_modn_ntl_ZZ(Polynomial_dense_mod_n): cdef ntl_ZZ_p val = ntl_ZZ_p(a, self.c) ZZ_pX_SetCoeff(self.x, n, val.x) - cpdef _add_(self, _right): + cpdef _add_(self, _right) noexcept: """ TESTS:: @@ -1309,7 +1309,7 @@ cdef class Polynomial_dense_modn_ntl_ZZ(Polynomial_dense_mod_n): if do_sig: sig_off() return r - cpdef _sub_(self, _right): + cpdef _sub_(self, _right) noexcept: """ TESTS:: @@ -1326,7 +1326,7 @@ cdef class Polynomial_dense_modn_ntl_ZZ(Polynomial_dense_mod_n): if do_sig: sig_off() return r - cpdef _mul_(self, _right): + cpdef _mul_(self, _right) noexcept: """ TESTS:: @@ -1346,7 +1346,7 @@ cdef class Polynomial_dense_modn_ntl_ZZ(Polynomial_dense_mod_n): if do_sig: sig_off() return r - cpdef Polynomial _mul_trunc_(self, Polynomial right, long n): + cpdef Polynomial _mul_trunc_(self, Polynomial right, long n) noexcept: """ Return the product of ``self`` and ``right`` truncated to the given length `n`, only return terms of degree less than `n`. @@ -1384,7 +1384,7 @@ cdef class Polynomial_dense_modn_ntl_ZZ(Polynomial_dense_mod_n): if do_sig: sig_off() return r - cpdef _rmul_(self, Element c): + cpdef _rmul_(self, Element c) noexcept: """ TESTS:: @@ -1401,7 +1401,7 @@ cdef class Polynomial_dense_modn_ntl_ZZ(Polynomial_dense_mod_n): if do_sig: sig_off() return r - cpdef _lmul_(self, Element c): + cpdef _lmul_(self, Element c) noexcept: """ TESTS:: @@ -1495,7 +1495,7 @@ cdef class Polynomial_dense_modn_ntl_ZZ(Polynomial_dense_mod_n): sig_off() return q, r - cpdef _floordiv_(self, right): + cpdef _floordiv_(self, right) noexcept: """ Return the whole part of ``self`` / ``right``, without remainder. @@ -1519,7 +1519,7 @@ cdef class Polynomial_dense_modn_ntl_ZZ(Polynomial_dense_mod_n): sig_off() return q - cpdef _mod_(self, right): + cpdef _mod_(self, right) noexcept: """ EXAMPLES:: @@ -1730,7 +1730,7 @@ cdef class Polynomial_dense_modn_ntl_ZZ(Polynomial_dense_mod_n): """ return ZZ_pX_deg(self.x) - cpdef Polynomial truncate(self, long n): + cpdef Polynomial truncate(self, long n) noexcept: """ Return this polynomial mod `x^n`. diff --git a/src/sage/rings/polynomial/polynomial_rational_flint.pxd b/src/sage/rings/polynomial/polynomial_rational_flint.pxd index f4644f19d04..dacca987830 100644 --- a/src/sage/rings/polynomial/polynomial_rational_flint.pxd +++ b/src/sage/rings/polynomial/polynomial_rational_flint.pxd @@ -13,8 +13,8 @@ from sage.rings.polynomial.polynomial_element cimport Polynomial cdef class Polynomial_rational_flint(Polynomial): cdef fmpq_poly_t _poly - cdef Polynomial_rational_flint _new(self) - cpdef _mod_(self, right) - cpdef _unsafe_mutate(self, unsigned long n, value) - cpdef Polynomial truncate(self, long n) + cdef Polynomial_rational_flint _new(self) noexcept + cpdef _mod_(self, right) noexcept + cpdef _unsafe_mutate(self, unsigned long n, value) noexcept + cpdef Polynomial truncate(self, long n) noexcept diff --git a/src/sage/rings/polynomial/polynomial_rational_flint.pyx b/src/sage/rings/polynomial/polynomial_rational_flint.pyx index b888b31d214..f651c9f3512 100644 --- a/src/sage/rings/polynomial/polynomial_rational_flint.pyx +++ b/src/sage/rings/polynomial/polynomial_rational_flint.pyx @@ -58,7 +58,7 @@ from sage.structure.element import coerce_binop from sage.misc.cachefunc import cached_method -cdef inline bint _do_sig(fmpq_poly_t op): +cdef inline bint _do_sig(fmpq_poly_t op) noexcept: """ Return 1 when signal handling should be carried out for an operation on this polynomial and 0 otherwise. @@ -108,7 +108,7 @@ cdef class Polynomial_rational_flint(Polynomial): # Allocation & initialisation # ########################################################################### - cdef Polynomial_rational_flint _new(self): + cdef Polynomial_rational_flint _new(self) noexcept: """ Quickly creates a new polynomial object in this class. @@ -129,7 +129,7 @@ cdef class Polynomial_rational_flint(Polynomial): res._is_gen = 0 return res - cpdef Polynomial _new_constant_poly(self, x, Parent P): + cpdef Polynomial _new_constant_poly(self, x, Parent P) noexcept: r""" Quickly creates a new constant polynomial with value x in parent P @@ -350,7 +350,7 @@ cdef class Polynomial_rational_flint(Polynomial): self._parent._singular_(singular).set_ring() # Expensive! return singular(self._singular_init_()) - cpdef list list(self, bint copy=True): + cpdef list list(self, bint copy=True) noexcept: """ Return a list with the coefficients of ``self``. @@ -394,7 +394,7 @@ cdef class Polynomial_rational_flint(Polynomial): """ return smallInteger(fmpq_poly_degree(self._poly)) - cdef get_unsafe(self, Py_ssize_t n): + cdef get_unsafe(self, Py_ssize_t n) noexcept: """ Return the `n`-th coefficient of ``self``. @@ -416,7 +416,7 @@ cdef class Polynomial_rational_flint(Polynomial): fmpq_poly_get_coeff_mpq(z.value, self._poly, n) return z - cpdef _unsafe_mutate(self, unsigned long n, value): + cpdef _unsafe_mutate(self, unsigned long n, value) noexcept: """ Sets the `n`-th coefficient of ``self`` to value. @@ -550,7 +550,7 @@ cdef class Polynomial_rational_flint(Polynomial): return Polynomial.__call__(self, *x, **kwds) - cpdef Polynomial truncate(self, long n): + cpdef Polynomial truncate(self, long n) noexcept: """ Return self truncated modulo `t^n`. @@ -837,7 +837,7 @@ cdef class Polynomial_rational_flint(Polynomial): # Arithmetic # ########################################################################### - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Return the sum of two rational polynomials. @@ -865,7 +865,7 @@ cdef class Polynomial_rational_flint(Polynomial): if do_sig: sig_off() return res - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Return the difference of two rational polynomials. @@ -893,7 +893,7 @@ cdef class Polynomial_rational_flint(Polynomial): if do_sig: sig_off() return res - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ Return the difference of two rational polynomials. @@ -1047,7 +1047,7 @@ cdef class Polynomial_rational_flint(Polynomial): sig_off() return d, s, t - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Return the product of ``self`` and ``right``. @@ -1076,7 +1076,7 @@ cdef class Polynomial_rational_flint(Polynomial): if do_sig: sig_off() return res - cpdef Polynomial _mul_trunc_(self, Polynomial right, long n): + cpdef Polynomial _mul_trunc_(self, Polynomial right, long n) noexcept: r""" Truncated multiplication. @@ -1113,7 +1113,7 @@ cdef class Polynomial_rational_flint(Polynomial): if do_sig: sig_off() return res - cpdef _rmul_(self, Element left): + cpdef _rmul_(self, Element left) noexcept: r""" Return ``left * self``, where ``left`` is a rational number. @@ -1133,7 +1133,7 @@ cdef class Polynomial_rational_flint(Polynomial): if do_sig: sig_off() return res - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: r""" Return ``self * right``, where ``right`` is a rational number. @@ -1345,7 +1345,7 @@ cdef class Polynomial_rational_flint(Polynomial): sig_off() return res - cpdef Polynomial inverse_series_trunc(self, long prec): + cpdef Polynomial inverse_series_trunc(self, long prec) noexcept: r""" Return a polynomial approximation of precision ``prec`` of the inverse series of this polynomial. @@ -1393,7 +1393,7 @@ cdef class Polynomial_rational_flint(Polynomial): sig_off() return res - cpdef _mod_(self, right): + cpdef _mod_(self, right) noexcept: """ Return the remainder of ``self`` and ``right`` obtain by Euclidean division. diff --git a/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx b/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx index da5462cddd4..15c65081cd9 100644 --- a/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx +++ b/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx @@ -184,7 +184,7 @@ cdef class PolynomialRealDense(Polynomial): """ return make_PolynomialRealDense, (self._parent, self.list()) - cdef _normalize(self): + cdef _normalize(self) noexcept: """ Remove all leading 0's. """ @@ -197,7 +197,7 @@ cdef class PolynomialRealDense(Polynomial): self._coeffs = check_reallocarray(self._coeffs, i+1, sizeof(mpfr_t)) self._degree = i - cdef get_unsafe(self, Py_ssize_t i): + cdef get_unsafe(self, Py_ssize_t i) noexcept: """ Return the `i`-th coefficient of ``self``. @@ -225,7 +225,7 @@ cdef class PolynomialRealDense(Polynomial): mpfr_set(r.value, self._coeffs[i], self._base_ring.rnd) return r - cdef PolynomialRealDense _new(self, Py_ssize_t degree): + cdef PolynomialRealDense _new(self, Py_ssize_t degree) noexcept: cdef Py_ssize_t i cdef int prec = self._base_ring._prec cdef PolynomialRealDense f = PolynomialRealDense.__new__(PolynomialRealDense) @@ -257,7 +257,7 @@ cdef class PolynomialRealDense(Polynomial): """ return smallInteger(self._degree) - cpdef Polynomial truncate(self, long n): + cpdef Polynomial truncate(self, long n) noexcept: r""" Returns the polynomial of degree `< n` which is equivalent to self modulo `x^n`. @@ -310,7 +310,7 @@ cdef class PolynomialRealDense(Polynomial): return self.truncate(i+1) return self._new(-1) - cpdef shift(self, Py_ssize_t n): + cpdef shift(self, Py_ssize_t n) noexcept: r""" Returns this polynomial multiplied by the power `x^n`. If `n` is negative, terms below `x^n` will be discarded. Does not @@ -351,7 +351,7 @@ cdef class PolynomialRealDense(Polynomial): mpfr_set(f._coeffs[i], self._coeffs[i-n], self._base_ring.rnd) return f - cpdef list list(self, bint copy=True): + cpdef list list(self, bint copy=True) noexcept: """ EXAMPLES:: @@ -386,7 +386,7 @@ cdef class PolynomialRealDense(Polynomial): mpfr_neg(f._coeffs[i], self._coeffs[i], rnd) return f - cpdef _add_(left, _right): + cpdef _add_(left, _right) noexcept: """ EXAMPLES:: @@ -419,7 +419,7 @@ cdef class PolynomialRealDense(Polynomial): f._normalize() return f - cpdef _sub_(left, _right): + cpdef _sub_(left, _right) noexcept: """ EXAMPLES:: @@ -450,7 +450,7 @@ cdef class PolynomialRealDense(Polynomial): f._normalize() return f - cpdef _lmul_(self, Element c): + cpdef _lmul_(self, Element c) noexcept: """ EXAMPLES:: @@ -472,7 +472,7 @@ cdef class PolynomialRealDense(Polynomial): mpfr_mul(f._coeffs[i], self._coeffs[i], a.value, rnd) return f - cpdef _mul_(left, _right): + cpdef _mul_(left, _right) noexcept: """ Here we use the naive `O(n^2)` algorithm, as asymptotically faster algorithms such as Karatsuba can have very inaccurate results due to intermediate rounding errors. diff --git a/src/sage/rings/polynomial/polynomial_ring_homomorphism.pyx b/src/sage/rings/polynomial/polynomial_ring_homomorphism.pyx index 7e3e27dd520..3be25f829c4 100644 --- a/src/sage/rings/polynomial/polynomial_ring_homomorphism.pyx +++ b/src/sage/rings/polynomial/polynomial_ring_homomorphism.pyx @@ -36,7 +36,7 @@ cdef class PolynomialRingHomomorphism_from_base(RingHomomorphism_from_base): To: Rational Field """ - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Evaluate the homomorphism ``self`` at ``x``. @@ -65,7 +65,7 @@ cdef class PolynomialRingHomomorphism_from_base(RingHomomorphism_from_base): else: return P([f(b) for b in x]) - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ Evaluate ``self`` at ``x`` with additional (keyword) arguments. diff --git a/src/sage/rings/polynomial/polynomial_template.pxi b/src/sage/rings/polynomial/polynomial_template.pxi index ada39527536..7c53f107180 100644 --- a/src/sage/rings/polynomial/polynomial_template.pxi +++ b/src/sage/rings/polynomial/polynomial_template.pxi @@ -29,7 +29,7 @@ from sage.interfaces.singular import singular as singular_default def make_element(parent, args): return parent(*args) -cdef inline Polynomial_template element_shift(self, int n): +cdef inline Polynomial_template element_shift(self, int n) noexcept: if not isinstance(self, Polynomial_template): if n > 0: error_msg = "Cannot shift %s << %n."%(self, n) @@ -189,7 +189,7 @@ cdef class Polynomial_template(Polynomial): """ return make_element, ((self)._parent, (self.list(), False, self.is_gen())) - cpdef list list(self, bint copy=True): + cpdef list list(self, bint copy=True) noexcept: """ EXAMPLES:: @@ -224,7 +224,7 @@ cdef class Polynomial_template(Polynomial): """ celement_destruct(&self.x, (self)._cparent) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ EXAMPLES:: @@ -242,7 +242,7 @@ cdef class Polynomial_template(Polynomial): #assert(r._parent(pari(self) + pari(right)) == r) return r - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ EXAMPLES:: @@ -276,7 +276,7 @@ cdef class Polynomial_template(Polynomial): #assert(r._parent(-pari(self)) == r) return r - cpdef _lmul_(self, Element left): + cpdef _lmul_(self, Element left) noexcept: """ EXAMPLES:: @@ -322,7 +322,7 @@ cdef class Polynomial_template(Polynomial): celement_mul_scalar(&r.x, &(self).x, left, (self)._cparent) return r - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ EXAMPLES:: @@ -409,7 +409,7 @@ cdef class Polynomial_template(Polynomial): #assert(t._parent(tp) == t) return r,s,t - cpdef _floordiv_(self, right): + cpdef _floordiv_(self, right) noexcept: """ EXAMPLES:: @@ -444,7 +444,7 @@ cdef class Polynomial_template(Polynomial): celement_floordiv(&r.x, &(self).x, &(right).x, (self)._cparent) return r - cpdef _mod_(self, other): + cpdef _mod_(self, other) noexcept: """ EXAMPLES:: @@ -513,7 +513,7 @@ cdef class Polynomial_template(Polynomial): """ return not celement_is_zero(&self.x, (self)._cparent) - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ EXAMPLES:: @@ -731,7 +731,7 @@ cdef class Polynomial_template(Polynomial): """ return Integer(celement_len(&self.x, (self)._cparent)-1) - cpdef Polynomial truncate(self, long n): + cpdef Polynomial truncate(self, long n) noexcept: r""" Returns this polynomial mod `x^n`. diff --git a/src/sage/rings/polynomial/polynomial_template_header.pxi b/src/sage/rings/polynomial/polynomial_template_header.pxi index 64ab106f314..ba7184f6643 100644 --- a/src/sage/rings/polynomial/polynomial_template_header.pxi +++ b/src/sage/rings/polynomial/polynomial_template_header.pxi @@ -7,4 +7,4 @@ from sage.rings.polynomial.polynomial_element cimport Polynomial cdef class Polynomial_template(Polynomial): cdef celement x cdef cparent _cparent - cpdef _mod_(self, right) + cpdef _mod_(self, right) noexcept diff --git a/src/sage/rings/polynomial/polynomial_zmod_flint.pxd b/src/sage/rings/polynomial/polynomial_zmod_flint.pxd index c6a92f3df6c..887f46ea6eb 100644 --- a/src/sage/rings/polynomial/polynomial_zmod_flint.pxd +++ b/src/sage/rings/polynomial/polynomial_zmod_flint.pxd @@ -10,8 +10,8 @@ include "polynomial_template_header.pxi" cdef cparent get_cparent(parent) except? 0 cdef class Polynomial_zmod_flint(Polynomial_template): - cdef Polynomial_template _new(self) + cdef Polynomial_template _new(self) noexcept cdef int _set_list(self, x) except -1 cdef int _set_fmpz_poly(self, fmpz_poly_t) except -1 - cpdef Polynomial _mul_trunc_opposite(self, Polynomial_zmod_flint other, length) - cpdef rational_reconstruction(self, m, n_deg=?, d_deg=?) + cpdef Polynomial _mul_trunc_opposite(self, Polynomial_zmod_flint other, length) noexcept + cpdef rational_reconstruction(self, m, n_deg=?, d_deg=?) noexcept diff --git a/src/sage/rings/polynomial/polynomial_zmod_flint.pyx b/src/sage/rings/polynomial/polynomial_zmod_flint.pyx index 4c480673861..6e7f7498329 100644 --- a/src/sage/rings/polynomial/polynomial_zmod_flint.pyx +++ b/src/sage/rings/polynomial/polynomial_zmod_flint.pyx @@ -122,7 +122,7 @@ cdef class Polynomial_zmod_flint(Polynomial_template): pass Polynomial_template.__init__(self, parent, x, check, is_gen, construct) - cdef Polynomial_template _new(self): + cdef Polynomial_template _new(self) noexcept: """ EXAMPLES:: @@ -137,7 +137,7 @@ cdef class Polynomial_zmod_flint(Polynomial_template): e._cparent = self._cparent return e - cpdef Polynomial _new_constant_poly(self, x, Parent P): + cpdef Polynomial _new_constant_poly(self, x, Parent P) noexcept: r""" Quickly creates a new constant polynomial with value x in parent P. @@ -244,7 +244,7 @@ cdef class Polynomial_zmod_flint(Polynomial_template): sig_off() return 0 - cdef get_unsafe(self, Py_ssize_t i): + cdef get_unsafe(self, Py_ssize_t i) noexcept: """ Return the `i`-th coefficient of ``self``. @@ -412,7 +412,7 @@ cdef class Polynomial_zmod_flint(Polynomial_template): else: raise IndexError("Polynomial coefficient index must be nonnegative.") - cpdef Polynomial _mul_trunc_(self, Polynomial right, long n): + cpdef Polynomial _mul_trunc_(self, Polynomial right, long n) noexcept: """ Return the product of this polynomial and other truncated to the given length `n`. @@ -445,7 +445,7 @@ cdef class Polynomial_zmod_flint(Polynomial_template): _mul_short = _mul_trunc_ - cpdef Polynomial _mul_trunc_opposite(self, Polynomial_zmod_flint other, n): + cpdef Polynomial _mul_trunc_opposite(self, Polynomial_zmod_flint other, n) noexcept: """ Return the product of this polynomial and other ignoring the least significant `n` terms of the result which may be set to anything. @@ -482,7 +482,7 @@ cdef class Polynomial_zmod_flint(Polynomial_template): _mul_short_opposite = _mul_trunc_opposite - cpdef Polynomial _power_trunc(self, unsigned long n, long prec): + cpdef Polynomial _power_trunc(self, unsigned long n, long prec) noexcept: r""" TESTS:: @@ -519,7 +519,7 @@ cdef class Polynomial_zmod_flint(Polynomial_template): nmod_poly_pow_trunc(&ans.x, &self.x, n, prec) return ans - cpdef rational_reconstruction(self, m, n_deg=0, d_deg=0): + cpdef rational_reconstruction(self, m, n_deg=0, d_deg=0) noexcept: """ Construct a rational function `n/d` such that `p*d` is equivalent to `n` modulo `m` where `p` is this polynomial. diff --git a/src/sage/rings/polynomial/polynomial_zz_pex.pyx b/src/sage/rings/polynomial/polynomial_zz_pex.pyx index 3cae5e13a48..60968b412da 100644 --- a/src/sage/rings/polynomial/polynomial_zz_pex.pyx +++ b/src/sage/rings/polynomial/polynomial_zz_pex.pyx @@ -44,7 +44,7 @@ include "polynomial_template.pxi" from sage.libs.ntl.ntl_ZZ_pE cimport ntl_ZZ_pE -cdef inline ZZ_pE_c_to_list(ZZ_pE_c x): +cdef inline ZZ_pE_c_to_list(ZZ_pE_c x) noexcept: cdef list L = [] cdef ZZ_pX_c c_pX cdef ZZ_p_c c_p @@ -152,7 +152,7 @@ cdef class Polynomial_ZZ_pEX(Polynomial_template): Polynomial_template.__init__(self, parent, x, check, is_gen, construct) - cdef get_unsafe(self, Py_ssize_t i): + cdef get_unsafe(self, Py_ssize_t i) noexcept: r""" Return the `i`-th coefficient of ``self``. @@ -176,7 +176,7 @@ cdef class Polynomial_ZZ_pEX(Polynomial_template): cdef ZZ_pE_c c_pE = ZZ_pEX_coeff(self.x, i) return self._parent._base(ZZ_pE_c_to_list(c_pE)) - cpdef list list(self, bint copy=True): + cpdef list list(self, bint copy=True) noexcept: r""" Return the list of coefficients. @@ -198,7 +198,7 @@ cdef class Polynomial_ZZ_pEX(Polynomial_template): return [K(ZZ_pE_c_to_list(ZZ_pEX_coeff(self.x, i))) for i in range(celement_len(&self.x, (self)._cparent))] - cpdef _lmul_(self, Element left): + cpdef _lmul_(self, Element left) noexcept: r""" EXAMPLES:: @@ -410,7 +410,7 @@ cdef class Polynomial_ZZ_pEX(Polynomial_template): ZZ_pEX_MinPolyMod(r.x, ((self % other)).x, (other).x) return r - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: r""" EXAMPLES:: diff --git a/src/sage/rings/polynomial/real_roots.pxd b/src/sage/rings/polynomial/real_roots.pxd index d282f350c7b..17b3ef6d8b8 100644 --- a/src/sage/rings/polynomial/real_roots.pxd +++ b/src/sage/rings/polynomial/real_roots.pxd @@ -20,16 +20,16 @@ cdef class interval_bernstein_polynomial: cdef int bitsize cdef int scale_log2 - cdef void update_variations(self, interval_bernstein_polynomial bp1, interval_bernstein_polynomial bp2) - cdef int degree(self) + cdef void update_variations(self, interval_bernstein_polynomial bp1, interval_bernstein_polynomial bp2) noexcept + cdef int degree(self) noexcept cdef class interval_bernstein_polynomial_integer(interval_bernstein_polynomial): cdef Vector_integer_dense coeffs cdef int error - cdef void _set_bitsize(self) - cdef void _count_variations(self) + cdef void _set_bitsize(self) noexcept + cdef void _count_variations(self) noexcept cdef class interval_bernstein_polynomial_float(interval_bernstein_polynomial): cdef Vector_real_double_dense coeffs @@ -37,7 +37,7 @@ cdef class interval_bernstein_polynomial_float(interval_bernstein_polynomial): cdef double neg_err cdef double pos_err - cdef void _count_variations(self) + cdef void _count_variations(self) noexcept # forward declaration cdef class rr_gap @@ -66,8 +66,8 @@ cdef class context: cdef dc_log cdef be_log - cdef void dc_log_append(self, x) - cdef void be_log_append(self, x) + cdef void dc_log_append(self, x) noexcept + cdef void be_log_append(self, x) noexcept cdef class ocean: cdef context ctx diff --git a/src/sage/rings/polynomial/real_roots.pyx b/src/sage/rings/polynomial/real_roots.pyx index 97af8b60ffd..79fdf47ca0f 100644 --- a/src/sage/rings/polynomial/real_roots.pyx +++ b/src/sage/rings/polynomial/real_roots.pyx @@ -319,7 +319,7 @@ cdef class interval_bernstein_polynomial: """ return (self.min_variations, self.max_variations) - cdef void update_variations(self, interval_bernstein_polynomial bp1, interval_bernstein_polynomial bp2): + cdef void update_variations(self, interval_bernstein_polynomial bp1, interval_bernstein_polynomial bp2) noexcept: """ Update the max_variations of bp1 and bp2 (which are assumed to be the result of splitting this polynomial). @@ -422,7 +422,7 @@ cdef class interval_bernstein_polynomial: return (p1, p2, rand) return None - cdef int degree(self): + cdef int degree(self) noexcept: raise NotImplementedError() def region(self): @@ -565,7 +565,7 @@ cdef class interval_bernstein_polynomial_integer(interval_bernstein_polynomial): """ return 'i' - cdef void _set_bitsize(self): + cdef void _set_bitsize(self) noexcept: """ A private function that computes the maximum coefficient size of this Bernstein polynomial (in bits). @@ -580,7 +580,7 @@ cdef class interval_bernstein_polynomial_integer(interval_bernstein_polynomial): """ self.bitsize = max_bitsize_intvec(self.coeffs) - cdef void _count_variations(self): + cdef void _count_variations(self) noexcept: """ A private function that counts the number of sign variations in this Bernstein polynomial. Since the coefficients are represented @@ -677,7 +677,7 @@ cdef class interval_bernstein_polynomial_integer(interval_bernstein_polynomial): else: self.max_variations = max(count_maybe_pos, count_maybe_neg) - cdef int degree(self): + cdef int degree(self) noexcept: """ Return the (formal) degree of this polynomial. """ @@ -1480,7 +1480,7 @@ cdef class interval_bernstein_polynomial_float(interval_bernstein_polynomial): """ return 'f' - cdef void _count_variations(self): + cdef void _count_variations(self) noexcept: """ A private function that counts the number of sign variations in this Bernstein polynomial. Since the coefficients are represented @@ -1552,7 +1552,7 @@ cdef class interval_bernstein_polynomial_float(interval_bernstein_polynomial): else: self.max_variations = max(count_maybe_pos, count_maybe_neg) - cdef int degree(self): + cdef int degree(self) noexcept: """ Return the (formal) degree of this polynomial. """ @@ -1939,7 +1939,7 @@ def relative_bounds(a, b): return ((bl - al) / width, (bh - al) / width) -cdef int bitsize(Integer a): +cdef int bitsize(Integer a) noexcept: """ Compute the number of bits required to write a given integer (the sign is ignored). @@ -2143,7 +2143,7 @@ def bernstein_up(d1, d2, s=None): return m -cdef int subsample_vec(int a, int slen, int llen): +cdef int subsample_vec(int a, int slen, int llen) noexcept: """ Given a vector of length llen, and slen < llen, we want to select slen of the elements of the vector, evenly spaced. @@ -4353,14 +4353,14 @@ cdef class context: s = s + "; wordsize=%d" % self.wordsize return s - cdef void dc_log_append(self, x): + cdef void dc_log_append(self, x) noexcept: """ Optional logging for the root isolation algorithm. """ if self.do_logging: self.dc_log.append(x) - cdef void be_log_append(self, x): + cdef void be_log_append(self, x) noexcept: """ Optional logging for degree reduction in the root isolation algorithm. """ @@ -4528,7 +4528,7 @@ def bernstein_expand(Vector_integer_dense c, int d2): return (c2, ndivides) -cdef int max_bitsize_intvec(Vector_integer_dense b): +cdef int max_bitsize_intvec(Vector_integer_dense b) noexcept: """ Given an integer vector, find the approximate log2 of the maximum of the absolute values of the elements. diff --git a/src/sage/rings/polynomial/skew_polynomial_element.pxd b/src/sage/rings/polynomial/skew_polynomial_element.pxd index b7222e38117..d967e898909 100644 --- a/src/sage/rings/polynomial/skew_polynomial_element.pxd +++ b/src/sage/rings/polynomial/skew_polynomial_element.pxd @@ -1,8 +1,8 @@ from sage.rings.polynomial.ore_polynomial_element cimport OrePolynomial_generic_dense cdef class SkewPolynomial_generic_dense(OrePolynomial_generic_dense): - cdef void _inplace_rmul(self, SkewPolynomial_generic_dense right) - cdef void _inplace_pow(self, Py_ssize_t n) - cpdef right_power_mod(self, exp, modulus) - cpdef left_power_mod(self, exp, modulus) - cpdef operator_eval(self, eval_pt) + cdef void _inplace_rmul(self, SkewPolynomial_generic_dense right) noexcept + cdef void _inplace_pow(self, Py_ssize_t n) noexcept + cpdef right_power_mod(self, exp, modulus) noexcept + cpdef left_power_mod(self, exp, modulus) noexcept + cpdef operator_eval(self, eval_pt) noexcept diff --git a/src/sage/rings/polynomial/skew_polynomial_element.pyx b/src/sage/rings/polynomial/skew_polynomial_element.pyx index 539e924a968..3ea7f87bddf 100644 --- a/src/sage/rings/polynomial/skew_polynomial_element.pyx +++ b/src/sage/rings/polynomial/skew_polynomial_element.pyx @@ -63,7 +63,7 @@ cdef class SkewPolynomial_generic_dense(OrePolynomial_generic_dense): Generic implementation of dense skew polynomial supporting any valid base ring and twisting morphism. """ - cpdef left_power_mod(self, exp, modulus): + cpdef left_power_mod(self, exp, modulus) noexcept: r""" Return the remainder of ``self**exp`` in the left euclidean division by ``modulus``. @@ -125,7 +125,7 @@ cdef class SkewPolynomial_generic_dense(OrePolynomial_generic_dense): _, r = r._left_quo_rem(modulus) return r - cpdef right_power_mod(self, exp, modulus): + cpdef right_power_mod(self, exp, modulus) noexcept: r""" Return the remainder of ``self**exp`` in the right euclidean division by ``modulus``. @@ -326,7 +326,7 @@ cdef class SkewPolynomial_generic_dense(OrePolynomial_generic_dense): """ return self.operator_eval(eval_pt) - cpdef operator_eval(self, eval_pt): + cpdef operator_eval(self, eval_pt) noexcept: r""" Evaluate ``self`` at ``eval_pt`` by the operator evaluation method. @@ -453,7 +453,7 @@ cdef class SkewPolynomial_generic_dense(OrePolynomial_generic_dense): """ return [ self(e) for e in eval_pts ] - cpdef ModuleElement _lmul_(self, Element right): + cpdef ModuleElement _lmul_(self, Element right) noexcept: r""" Return the product ``self * right``. @@ -482,7 +482,7 @@ cdef class SkewPolynomial_generic_dense(OrePolynomial_generic_dense): self._parent, 0) return r - cpdef ModuleElement _rmul_(self, Element left): + cpdef ModuleElement _rmul_(self, Element left) noexcept: r""" Return the product ``left * self``. @@ -509,7 +509,7 @@ cdef class SkewPolynomial_generic_dense(OrePolynomial_generic_dense): r = self._new_c([ left*x[i] for i from 0 <= i < len(x) ], self._parent, 0) return r - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: r""" Return the product ``self * right``. @@ -560,7 +560,7 @@ cdef class SkewPolynomial_generic_dense(OrePolynomial_generic_dense): r = self._new_c(coeffs, parent, 0) return r - cdef void _inplace_rmul(self, SkewPolynomial_generic_dense right): + cdef void _inplace_rmul(self, SkewPolynomial_generic_dense right) noexcept: r""" Replace ``self`` by ``self*right`` (only for internal use). @@ -596,7 +596,7 @@ cdef class SkewPolynomial_generic_dense(OrePolynomial_generic_dense): sum += x[i] * parent.twisting_morphism(i)(y[k-i]) x[k] = sum - cdef void _inplace_pow(self, Py_ssize_t n): + cdef void _inplace_pow(self, Py_ssize_t n) noexcept: r""" Replace ``self`` by ``self**n`` (only for internal use). @@ -621,7 +621,7 @@ cdef class SkewPolynomial_generic_dense(OrePolynomial_generic_dense): self._inplace_rmul(selfpow) n = n >> 1 - cdef _left_quo_rem(self, OrePolynomial other): + cdef _left_quo_rem(self, OrePolynomial other) noexcept: r""" Return the quotient and remainder of the left euclidean division of ``self`` by ``other`` (C implementation). @@ -650,7 +650,7 @@ cdef class SkewPolynomial_generic_dense(OrePolynomial_generic_dense): q.reverse() return (self._new_c(q, parent), self._new_c(a[:db], parent, 1)) - cdef _right_quo_rem(self, OrePolynomial other): + cdef _right_quo_rem(self, OrePolynomial other) noexcept: r""" Return the quotient and remainder of the right euclidean division of ``self`` by ``other`` (C implementation). diff --git a/src/sage/rings/polynomial/skew_polynomial_finite_field.pxd b/src/sage/rings/polynomial/skew_polynomial_finite_field.pxd index f27cfdd6ff1..1718554cc3a 100644 --- a/src/sage/rings/polynomial/skew_polynomial_finite_field.pxd +++ b/src/sage/rings/polynomial/skew_polynomial_finite_field.pxd @@ -5,14 +5,14 @@ cdef class SkewPolynomial_finite_field_dense (SkewPolynomial_finite_order_dense) cdef dict _types cdef _factorization - cdef inline _reduced_norm_factored(self) + cdef inline _reduced_norm_factored(self) noexcept # Finding divisors - cdef SkewPolynomial_finite_field_dense _rdivisor_c(P, N) + cdef SkewPolynomial_finite_field_dense _rdivisor_c(P, N) noexcept # Finding factorizations - cdef _factor_c(self) - cdef _factor_uniform_c(self) + cdef _factor_c(self) noexcept + cdef _factor_uniform_c(self) noexcept -cdef inline SkewPolynomial_finite_field_dense mul_op(SkewPolynomial_finite_field_dense P, SkewPolynomial_finite_field_dense Q): +cdef inline SkewPolynomial_finite_field_dense mul_op(SkewPolynomial_finite_field_dense P, SkewPolynomial_finite_field_dense Q) noexcept: return Q * P diff --git a/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx b/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx index c6b67cba5fb..8066670c4a0 100644 --- a/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx +++ b/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx @@ -43,7 +43,7 @@ from sage.combinat.q_analogues import q_jordan cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense): - cdef inline _reduced_norm_factored(self): + cdef inline _reduced_norm_factored(self) noexcept: """ Return the reduced norm of this polynomial factorized in the center. """ @@ -212,7 +212,7 @@ cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense): # Finding divisors # ---------------- - cdef SkewPolynomial_finite_field_dense _rdivisor_c(self, N): + cdef SkewPolynomial_finite_field_dense _rdivisor_c(self, N) noexcept: r""" Return a right divisor of this skew polynomial whose reduced norm is `N`. @@ -747,7 +747,7 @@ cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense): # Finding factorizations # ---------------------- - cdef _factor_c(self): + cdef _factor_c(self) noexcept: r""" Compute a factorization of ``self``. @@ -818,7 +818,7 @@ cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense): factors.reverse() return Factorization(factors, sort=False, unit=unit) - cdef _factor_uniform_c(self): + cdef _factor_uniform_c(self) noexcept: r""" Compute a uniformly distributed factorization of ``self``. diff --git a/src/sage/rings/polynomial/skew_polynomial_finite_order.pxd b/src/sage/rings/polynomial/skew_polynomial_finite_order.pxd index 438773a39ef..bfaf8d04d14 100644 --- a/src/sage/rings/polynomial/skew_polynomial_finite_order.pxd +++ b/src/sage/rings/polynomial/skew_polynomial_finite_order.pxd @@ -5,6 +5,6 @@ cdef class SkewPolynomial_finite_order_dense (SkewPolynomial_generic_dense): cdef _charpoly cdef _optbound - cdef _matphir_c(self) - cdef _matmul_c(self) + cdef _matphir_c(self) noexcept + cdef _matmul_c(self) noexcept diff --git a/src/sage/rings/polynomial/skew_polynomial_finite_order.pyx b/src/sage/rings/polynomial/skew_polynomial_finite_order.pyx index 6ab57e1f7c5..968c45c8453 100644 --- a/src/sage/rings/polynomial/skew_polynomial_finite_order.pyx +++ b/src/sage/rings/polynomial/skew_polynomial_finite_order.pyx @@ -71,7 +71,7 @@ cdef class SkewPolynomial_finite_order_dense(SkewPolynomial_generic_dense): self._optbound = None - cdef _matphir_c(self): + cdef _matphir_c(self) noexcept: r""" Return the matrix of the multiplication by `X^r` on the quotient `K[X,\sigma] / K[X,\sigma]*self`. @@ -122,7 +122,7 @@ cdef class SkewPolynomial_finite_order_dense(SkewPolynomial_generic_dense): phir.append(line) return matrix(k, phir) - cdef _matmul_c(self): + cdef _matmul_c(self) noexcept: r""" Return the matrix of the multiplication by ``self`` on `K[X,\sigma]` considered as a free module over `K[X^r]` diff --git a/src/sage/rings/polynomial/weil/weil_polynomials.pyx b/src/sage/rings/polynomial/weil/weil_polynomials.pyx index 2e2d6974fb7..182d0c41e6f 100755 --- a/src/sage/rings/polynomial/weil/weil_polynomials.pyx +++ b/src/sage/rings/polynomial/weil/weil_polynomials.pyx @@ -153,7 +153,7 @@ cdef class dfs_manager: free(self.dy_data_buf) self.dy_data_buf = NULL - cpdef long node_count(self): + cpdef long node_count(self) noexcept: """ Count nodes. @@ -175,7 +175,7 @@ cdef class dfs_manager: count += self.dy_data_buf[i].node_count return count - cpdef object advance_exhaust(self): + cpdef object advance_exhaust(self) noexcept: """ Advance the tree exhaustion. diff --git a/src/sage/rings/power_series_mpoly.pyx b/src/sage/rings/power_series_mpoly.pyx index be59294e75b..fa62a7ef6d6 100644 --- a/src/sage/rings/power_series_mpoly.pyx +++ b/src/sage/rings/power_series_mpoly.pyx @@ -100,7 +100,7 @@ cdef class PowerSeries_mpoly(PowerSeries): def _mpoly(self): return self.__f - cpdef _mul_(self, right_r): + cpdef _mul_(self, right_r) noexcept: """ Return the product of two power series. """ @@ -124,7 +124,7 @@ cdef class PowerSeries_mpoly(PowerSeries): return PowerSeries_mpoly(self._parent, -self.__f, self._prec, check=False) - cpdef _add_(self, right_m): + cpdef _add_(self, right_m) noexcept: """ EXAMPLES: """ @@ -132,7 +132,7 @@ cdef class PowerSeries_mpoly(PowerSeries): return PowerSeries_mpoly(self._parent, self.__f + right.__f, self.common_prec_c(right), check=True) - cpdef _sub_(self, right_m): + cpdef _sub_(self, right_m) noexcept: """ Return difference of two power series. @@ -142,11 +142,11 @@ cdef class PowerSeries_mpoly(PowerSeries): return PowerSeries_mpoly(self._parent, self.__f - right.__f, self.common_prec_c(right), check=True) - cpdef _rmul_(self, Element c): + cpdef _rmul_(self, Element c) noexcept: return PowerSeries_mpoly(self._parent, self.__f._rmul_(c), self._prec, check=False) - cpdef _lmul_(self, Element c): + cpdef _lmul_(self, Element c) noexcept: return PowerSeries_mpoly(self._parent, self.__f._lmul_(c), self._prec, check=False) diff --git a/src/sage/rings/power_series_pari.pyx b/src/sage/rings/power_series_pari.pyx index 94a6d1baacb..6b8d02b5762 100644 --- a/src/sage/rings/power_series_pari.pyx +++ b/src/sage/rings/power_series_pari.pyx @@ -81,7 +81,7 @@ from sage.structure.parent cimport Parent from sage.rings.infinity import infinity -cdef PowerSeries_pari construct_from_pari(parent, pari_gen g): +cdef PowerSeries_pari construct_from_pari(parent, pari_gen g) noexcept: r""" Fast construction of power series from PARI objects of suitable type (series, polynomials, scalars and rational functions). @@ -556,7 +556,7 @@ cdef class PowerSeries_pari(PowerSeries): return self._parent.laurent_series_ring()(h) return construct_from_pari(self._parent, h) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Addition of power series. @@ -573,7 +573,7 @@ cdef class PowerSeries_pari(PowerSeries): """ return construct_from_pari(self._parent, self.g + (right).g) - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Subtraction of power series. @@ -587,7 +587,7 @@ cdef class PowerSeries_pari(PowerSeries): """ return construct_from_pari(self._parent, self.g - (right).g) - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Multiplication of power series. @@ -600,7 +600,7 @@ cdef class PowerSeries_pari(PowerSeries): """ return construct_from_pari(self._parent, self.g * (right).g) - cpdef _rmul_(self, Element c): + cpdef _rmul_(self, Element c) noexcept: """ Right multiplication by a scalar. @@ -614,7 +614,7 @@ cdef class PowerSeries_pari(PowerSeries): """ return construct_from_pari(self._parent, self.g * c) - cpdef _lmul_(self, Element c): + cpdef _lmul_(self, Element c) noexcept: """ Left multiplication by a scalar. @@ -628,7 +628,7 @@ cdef class PowerSeries_pari(PowerSeries): """ return construct_from_pari(self._parent, c * self.g) - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Division of power series. diff --git a/src/sage/rings/power_series_poly.pyx b/src/sage/rings/power_series_poly.pyx index c7cd78db093..083fddaa805 100644 --- a/src/sage/rings/power_series_poly.pyx +++ b/src/sage/rings/power_series_poly.pyx @@ -485,7 +485,7 @@ cdef class PowerSeries_poly(PowerSeries): return PowerSeries_poly(self._parent, -self.__f, self._prec, check=False) - cpdef _add_(self, right_m): + cpdef _add_(self, right_m) noexcept: """ EXAMPLES:: @@ -516,7 +516,7 @@ cdef class PowerSeries_poly(PowerSeries): return PowerSeries_poly(self._parent, self.__f + right.__f, self.common_prec_c(right), check=True) - cpdef _sub_(self, right_m): + cpdef _sub_(self, right_m) noexcept: """ Return the difference of two power series. @@ -531,7 +531,7 @@ cdef class PowerSeries_poly(PowerSeries): return PowerSeries_poly(self._parent, self.__f - right.__f, self.common_prec_c(right), check=True) - cpdef _mul_(self, right_r): + cpdef _mul_(self, right_r) noexcept: """ Return the product of two power series. @@ -547,7 +547,7 @@ cdef class PowerSeries_poly(PowerSeries): prec=prec, check=True) # check, since truncation may be needed - cpdef _rmul_(self, Element c): + cpdef _rmul_(self, Element c) noexcept: """ Multiply ``self`` on the right by a scalar. @@ -560,7 +560,7 @@ cdef class PowerSeries_poly(PowerSeries): """ return PowerSeries_poly(self._parent, self.__f * c, self._prec, check=False) - cpdef _lmul_(self, Element c): + cpdef _lmul_(self, Element c) noexcept: """ Multiply ``self`` on the left by a scalar. @@ -744,7 +744,7 @@ cdef class PowerSeries_poly(PowerSeries): else: return self.__f.truncate(prec) - cdef _inplace_truncate(self, long prec): + cdef _inplace_truncate(self, long prec) noexcept: """ Truncate ``self`` to precision ``prec`` in place. @@ -1243,7 +1243,7 @@ cdef class BaseRingFloorDivAction(Action): """ The floor division action of the base ring on a formal power series. """ - cpdef _act_(self, g, x): + cpdef _act_(self, g, x) noexcept: r""" Let ``g`` act on ``x`` under ``self``. diff --git a/src/sage/rings/power_series_ring_element.pxd b/src/sage/rings/power_series_ring_element.pxd index e5c031ee147..b8c28103131 100644 --- a/src/sage/rings/power_series_ring_element.pxd +++ b/src/sage/rings/power_series_ring_element.pxd @@ -3,9 +3,9 @@ from sage.structure.element cimport AlgebraElement, RingElement cdef class PowerSeries(AlgebraElement): cdef char _is_gen cdef _prec - cdef common_prec_c(self, PowerSeries other) + cdef common_prec_c(self, PowerSeries other) noexcept #_prec(self, RingElement right_r) # UNSAFE, only call from an inplace operator # may return a new element if not possible to modify inplace - cdef _inplace_truncate(self, long prec) + cdef _inplace_truncate(self, long prec) noexcept diff --git a/src/sage/rings/power_series_ring_element.pyx b/src/sage/rings/power_series_ring_element.pyx index 5e2c4511e49..ceb8198fafc 100644 --- a/src/sage/rings/power_series_ring_element.pyx +++ b/src/sage/rings/power_series_ring_element.pyx @@ -254,7 +254,7 @@ cdef class PowerSeries(AlgebraElement): else: raise NotImplementedError - cpdef base_extend(self, R): + cpdef base_extend(self, R) noexcept: """ Return a copy of this power series but with coefficients in R. @@ -311,7 +311,7 @@ cdef class PowerSeries(AlgebraElement): S = self._parent.change_ring(R) return S(self) - cpdef _richcmp_(self, right, int op): + cpdef _richcmp_(self, right, int op) noexcept: r""" Comparison of self and ``right``. @@ -813,7 +813,7 @@ cdef class PowerSeries(AlgebraElement): v = [a[i] for i in range(min(prec, len(a)))] return self._parent._poly_ring()(v) - cdef _inplace_truncate(self, long prec): + cdef _inplace_truncate(self, long prec) noexcept: return self.truncate(prec) def add_bigoh(self, prec): @@ -917,7 +917,7 @@ cdef class PowerSeries(AlgebraElement): return self.prec() return min(self.prec(), f.prec()) - cdef common_prec_c(self, PowerSeries f): + cdef common_prec_c(self, PowerSeries f) noexcept: if self._prec is infinity: return f._prec elif f._prec is infinity: @@ -1048,7 +1048,7 @@ cdef class PowerSeries(AlgebraElement): v[k-n] = x return self._parent(v, self.prec()-n) - cpdef _div_(self, denom_r): + cpdef _div_(self, denom_r) noexcept: """ EXAMPLES:: diff --git a/src/sage/rings/puiseux_series_ring_element.pyx b/src/sage/rings/puiseux_series_ring_element.pyx index 503d11ee975..39edce35bc9 100644 --- a/src/sage/rings/puiseux_series_ring_element.pyx +++ b/src/sage/rings/puiseux_series_ring_element.pyx @@ -354,7 +354,7 @@ cdef class PuiseuxSeries(AlgebraElement): n = g / n return g, m, n - cpdef _add_(self, right_m): + cpdef _add_(self, right_m) noexcept: """ Return the sum. @@ -376,7 +376,7 @@ cdef class PuiseuxSeries(AlgebraElement): l = l1 + l2 return type(self)(self._parent, l, g) - cpdef _sub_(self, right_m): + cpdef _sub_(self, right_m) noexcept: """ Return the difference. @@ -398,7 +398,7 @@ cdef class PuiseuxSeries(AlgebraElement): l = l1 - l2 return type(self)(self._parent, l, g) - cpdef _mul_(self, right_r): + cpdef _mul_(self, right_r) noexcept: """ Return the product. @@ -420,7 +420,7 @@ cdef class PuiseuxSeries(AlgebraElement): l = l1 * l2 return type(self)(self._parent, l, g) - cpdef _rmul_(self, Element c): + cpdef _rmul_(self, Element c) noexcept: """ Return the right scalar multiplication. @@ -433,7 +433,7 @@ cdef class PuiseuxSeries(AlgebraElement): """ return type(self)(self._parent, self._l._rmul_(c), self._e) - cpdef _lmul_(self, Element c): + cpdef _lmul_(self, Element c) noexcept: """ Return the left scalar multiplication. @@ -446,7 +446,7 @@ cdef class PuiseuxSeries(AlgebraElement): """ return type(self)(self._parent, self._l._lmul_(c), self._e) - cpdef _div_(self, right_r): + cpdef _div_(self, right_r) noexcept: """ Return the quotient. @@ -508,7 +508,7 @@ cdef class PuiseuxSeries(AlgebraElement): e = self._e * int(denom) return type(self)(self._parent, l, e) - cpdef _richcmp_(self, right_r, int op): + cpdef _richcmp_(self, right_r, int op) noexcept: r""" Comparison of ``self`` and ``right``. diff --git a/src/sage/rings/rational.pxd b/src/sage/rings/rational.pxd index a1b2403c723..f80ec22e9a9 100644 --- a/src/sage/rings/rational.pxd +++ b/src/sage/rings/rational.pxd @@ -3,17 +3,17 @@ from sage.libs.gmp.types cimport mpq_t cimport sage.structure.element cimport sage.rings.integer as integer -cpdef rational_power_parts(a, Rational b, factor_limit=?) +cpdef rational_power_parts(a, Rational b, factor_limit=?) noexcept cdef class Rational(sage.structure.element.FieldElement): cdef mpq_t value - cpdef _add_(self, other) - cpdef _mul_(self, other) - cpdef _pow_(self, other) - cdef __set_value(self, x, unsigned int base) - cdef void set_from_mpq(Rational self, mpq_t value) - cdef _lshift(self, long int exp) - cdef _rshift(self, long int exp) + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept + cpdef _pow_(self, other) noexcept + cdef __set_value(self, x, unsigned int base) noexcept + cdef void set_from_mpq(Rational self, mpq_t value) noexcept + cdef _lshift(self, long int exp) noexcept + cdef _rshift(self, long int exp) noexcept - cdef _val_unit(self, integer.Integer p) + cdef _val_unit(self, integer.Integer p) noexcept diff --git a/src/sage/rings/rational.pyx b/src/sage/rings/rational.pyx index f8843a2cee7..0b398428006 100644 --- a/src/sage/rings/rational.pyx +++ b/src/sage/rings/rational.pyx @@ -123,16 +123,16 @@ gmpy2.import_gmpy2() cdef class Rational(sage.structure.element.FieldElement) -cdef inline void set_from_mpq(Rational self, mpq_t value): +cdef inline void set_from_mpq(Rational self, mpq_t value) noexcept: mpq_set(self.value, value) -cdef inline void set_from_Rational(Rational self, Rational other): +cdef inline void set_from_Rational(Rational self, Rational other) noexcept: mpq_set(self.value, other.value) -cdef inline void set_from_Integer(Rational self, integer.Integer other): +cdef inline void set_from_Integer(Rational self, integer.Integer other) noexcept: mpq_set_z(self.value, other.value) -cdef object Rational_mul_(Rational a, Rational b): +cdef object Rational_mul_(Rational a, Rational b) noexcept: cdef Rational x x = Rational.__new__(Rational) @@ -142,7 +142,7 @@ cdef object Rational_mul_(Rational a, Rational b): return x -cdef object Rational_div_(Rational a, Rational b): +cdef object Rational_div_(Rational a, Rational b) noexcept: cdef Rational x x = Rational.__new__(Rational) @@ -152,7 +152,7 @@ cdef object Rational_div_(Rational a, Rational b): return x -cdef Rational_add_(Rational self, Rational other): +cdef Rational_add_(Rational self, Rational other) noexcept: cdef Rational x x = Rational.__new__(Rational) sig_on() @@ -160,7 +160,7 @@ cdef Rational_add_(Rational self, Rational other): sig_off() return x -cdef Rational_sub_(Rational self, Rational other): +cdef Rational_sub_(Rational self, Rational other) noexcept: cdef Rational x x = Rational.__new__(Rational) @@ -173,14 +173,14 @@ cdef Rational_sub_(Rational self, Rational other): cdef Parent the_rational_ring = sage.rings.rational_field.Q # make sure zero/one elements are set -cdef set_zero_one_elements(): +cdef set_zero_one_elements() noexcept: global the_rational_ring the_rational_ring._zero_element = Rational(0) the_rational_ring._one_element = Rational(1) set_zero_one_elements() -cpdef Integer integer_rational_power(Integer a, Rational b): +cpdef Integer integer_rational_power(Integer a, Rational b) noexcept: """ Compute `a^b` as an integer, if it is integral, or return ``None``. @@ -262,7 +262,7 @@ cpdef Integer integer_rational_power(Integer a, Rational b): return z -cpdef rational_power_parts(a, Rational b, factor_limit=10**5): +cpdef rational_power_parts(a, Rational b, factor_limit=10**5) noexcept: """ Compute rationals or integers `c` and `d` such that `a^b = c*d^b` with `d` small. This is used for simplifying radicals. @@ -566,7 +566,7 @@ cdef class Rational(sage.structure.element.FieldElement): raise TypeError(f"unable to convert rational {self} to an integer") - cdef __set_value(self, x, unsigned int base): + cdef __set_value(self, x, unsigned int base) noexcept: cdef int n cdef Rational temp_rational cdef integer.Integer a, b @@ -680,7 +680,7 @@ cdef class Rational(sage.structure.element.FieldElement): else: raise TypeError("unable to convert {!r} to a rational".format(x)) - cdef void set_from_mpq(Rational self, mpq_t value): + cdef void set_from_mpq(Rational self, mpq_t value) noexcept: mpq_set(self.value, value) def list(self): @@ -820,7 +820,7 @@ cdef class Rational(sage.structure.element.FieldElement): l = self.continued_fraction_list() return ContinuedFraction_periodic(l) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Compare two rational numbers. @@ -1801,7 +1801,7 @@ cdef class Rational(sage.structure.element.FieldElement): # TODO -- change to use cpdef? If so, must fix # code in padics, etc. Do search_src('_val_unit'). - cdef _val_unit(Rational self, integer.Integer p): + cdef _val_unit(Rational self, integer.Integer p) noexcept: """ This is called by :meth:`val_unit()`. @@ -2307,7 +2307,7 @@ cdef class Rational(sage.structure.element.FieldElement): return coercion_model.bin_op(left, right, operator.add) - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Return ``right`` plus ``self``. @@ -2359,7 +2359,7 @@ cdef class Rational(sage.structure.element.FieldElement): return coercion_model.bin_op(left, right, operator.sub) - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Return ``self`` minus ``right``. @@ -2373,7 +2373,7 @@ cdef class Rational(sage.structure.element.FieldElement): mpq_sub(x.value, self.value, (right).value) return x - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ Negate ``self``. @@ -2412,7 +2412,7 @@ cdef class Rational(sage.structure.element.FieldElement): return coercion_model.bin_op(left, right, operator.mul) - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Return ``self`` times ``right``. @@ -2469,7 +2469,7 @@ cdef class Rational(sage.structure.element.FieldElement): return coercion_model.bin_op(left, right, operator.truediv) - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Return ``self`` divided by ``right``. @@ -2513,7 +2513,7 @@ cdef class Rational(sage.structure.element.FieldElement): mpq_inv(x.value, self.value) return x - cpdef _pow_(self, other): + cpdef _pow_(self, other) noexcept: """ Raise ``self`` to the rational power ``other``. @@ -2608,7 +2608,7 @@ cdef class Rational(sage.structure.element.FieldElement): from sage.symbolic.ring import SR return SR(c) * SR(d).power(n, hold=True) - cpdef _pow_int(self, n): + cpdef _pow_int(self, n) noexcept: """ Raise ``self`` to the integer power ``n``. @@ -2628,7 +2628,7 @@ cdef class Rational(sage.structure.element.FieldElement): # be particularly efficient here. return self._pow_(Rational(n)) - cdef _pow_long(self, long n): + cdef _pow_long(self, long n) noexcept: """ TESTS:: @@ -3663,7 +3663,7 @@ cdef class Rational(sage.structure.element.FieldElement): return False return a.prime_to_S_part(S) == 1 - cdef _lshift(self, long int exp): + cdef _lshift(self, long int exp) noexcept: r""" Return ``self * 2^exp``. """ @@ -3711,7 +3711,7 @@ cdef class Rational(sage.structure.element.FieldElement): return (x)._lshift(y) return coercion_model.bin_op(x, y, operator.lshift) - cdef _rshift(self, long int exp): + cdef _rshift(self, long int exp) noexcept: r""" Return ``self / 2^exp``. """ @@ -4099,7 +4099,7 @@ cdef class Z_to_Q(Morphism): import sage.categories.homset Morphism.__init__(self, sage.categories.homset.Hom(integer_ring.ZZ, rational_field.QQ)) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Return the image of the morphism on ``x``. @@ -4166,7 +4166,7 @@ cdef class Q_to_Z(Map): sage: type(ZZ.convert_map_from(QQ)) """ - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ A fast map from the rationals to the integers. @@ -4221,7 +4221,7 @@ cdef class int_to_Q(Morphism): Morphism.__init__(self, sage.categories.homset.Hom( Set_PythonType(long), rational_field.QQ)) - cpdef Element _call_(self, a): + cpdef Element _call_(self, a) noexcept: """ Return the image of the morphism on ``a``. diff --git a/src/sage/rings/real_arb.pxd b/src/sage/rings/real_arb.pxd index 2f48fa06988..0a3a68d1057 100644 --- a/src/sage/rings/real_arb.pxd +++ b/src/sage/rings/real_arb.pxd @@ -4,17 +4,17 @@ from sage.rings.real_mpfi cimport RealIntervalField_class, RealIntervalFieldElem from sage.structure.parent cimport Parent from sage.structure.element cimport RingElement -cdef void mpfi_to_arb(arb_t target, const mpfi_t source, const long precision) +cdef void mpfi_to_arb(arb_t target, const mpfi_t source, const long precision) noexcept cdef int arb_to_mpfi(mpfi_t target, arb_t source, const long precision) except -1 cdef class RealBall(RingElement): cdef arb_t value - cpdef _add_(self, other) - cpdef _mul_(self, other) - cpdef RealIntervalFieldElement _real_mpfi_(self, RealIntervalField_class parent) - cpdef RealBall psi(self) + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept + cpdef RealIntervalFieldElement _real_mpfi_(self, RealIntervalField_class parent) noexcept + cpdef RealBall psi(self) noexcept - cdef inline RealBall _new(self): + cdef inline RealBall _new(self) noexcept: cdef RealBall res = RealBall.__new__(RealBall) res._parent = self._parent return res diff --git a/src/sage/rings/real_arb.pyx b/src/sage/rings/real_arb.pyx index 17859068273..a9ce06d14ca 100644 --- a/src/sage/rings/real_arb.pyx +++ b/src/sage/rings/real_arb.pyx @@ -236,7 +236,7 @@ from sage.rings.real_mpfi import RealIntervalField, RealIntervalField_class from sage.structure.unique_representation import UniqueRepresentation from sage.cpython.string cimport char_to_str, str_to_bytes -cdef void mpfi_to_arb(arb_t target, const mpfi_t source, const long precision): +cdef void mpfi_to_arb(arb_t target, const mpfi_t source, const long precision) noexcept: r""" Convert an MPFI interval to an Arb ball. @@ -1145,7 +1145,7 @@ class RealBallField(UniqueRepresentation, sage.rings.abc.RealBallField): """ return ARF_PREC_EXACT -cdef inline bint _do_sig(long prec): +cdef inline bint _do_sig(long prec) noexcept: """ Whether signal handlers should be installed for calls to arb. @@ -1156,7 +1156,7 @@ cdef inline bint _do_sig(long prec): """ return (prec > 1000) -cdef inline long prec(RealBall ball): +cdef inline long prec(RealBall ball) noexcept: return ball._parent._prec def create_RealBall(parent, serialized): @@ -1553,7 +1553,7 @@ cdef class RealBall(RingElement): # Conversions - cpdef RealIntervalFieldElement _real_mpfi_(self, RealIntervalField_class parent): + cpdef RealIntervalFieldElement _real_mpfi_(self, RealIntervalField_class parent) noexcept: """ Return a :mod:`real interval ` containing this ball. @@ -2255,7 +2255,7 @@ cdef class RealBall(RingElement): """ return arb_is_exact(self.value) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Compare ``left`` and ``right``. @@ -2797,7 +2797,7 @@ cdef class RealBall(RingElement): if _do_sig(prec(self)): sig_off() return res - cpdef _add_(self, other): + cpdef _add_(self, other) noexcept: """ Return the sum of two balls, rounded to the ambient field's precision. @@ -2815,7 +2815,7 @@ cdef class RealBall(RingElement): if _do_sig(prec(self)): sig_off() return res - cpdef _sub_(self, other): + cpdef _sub_(self, other) noexcept: """ Return the difference of two balls, rounded to the ambient field's precision. @@ -2834,7 +2834,7 @@ cdef class RealBall(RingElement): if _do_sig(prec(self)): sig_off() return res - cpdef _mul_(self, other): + cpdef _mul_(self, other) noexcept: """ Return the product of two balls, rounded to the ambient field's precision. @@ -2853,7 +2853,7 @@ cdef class RealBall(RingElement): if _do_sig(prec(self)): sig_off() return res - cpdef _div_(self, other): + cpdef _div_(self, other) noexcept: """ Return the quotient of two balls, rounded to the ambient field's precision. @@ -3850,7 +3850,7 @@ cdef class RealBall(RingElement): if _do_sig(prec(self)): sig_off() return result - cpdef RealBall psi(self): + cpdef RealBall psi(self) noexcept: """ Compute the digamma function with argument self. diff --git a/src/sage/rings/real_double.pxd b/src/sage/rings/real_double.pxd index 06d4121ef26..e2c657faec2 100644 --- a/src/sage/rings/real_double.pxd +++ b/src/sage/rings/real_double.pxd @@ -3,13 +3,13 @@ from sage.rings.ring cimport Field cimport sage.rings.abc cdef class RealDoubleField_class(sage.rings.abc.RealDoubleField): - cdef _new_c(self, double value) + cdef _new_c(self, double value) noexcept cdef class RealDoubleElement(FieldElement): cdef double _value - cdef _new_c(self, double value) - cpdef _add_(self, other) - cpdef _mul_(self, other) - cpdef RealDoubleElement abs(RealDoubleElement self) + cdef _new_c(self, double value) noexcept + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept + cpdef RealDoubleElement abs(RealDoubleElement self) noexcept -cdef double_repr(double x) +cdef double_repr(double x) noexcept diff --git a/src/sage/rings/real_double.pyx b/src/sage/rings/real_double.pyx index dea1633dd15..f1e5eb0a2c8 100644 --- a/src/sage/rings/real_double.pyx +++ b/src/sage/rings/real_double.pyx @@ -277,7 +277,7 @@ cdef class RealDoubleField_class(sage.rings.abc.RealDoubleField): from sage.rings.complex_double import CDF return CDF - cpdef _coerce_map_from_(self, S): + cpdef _coerce_map_from_(self, S) noexcept: """ Canonical coercion of ``S`` to the real double field. @@ -472,7 +472,7 @@ cdef class RealDoubleField_class(sage.rings.abc.RealDoubleField): """ return Integer(0) - cdef _new_c(self, double value): + cdef _new_c(self, double value) noexcept: cdef RealDoubleElement x x = PY_NEW(RealDoubleElement) x._value = value @@ -740,7 +740,7 @@ cdef class RealDoubleElement(FieldElement): """ return RealDoubleElement, (self._value, ) - cdef _new_c(self, double value): + cdef _new_c(self, double value) noexcept: cdef RealDoubleElement x x = PY_NEW(RealDoubleElement) x._value = value @@ -1309,7 +1309,7 @@ cdef class RealDoubleElement(FieldElement): x._value = 1.0 / self._value return x - cpdef _add_(self, right): + cpdef _add_(self, right) noexcept: """ Add two real numbers with the same parent. @@ -1322,7 +1322,7 @@ cdef class RealDoubleElement(FieldElement): x._value = self._value + (right)._value return x - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Subtract two real numbers with the same parent. @@ -1335,7 +1335,7 @@ cdef class RealDoubleElement(FieldElement): x._value = self._value - (right)._value return x - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Multiply two real numbers with the same parent. @@ -1348,7 +1348,7 @@ cdef class RealDoubleElement(FieldElement): x._value = self._value * (right)._value return x - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Divide ``self`` by ``right``. @@ -1409,7 +1409,7 @@ cdef class RealDoubleElement(FieldElement): else: return self._new_c(-self._value) - cpdef RealDoubleElement abs(RealDoubleElement self): + cpdef RealDoubleElement abs(RealDoubleElement self) noexcept: """ Returns the absolute value of ``self``. @@ -1740,7 +1740,7 @@ cdef class RealDoubleElement(FieldElement): """ return bool(libc.math.isinf(self._value)) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Rich comparison of ``left`` and ``right``. @@ -1998,7 +1998,7 @@ cdef class ToRDF(Morphism): R = Set_PythonType(R) Morphism.__init__(self, Hom(R, RDF)) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Send ``x`` to the image under this map. @@ -2093,7 +2093,7 @@ cdef int total_alloc = 0 cdef int use_pool = 0 -cdef PyObject* fast_tp_new(type t, args, kwds): +cdef PyObject* fast_tp_new(type t, args, kwds) noexcept: global element_pool, element_pool_count, total_alloc, use_pool cdef PyObject* new @@ -2151,7 +2151,7 @@ cdef PyObject* fast_tp_new(type t, args, kwds): return new -cdef void fast_tp_dealloc(PyObject* o): +cdef void fast_tp_dealloc(PyObject* o) noexcept: # If there is room in the pool for a used integer object, # then put it in rather than deallocating it. @@ -2185,7 +2185,7 @@ else: # From here on, calling PY_NEW(RealDoubleElement) actually creates an instance of RealDoubleElement_gsl -cdef double_repr(double x): +cdef double_repr(double x) noexcept: """ Convert a double to a string with maximum precision. """ diff --git a/src/sage/rings/real_double_element_gsl.pxd b/src/sage/rings/real_double_element_gsl.pxd index 4ddc886cdf1..39c36999ec4 100644 --- a/src/sage/rings/real_double_element_gsl.pxd +++ b/src/sage/rings/real_double_element_gsl.pxd @@ -2,6 +2,6 @@ from .real_double cimport RealDoubleElement cdef class RealDoubleElement_gsl(RealDoubleElement): - cdef __pow_double(self, double exponent, double sign) - cpdef _pow_(self, other) - cdef _log_base(self, double log_of_base) + cdef __pow_double(self, double exponent, double sign) noexcept + cpdef _pow_(self, other) noexcept + cdef _log_base(self, double log_of_base) noexcept diff --git a/src/sage/rings/real_double_element_gsl.pyx b/src/sage/rings/real_double_element_gsl.pyx index 8b6b3671605..3ebb703b367 100644 --- a/src/sage/rings/real_double_element_gsl.pyx +++ b/src/sage/rings/real_double_element_gsl.pyx @@ -57,7 +57,7 @@ cdef class RealDoubleElement_gsl(RealDoubleElement): else: return self ** (float(1)/n) - cdef __pow_double(self, double exponent, double sign): + cdef __pow_double(self, double exponent, double sign) noexcept: """ If ``sign == 1`` or ``self >= 0``, return ``self ^ exponent``. If ``sign == -1`` and ``self < 0``, return ``- abs(self) ^ exponent``. @@ -84,7 +84,7 @@ cdef class RealDoubleElement_gsl(RealDoubleElement): v = -v return self._new_c(sign * gsl_sf_exp(gsl_sf_log(v) * exponent)) - cpdef _pow_(self, other): + cpdef _pow_(self, other) noexcept: """ Return ``self`` raised to the real double power ``other``. @@ -117,7 +117,7 @@ cdef class RealDoubleElement_gsl(RealDoubleElement): """ return self.__pow_double((other)._value, 1) - cpdef _pow_int(self, n): + cpdef _pow_int(self, n) noexcept: """ Return ``self`` raised to the integer power ``n``. @@ -174,7 +174,7 @@ cdef class RealDoubleElement_gsl(RealDoubleElement): """ return self.__pow_double(n, -1.0 if (n & 1) else 1.0) - cdef _pow_long(self, long n): + cdef _pow_long(self, long n) noexcept: """ Compute ``self`` raised to the power ``n``. @@ -214,7 +214,7 @@ cdef class RealDoubleElement_gsl(RealDoubleElement): # of n to double might change an odd number to an even number. return self.__pow_double(n, -1.0 if (n & 1) else 1.0) - cdef _log_base(self, double log_of_base): + cdef _log_base(self, double log_of_base) noexcept: if self._value == 0: from .real_double import RDF return RDF(-1)/RDF(0) diff --git a/src/sage/rings/real_interval_absolute.pyx b/src/sage/rings/real_interval_absolute.pyx index 5caf4ac40f1..aab89c97d0e 100644 --- a/src/sage/rings/real_interval_absolute.pyx +++ b/src/sage/rings/real_interval_absolute.pyx @@ -23,7 +23,7 @@ from sage.rings.rational_field import QQ cdef Integer zero = Integer(0) cdef Integer one = Integer(1) -cpdef inline Integer shift_floor(Integer x, long shift): +cpdef inline Integer shift_floor(Integer x, long shift) noexcept: r""" Return `x / 2^s` where `s` is the value of ``shift``, rounded towards `-\infty`. For internal use. @@ -40,7 +40,7 @@ cpdef inline Integer shift_floor(Integer x, long shift): mpz_fdiv_q_2exp(z.value, x.value, shift) return z -cpdef inline Integer shift_ceil(Integer x, long shift): +cpdef inline Integer shift_ceil(Integer x, long shift) noexcept: r""" Return `x / 2^s` where `s` is the value of ``shift``, rounded towards `+\infty`. For internal use. @@ -161,7 +161,7 @@ cdef class RealIntervalAbsoluteField_class(Field): """ return RealIntervalAbsoluteElement(self, x) - cpdef _coerce_map_from_(self, R): + cpdef _coerce_map_from_(self, R) noexcept: """ Anything that coerces into the reals coerces into this ring. @@ -223,7 +223,7 @@ cdef class RealIntervalAbsoluteField_class(Field): return self._absprec -cdef inline shift_left(value, shift): +cdef inline shift_left(value, shift) noexcept: """ Utility function for operands that don't support the ``<<`` operator. """ @@ -319,7 +319,7 @@ cdef class RealIntervalAbsoluteElement(FieldElement): """ return RealIntervalAbsoluteElement, (self._parent, self.endpoints()) - cdef _new_c(self, Integer _mantissa, Integer _diameter): + cdef _new_c(self, Integer _mantissa, Integer _diameter) noexcept: cdef RealIntervalAbsoluteElement x x = RealIntervalAbsoluteElement.__new__(RealIntervalAbsoluteElement) x._parent = self._parent @@ -327,7 +327,7 @@ cdef class RealIntervalAbsoluteElement(FieldElement): x._diameter = _diameter return x - cpdef lower(self): + cpdef lower(self) noexcept: """ Return the lower bound of ``self``. @@ -340,7 +340,7 @@ cdef class RealIntervalAbsoluteElement(FieldElement): """ return QQ(self._mantissa) >> (self._parent)._absprec - cpdef midpoint(self): + cpdef midpoint(self) noexcept: """ Return the midpoint of ``self``. @@ -357,7 +357,7 @@ cdef class RealIntervalAbsoluteElement(FieldElement): """ return (self._mantissa + self._diameter / 2) >> (self._parent)._absprec - cpdef upper(self): + cpdef upper(self) noexcept: """ Return the upper bound of ``self``. @@ -370,7 +370,7 @@ cdef class RealIntervalAbsoluteElement(FieldElement): """ return QQ(self._mantissa + self._diameter) >> (self._parent)._absprec - cpdef absolute_diameter(self): + cpdef absolute_diameter(self) noexcept: """ Return the diameter ``self``. @@ -390,7 +390,7 @@ cdef class RealIntervalAbsoluteElement(FieldElement): diameter = absolute_diameter - cpdef endpoints(self): + cpdef endpoints(self) noexcept: """ Return the left and right endpoints of ``self``, as a tuple. @@ -422,7 +422,7 @@ cdef class RealIntervalAbsoluteElement(FieldElement): """ return R(self._mantissa, self._mantissa+self._diameter) >> (self._parent)._absprec - cpdef long mpfi_prec(self): + cpdef long mpfi_prec(self) noexcept: """ Return the precision needed to represent this value as an mpfi interval. @@ -495,7 +495,7 @@ cdef class RealIntervalAbsoluteElement(FieldElement): x *= (one << self._parent.absprec()) return self._mantissa <= x <= self._mantissa + self._diameter - cpdef bint is_positive(self): + cpdef bint is_positive(self) noexcept: """ Return whether ``self`` is definitely positive. @@ -518,7 +518,7 @@ cdef class RealIntervalAbsoluteElement(FieldElement): """ return mpz_sgn(self._mantissa.value) == 1 - cpdef bint contains_zero(self): + cpdef bint contains_zero(self) noexcept: """ Return whether ``self`` contains zero. @@ -544,7 +544,7 @@ cdef class RealIntervalAbsoluteElement(FieldElement): return (mpz_sgn(self._mantissa.value) == 0 or (mpz_sgn(self._mantissa.value) == -1 and mpz_cmpabs(self._mantissa.value, self._diameter.value) <= 0)) - cpdef bint is_negative(self): + cpdef bint is_negative(self) noexcept: """ Return whether ``self`` is definitely negative. @@ -568,7 +568,7 @@ cdef class RealIntervalAbsoluteElement(FieldElement): return (mpz_sgn(self._mantissa.value) == -1 and mpz_cmpabs(self._mantissa.value, self._diameter.value) > 0) - cdef bint is_exact(self): + cdef bint is_exact(self) noexcept: return not self._diameter def __bool__(self): @@ -612,7 +612,7 @@ cdef class RealIntervalAbsoluteElement(FieldElement): """ return self.abs() - cpdef abs(self): + cpdef abs(self) noexcept: """ Return the absolute value of ``self``. @@ -638,7 +638,7 @@ cdef class RealIntervalAbsoluteElement(FieldElement): else: return self._new_c(zero, max(-self._mantissa, self._mantissa + self._diameter)) - cpdef _add_(self, _other): + cpdef _add_(self, _other) noexcept: """ TESTS:: @@ -656,7 +656,7 @@ cdef class RealIntervalAbsoluteElement(FieldElement): cdef RealIntervalAbsoluteElement other = _other return self._new_c(self._mantissa + other._mantissa, self._diameter + other._diameter) - cpdef _sub_(self, _other): + cpdef _sub_(self, _other) noexcept: """ TESTS:: @@ -676,7 +676,7 @@ cdef class RealIntervalAbsoluteElement(FieldElement): cdef RealIntervalAbsoluteElement other = _other return self._new_c(self._mantissa - other._mantissa - other._diameter, self._diameter + other._diameter) - cpdef _mul_(self, _other): + cpdef _mul_(self, _other) noexcept: """ TESTS:: @@ -731,7 +731,7 @@ cdef class RealIntervalAbsoluteElement(FieldElement): res = -res return res - cpdef _acted_upon_(self, x, bint self_on_left): + cpdef _acted_upon_(self, x, bint self_on_left) noexcept: """ ``Absprec * relprec -> absprec`` works better than coercing both operands to absolute precision first. @@ -836,7 +836,7 @@ cdef class RealIntervalAbsoluteElement(FieldElement): res = -res return res - cpdef _div_(self, _other): + cpdef _div_(self, _other) noexcept: """ TESTS:: @@ -920,7 +920,7 @@ cdef class RealIntervalAbsoluteElement(FieldElement): """ return self.shift(-n) - cdef shift(self, long n): + cdef shift(self, long n) noexcept: if n >= 0: return self._new_c(self._mantissa << n, self._diameter << n) else: diff --git a/src/sage/rings/real_lazy.pxd b/src/sage/rings/real_lazy.pxd index 4110a83ae36..5619e492e9e 100644 --- a/src/sage/rings/real_lazy.pxd +++ b/src/sage/rings/real_lazy.pxd @@ -2,16 +2,16 @@ from sage.rings.ring cimport Field from sage.structure.element cimport RingElement, ModuleElement, Element, FieldElement cdef class LazyField(Field): - cpdef interval_field(self, prec=*) + cpdef interval_field(self, prec=*) noexcept cdef class LazyFieldElement(FieldElement): - cpdef _add_(self, other) - cpdef _mul_(self, other) - cdef LazyFieldElement _new_wrapper(self, value) - cdef LazyFieldElement _new_binop(self, LazyFieldElement left, LazyFieldElement right, op) - cdef LazyFieldElement _new_unop(self, LazyFieldElement arg, op) - cpdef eval(self, R) - cpdef int depth(self) + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept + cdef LazyFieldElement _new_wrapper(self, value) noexcept + cdef LazyFieldElement _new_binop(self, LazyFieldElement left, LazyFieldElement right, op) noexcept + cdef LazyFieldElement _new_unop(self, LazyFieldElement arg, op) noexcept + cpdef eval(self, R) noexcept + cpdef int depth(self) noexcept cdef class LazyWrapper(LazyFieldElement): cdef readonly _value diff --git a/src/sage/rings/real_lazy.pyx b/src/sage/rings/real_lazy.pyx index fb96ae89407..54a84e4920a 100644 --- a/src/sage/rings/real_lazy.pyx +++ b/src/sage/rings/real_lazy.pyx @@ -55,7 +55,7 @@ from sage.rings.cc import CC cdef _QQx = None -cdef QQx(): +cdef QQx() noexcept: global _QQx if _QQx is None: _QQx = QQ['x'] @@ -126,7 +126,7 @@ cdef class LazyField(Field): else: raise AttributeError(name) - cpdef _coerce_map_from_(self, R): + cpdef _coerce_map_from_(self, R) noexcept: r""" The only things that coerce into this ring are exact rings that embed into `\RR` or `\CC` (depending on whether this field @@ -198,7 +198,7 @@ cdef class LazyField(Field): """ return CLF - cpdef interval_field(self, prec=None): + cpdef interval_field(self, prec=None) noexcept: """ Abstract method to create the corresponding interval field. @@ -533,7 +533,7 @@ cdef int get_new_prec(R, int depth) except -1: cdef class LazyFieldElement(FieldElement): - cpdef _add_(left, right): + cpdef _add_(left, right) noexcept: """ Add ``left`` with ``right``. @@ -549,7 +549,7 @@ cdef class LazyFieldElement(FieldElement): pass return left._new_binop(left, right, add) - cpdef _sub_(left, right): + cpdef _sub_(left, right) noexcept: """ Subtract ``right`` from ``left``. @@ -565,7 +565,7 @@ cdef class LazyFieldElement(FieldElement): pass return left._new_binop(left, right, sub) - cpdef _mul_(left, right): + cpdef _mul_(left, right) noexcept: """ Multiply ``left`` with ``right``. @@ -581,7 +581,7 @@ cdef class LazyFieldElement(FieldElement): pass return left._new_binop(left, right, mul) - cpdef _div_(left, right): + cpdef _div_(left, right) noexcept: """ Divide ``left`` by ``right``. @@ -645,7 +645,7 @@ cdef class LazyFieldElement(FieldElement): """ return self._new_unop(self, inv) - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ If things are being wrapped, tries to compare values. That failing, it tries to compare intervals, which may return a false negative. @@ -699,13 +699,13 @@ cdef class LazyFieldElement(FieldElement): """ return hash(complex(self)) - cdef LazyFieldElement _new_wrapper(self, value): + cdef LazyFieldElement _new_wrapper(self, value) noexcept: cdef LazyWrapper e = LazyWrapper.__new__(LazyWrapper) e._parent = self._parent e._value = value return e - cdef LazyFieldElement _new_binop(self, LazyFieldElement left, LazyFieldElement right, op): + cdef LazyFieldElement _new_binop(self, LazyFieldElement left, LazyFieldElement right, op) noexcept: cdef LazyBinop e = LazyBinop.__new__(LazyBinop) e._parent = self._parent e._left = left @@ -713,7 +713,7 @@ cdef class LazyFieldElement(FieldElement): e._op = op return e - cdef LazyFieldElement _new_unop(self, LazyFieldElement arg, op): + cdef LazyFieldElement _new_unop(self, LazyFieldElement arg, op) noexcept: cdef LazyUnop e = LazyUnop.__new__(LazyUnop) e._parent = self._parent e._op = op @@ -817,7 +817,7 @@ cdef class LazyFieldElement(FieldElement): from .complex_mpfr import ComplexField return complex(self.eval(ComplexField(53))) - cpdef eval(self, R): + cpdef eval(self, R) noexcept: """ Abstract method for converting ``self`` into an element of ``R``. @@ -829,7 +829,7 @@ cdef class LazyFieldElement(FieldElement): """ raise NotImplementedError("Subclasses must override this method.") - cpdef int depth(self): + cpdef int depth(self) noexcept: """ Abstract method for returning the depth of ``self`` as an arithmetic expression. @@ -912,7 +912,7 @@ def make_element(parent, *args): cdef class LazyWrapper(LazyFieldElement): - cpdef int depth(self): + cpdef int depth(self) noexcept: """ Returns the depth of ``self`` as an expression, which is always 0. @@ -1005,7 +1005,7 @@ cdef class LazyWrapper(LazyFieldElement): """ return hash(self._value) - cpdef eval(self, R): + cpdef eval(self, R) noexcept: """ Convert ``self`` into an element of ``R``. @@ -1079,7 +1079,7 @@ cdef class LazyBinop(LazyFieldElement): self._right = right self._op = op - cpdef int depth(self): + cpdef int depth(self) noexcept: """ Return the depth of ``self`` as an arithmetic expression. @@ -1103,7 +1103,7 @@ cdef class LazyBinop(LazyFieldElement): cdef int right = self._right.depth() return 1 + (left if left > right else right) - cpdef eval(self, R): + cpdef eval(self, R) noexcept: """ Convert the operands to elements of ``R``, then perform the operation on them. @@ -1217,7 +1217,7 @@ cdef class LazyUnop(LazyFieldElement): self._op = op self._arg = arg - cpdef int depth(self): + cpdef int depth(self) noexcept: """ Return the depth of ``self`` as an arithmetic expression. @@ -1239,7 +1239,7 @@ cdef class LazyUnop(LazyFieldElement): """ return 1 + self._arg.depth() - cpdef eval(self, R): + cpdef eval(self, R) noexcept: """ Convert ``self`` into an element of ``R``. @@ -1318,7 +1318,7 @@ cdef class LazyNamedUnop(LazyUnop): raise TypeError("extra args must be a tuple") self._extra_args = extra_args - cpdef eval(self, R): + cpdef eval(self, R) noexcept: """ Convert ``self`` into an element of ``R``. @@ -1461,7 +1461,7 @@ cdef class LazyConstant(LazyFieldElement): self._name = name self._extra_args = extra_args - cpdef eval(self, R): + cpdef eval(self, R) noexcept: """ Convert ``self`` into an element of ``R``. @@ -1616,7 +1616,7 @@ cdef class LazyAlgebraic(LazyFieldElement): approx = (CC if prec == 0 else ComplexField(prec))(approx) self._root_approx = approx - cpdef eval(self, R): + cpdef eval(self, R) noexcept: """ Convert ``self`` into an element of ``R``. @@ -1723,7 +1723,7 @@ cdef class LazyWrapperMorphism(Morphism): from sage.categories.homset import Hom Morphism.__init__(self, Hom(domain, codomain)) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ EXAMPLES:: diff --git a/src/sage/rings/real_mpfi.pxd b/src/sage/rings/real_mpfi.pxd index 4201788d198..32332d81e3e 100644 --- a/src/sage/rings/real_mpfi.pxd +++ b/src/sage/rings/real_mpfi.pxd @@ -32,7 +32,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField): cdef RealField_class __upper_field cdef object _multiplicative_order - cdef inline RealIntervalFieldElement _new(self): + cdef inline RealIntervalFieldElement _new(self) noexcept: """Return a new real interval with parent ``self``.""" t = self.element_class return (t.__new__(t, self)) @@ -41,9 +41,9 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField): cdef class RealIntervalFieldElement(RingElement): cdef mpfi_t value - cdef inline RealIntervalFieldElement _new(self): + cdef inline RealIntervalFieldElement _new(self) noexcept: """Return a new real interval with same parent as ``self``.""" return (self._parent)._new() - cdef RealIntervalFieldElement abs(RealIntervalFieldElement self) - cdef Rational _simplest_rational_helper(self) - cpdef _str_question_style(self, int base, int error_digits, e, bint prefer_sci) + cdef RealIntervalFieldElement abs(RealIntervalFieldElement self) noexcept + cdef Rational _simplest_rational_helper(self) noexcept + cpdef _str_question_style(self, int base, int error_digits, e, bint prefer_sci) noexcept diff --git a/src/sage/rings/real_mpfi.pyx b/src/sage/rings/real_mpfi.pyx index 461b87db869..6e389b53ac2 100644 --- a/src/sage/rings/real_mpfi.pyx +++ b/src/sage/rings/real_mpfi.pyx @@ -303,7 +303,7 @@ printing_error_digits = 0 #***************************************************************************** cdef dict RealIntervalField_cache = {} -cpdef RealIntervalField_class RealIntervalField(prec=53, sci_not=False): +cpdef RealIntervalField_class RealIntervalField(prec=53, sci_not=False) noexcept: r""" Construct a :class:`RealIntervalField_class`, with caching. @@ -747,7 +747,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField): {'sci_not': self.scientific_notation(), 'type': 'Interval'}), sage.rings.rational_field.QQ) - cpdef _coerce_map_from_(self, S): + cpdef _coerce_map_from_(self, S) noexcept: """ Canonical coercion from ``S`` to this real interval field. @@ -1692,7 +1692,7 @@ cdef class RealIntervalFieldElement(RingElement): else: raise ValueError('Illegal interval printing style %s' % printing_style) - cpdef _str_question_style(self, int base, int error_digits, e, bint prefer_sci): + cpdef _str_question_style(self, int base, int error_digits, e, bint prefer_sci) noexcept: r""" Compute the "question-style print representation" of this value, with the given base and error_digits. See the documentation for @@ -2683,7 +2683,7 @@ cdef class RealIntervalFieldElement(RingElement): else: return Element.__rtruediv__(right, left) - cpdef _add_(self, other): + cpdef _add_(self, other) noexcept: """ Add two real intervals with the same parent. @@ -2727,7 +2727,7 @@ cdef class RealIntervalFieldElement(RingElement): mpfi_inv(x.value, self.value) return x - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Subtract two real intervals with the same parent. @@ -2745,7 +2745,7 @@ cdef class RealIntervalFieldElement(RingElement): mpfi_sub(x.value, self.value, (right).value) return x - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Multiply two real intervals with the same parent. @@ -2782,7 +2782,7 @@ cdef class RealIntervalFieldElement(RingElement): return x - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Divide ``self`` by ``right``, where both are real intervals with the same parent. @@ -2809,7 +2809,7 @@ cdef class RealIntervalFieldElement(RingElement): (right).value) return x - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ Return the additive "inverse" of this interval. (Technically, non-precise intervals don't have additive inverses.) @@ -2848,7 +2848,7 @@ cdef class RealIntervalFieldElement(RingElement): """ return self.abs() - cdef RealIntervalFieldElement abs(self): + cdef RealIntervalFieldElement abs(self) noexcept: """ Return the absolute value of ``self``. @@ -3653,7 +3653,7 @@ cdef class RealIntervalFieldElement(RingElement): low_open, high_open) - cdef Rational _simplest_rational_helper(self): + cdef Rational _simplest_rational_helper(self) noexcept: """ Returns the simplest rational in an interval which is either equal to or slightly larger than ``self``. We assume that both endpoints of @@ -3693,7 +3693,7 @@ cdef class RealIntervalFieldElement(RingElement): """ return mpfi_nan_p(self.value) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Implement comparisons between intervals. @@ -5186,7 +5186,7 @@ def _simplest_rational_test_helper(low, high, low_open=False, high_open=False): """ return _simplest_rational_exact(low, high, low_open, high_open) -cdef _simplest_rational_exact(Rational low, Rational high, int low_open, int high_open): +cdef _simplest_rational_exact(Rational low, Rational high, int low_open, int high_open) noexcept: """ Return the simplest rational between ``low`` and ``high``. May return ``low`` or ``high`` unless ``low_open`` or ``high_open`` (respectively) are diff --git a/src/sage/rings/real_mpfr.pxd b/src/sage/rings/real_mpfr.pxd index dd18e87715b..5d44208f339 100644 --- a/src/sage/rings/real_mpfr.pxd +++ b/src/sage/rings/real_mpfr.pxd @@ -13,20 +13,20 @@ cdef class RealField_class(sage.rings.abc.RealField): cdef bint sci_not cdef mpfr_rnd_t rnd cdef object rnd_str - cdef inline RealNumber _new(self): + cdef inline RealNumber _new(self) noexcept: """Return a new real number with parent ``self``.""" return (RealNumber.__new__(RealNumber, self)) cdef class RealNumber(sage.structure.element.RingElement): cdef mpfr_t value - cdef inline RealNumber _new(self): + cdef inline RealNumber _new(self) noexcept: """Return a new real number with same parent as ``self``.""" return (RealNumber.__new__(RealNumber, self._parent)) - cpdef _add_(self, other) - cpdef _mul_(self, other) - cpdef _mod_(self, right) - cdef _set(self, x, int base) - cdef _set_from_GEN_REAL(self, GEN g) - cdef RealNumber abs(RealNumber self) + cpdef _add_(self, other) noexcept + cpdef _mul_(self, other) noexcept + cpdef _mod_(self, right) noexcept + cdef _set(self, x, int base) noexcept + cdef _set_from_GEN_REAL(self, GEN g) noexcept + cdef RealNumber abs(RealNumber self) noexcept -cpdef RealField(mpfr_prec_t prec=*, int sci_not=*, rnd=*) +cpdef RealField(mpfr_prec_t prec=*, int sci_not=*, rnd=*) noexcept diff --git a/src/sage/rings/real_mpfr.pyx b/src/sage/rings/real_mpfr.pyx index fb2eb1d718c..4a091fd9191 100644 --- a/src/sage/rings/real_mpfr.pyx +++ b/src/sage/rings/real_mpfr.pyx @@ -373,7 +373,7 @@ cdef double LOG_TEN_TWO_PLUS_EPSILON = 3.321928094887363 # a small overestimate cdef object RealField_cache = sage.misc.weak_dict.WeakValueDictionary() -cpdef RealField(mpfr_prec_t prec=53, int sci_not=0, rnd=MPFR_RNDN): +cpdef RealField(mpfr_prec_t prec=53, int sci_not=0, rnd=MPFR_RNDN) noexcept: """ RealField(prec, sci_not, rnd): @@ -666,7 +666,7 @@ cdef class RealField_class(sage.rings.abc.RealField): z._set(x, base) return z - cpdef _coerce_map_from_(self, S): + cpdef _coerce_map_from_(self, S) noexcept: """ Canonical coercion of x to this MPFR real field. @@ -1452,7 +1452,7 @@ cdef class RealNumber(sage.structure.element.RingElement): else: return numpy_object_interface - cdef _set(self, x, int base): + cdef _set(self, x, int base) noexcept: # This should not be called except when the number is being created. # Real Numbers are supposed to be immutable. cdef RealField_class parent @@ -1504,7 +1504,7 @@ cdef class RealNumber(sage.structure.element.RingElement): else: raise TypeError("unable to convert {!r} to a real number".format(s)) - cdef _set_from_GEN_REAL(self, GEN g): + cdef _set_from_GEN_REAL(self, GEN g) noexcept: """ EXAMPLES:: @@ -2471,7 +2471,7 @@ cdef class RealNumber(sage.structure.element.RingElement): else: return Element.__rtruediv__(right, left) - cpdef _add_(self, other): + cpdef _add_(self, other) noexcept: """ Add two real numbers with the same parent. @@ -2500,7 +2500,7 @@ cdef class RealNumber(sage.structure.element.RingElement): """ return self._parent(1) / self - cpdef _sub_(self, right): + cpdef _sub_(self, right) noexcept: """ Subtract two real numbers with the same parent. @@ -2541,7 +2541,7 @@ cdef class RealNumber(sage.structure.element.RingElement): import sympy return sympy.Float(self, precision=self._parent.precision()) - cpdef _mul_(self, right): + cpdef _mul_(self, right) noexcept: """ Multiply two real numbers with the same parent. @@ -2574,7 +2574,7 @@ cdef class RealNumber(sage.structure.element.RingElement): return x - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Divide ``self`` by other, where both are real numbers with the same parent. @@ -2594,7 +2594,7 @@ cdef class RealNumber(sage.structure.element.RingElement): (right).value, (self._parent).rnd) return x - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ Return the negative of ``self``. @@ -2628,7 +2628,7 @@ cdef class RealNumber(sage.structure.element.RingElement): """ return self.abs() - cdef RealNumber abs(RealNumber self): + cdef RealNumber abs(RealNumber self) noexcept: """ Return the absolute value of ``self``. @@ -2981,7 +2981,7 @@ cdef class RealNumber(sage.structure.element.RingElement): # Rounding etc ################### - cpdef _mod_(left, right): + cpdef _mod_(left, right) noexcept: """ Return the value of ``left - n*right``, rounded according to the rounding mode of the parent, where ``n`` is the integer quotient of @@ -4147,7 +4147,7 @@ cdef class RealNumber(sage.structure.element.RingElement): """ return not mpfr_zero_p(self.value) - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: """ Compare ``self`` and ``other`` according to the rich comparison operator ``op``. @@ -5955,7 +5955,7 @@ def __create__RealNumber_version0(parent, x, base=10): cdef class RRtoRR(Map): - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ EXAMPLES:: @@ -6004,7 +6004,7 @@ cdef class RRtoRR(Map): return RRtoRR(self._codomain, self.domain()) cdef class ZZtoRR(Map): - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ EXAMPLES:: @@ -6019,7 +6019,7 @@ cdef class ZZtoRR(Map): return y cdef class QQtoRR(Map): - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ EXAMPLES:: @@ -6034,7 +6034,7 @@ cdef class QQtoRR(Map): return y cdef class double_toRR(Map): - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Takes anything that can be converted to a double. @@ -6054,7 +6054,7 @@ cdef class double_toRR(Map): return y cdef class int_toRR(Map): - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Takes Python int/long instances. diff --git a/src/sage/rings/ring_extension.pxd b/src/sage/rings/ring_extension.pxd index 9115f8d26f8..995bb23a976 100644 --- a/src/sage/rings/ring_extension.pxd +++ b/src/sage/rings/ring_extension.pxd @@ -14,12 +14,12 @@ cdef class RingExtension_generic(CommutativeAlgebra): cdef RingExtension_generic _fraction_field cdef type _fraction_field_type - cpdef is_defined_over(self, base) - cpdef CommutativeRing _check_base(self, CommutativeRing base) - cpdef _degree_over(self, CommutativeRing base) - cpdef _is_finite_over(self, CommutativeRing base) - cpdef _is_free_over(self, CommutativeRing base) - cdef Map _defining_morphism_fraction_field(self, bint extend_base) + cpdef is_defined_over(self, base) noexcept + cpdef CommutativeRing _check_base(self, CommutativeRing base) noexcept + cpdef _degree_over(self, CommutativeRing base) noexcept + cpdef _is_finite_over(self, CommutativeRing base) noexcept + cpdef _is_free_over(self, CommutativeRing base) noexcept + cdef Map _defining_morphism_fraction_field(self, bint extend_base) noexcept cdef class RingExtensionFractionField(RingExtension_generic): @@ -31,7 +31,7 @@ cdef class RingExtensionWithBasis(RingExtension_generic): cdef _basis_names cdef _basis_latex_names - cpdef _basis_over(self, CommutativeRing base) + cpdef _basis_over(self, CommutativeRing base) noexcept # cpdef _free_module(self, CommutativeRing base, bint map) diff --git a/src/sage/rings/ring_extension.pyx b/src/sage/rings/ring_extension.pyx index d9438aaa648..0388689a3e2 100644 --- a/src/sage/rings/ring_extension.pyx +++ b/src/sage/rings/ring_extension.pyx @@ -1007,7 +1007,7 @@ cdef class RingExtension_generic(CommutativeAlgebra): raise RuntimeError("backend is not exposed to the user; cannot print") return latex(self._backend) - cpdef _coerce_map_from_(self, other): + cpdef _coerce_map_from_(self, other) noexcept: r""" Return a coerce map from this extension to ``other`` if defined. @@ -1168,7 +1168,7 @@ cdef class RingExtension_generic(CommutativeAlgebra): """ return self.bases()[-1] - cpdef is_defined_over(self, base): + cpdef is_defined_over(self, base) noexcept: r""" Return whether or not ``base`` is one of the bases of this extension. @@ -1216,7 +1216,7 @@ cdef class RingExtension_generic(CommutativeAlgebra): b = (b)._base return b is base - cpdef CommutativeRing _check_base(self, CommutativeRing base): + cpdef CommutativeRing _check_base(self, CommutativeRing base) noexcept: r""" Check if ``base`` is one of the successive bases of this extension and, if it is, normalize it. @@ -1463,7 +1463,7 @@ cdef class RingExtension_generic(CommutativeAlgebra): base = self._check_base(base) return self._degree_over(base) - cpdef _degree_over(self, CommutativeRing base): + cpdef _degree_over(self, CommutativeRing base) noexcept: r""" Return the degree of this extension over ``base``. @@ -1603,7 +1603,7 @@ cdef class RingExtension_generic(CommutativeAlgebra): b = (b)._base raise NotImplementedError - cpdef _is_finite_over(self, CommutativeRing base): + cpdef _is_finite_over(self, CommutativeRing base) noexcept: r""" Return whether or not this extension is finite over ``base``. @@ -1666,7 +1666,7 @@ cdef class RingExtension_generic(CommutativeAlgebra): b = (b)._base raise NotImplementedError - cpdef _is_free_over(self, CommutativeRing base): + cpdef _is_free_over(self, CommutativeRing base) noexcept: r""" Return whether or not this extension is finite over ``base``. @@ -1782,7 +1782,7 @@ cdef class RingExtension_generic(CommutativeAlgebra): constructor = RingExtensionFractionField, {'ring': self, 'is_backend_exposed': self._is_backend_exposed} return RingExtension(ring, defining_morphism, constructors=[constructor]) - cdef Map _defining_morphism_fraction_field(self, bint extend_base): + cdef Map _defining_morphism_fraction_field(self, bint extend_base) noexcept: r""" Return the defining morphism of the fraction field of this extension. @@ -2207,7 +2207,7 @@ cdef class RingExtensionWithBasis(RingExtension_generic): b = b.base_ring() return base - cpdef _degree_over(self, CommutativeRing base): + cpdef _degree_over(self, CommutativeRing base) noexcept: r""" Return the degree of this extension over ``base``. @@ -2234,7 +2234,7 @@ cdef class RingExtensionWithBasis(RingExtension_generic): else: return len(self._basis) * self._base._degree_over(base) - cpdef _is_finite_over(self, CommutativeRing base): + cpdef _is_finite_over(self, CommutativeRing base) noexcept: r""" Return whether or not this extension is finite over ``base``. @@ -2253,7 +2253,7 @@ cdef class RingExtensionWithBasis(RingExtension_generic): return True return self._base._is_finite_over(base) - cpdef _is_free_over(self, CommutativeRing base): + cpdef _is_free_over(self, CommutativeRing base) noexcept: r""" Return whether or not this extension is free over ``base``. @@ -2314,7 +2314,7 @@ cdef class RingExtensionWithBasis(RingExtension_generic): base = self._check_base(base) return self._basis_over(base) - cpdef _basis_over(self, CommutativeRing base): + cpdef _basis_over(self, CommutativeRing base) noexcept: r""" Return a basis of this extension over ``base``. diff --git a/src/sage/rings/ring_extension_conversion.pxd b/src/sage/rings/ring_extension_conversion.pxd index e3815a411ba..74e09e4f356 100644 --- a/src/sage/rings/ring_extension_conversion.pxd +++ b/src/sage/rings/ring_extension_conversion.pxd @@ -1,17 +1,17 @@ from sage.rings.ring_extension cimport RingExtension_generic -cpdef backend_parent(R) -cpdef from_backend_parent(R, RingExtension_generic E) +cpdef backend_parent(R) noexcept +cpdef from_backend_parent(R, RingExtension_generic E) noexcept -cpdef backend_element(x) -cpdef from_backend_element(x, RingExtension_generic E) +cpdef backend_element(x) noexcept +cpdef from_backend_element(x, RingExtension_generic E) noexcept -cdef _backend_morphism(f) -cpdef backend_morphism(f, forget=*) -cpdef from_backend_morphism(f, RingExtension_generic E) +cdef _backend_morphism(f) noexcept +cpdef backend_morphism(f, forget=*) noexcept +cpdef from_backend_morphism(f, RingExtension_generic E) noexcept -cpdef to_backend(arg) -cpdef from_backend(arg, E) +cpdef to_backend(arg) noexcept +cpdef from_backend(arg, E) noexcept diff --git a/src/sage/rings/ring_extension_conversion.pyx b/src/sage/rings/ring_extension_conversion.pyx index eeb6077cd0a..597320e8af8 100644 --- a/src/sage/rings/ring_extension_conversion.pyx +++ b/src/sage/rings/ring_extension_conversion.pyx @@ -26,7 +26,7 @@ from sage.rings.ring_extension_morphism cimport RingExtensionBackendReverseIsomo # For parents ############# -cpdef backend_parent(R): +cpdef backend_parent(R) noexcept: r""" Return the backend parent of ``R``. @@ -49,7 +49,7 @@ cpdef backend_parent(R): else: return R -cpdef from_backend_parent(R, RingExtension_generic E): +cpdef from_backend_parent(R, RingExtension_generic E) noexcept: r""" Try to reconstruct a ring extension (somehow related to ``E``) whose backend is ``R``. @@ -107,7 +107,7 @@ cpdef from_backend_parent(R, RingExtension_generic E): # For elements ############## -cpdef backend_element(x): +cpdef backend_element(x) noexcept: r""" Return the backend element of ``x``. @@ -130,7 +130,7 @@ cpdef backend_element(x): else: return x -cpdef from_backend_element(x, RingExtension_generic E): +cpdef from_backend_element(x, RingExtension_generic E) noexcept: r""" Try to reconstruct an element in a ring extension (somehow related to ``E``) whose backend is ``x``. @@ -181,7 +181,7 @@ cpdef from_backend_element(x, RingExtension_generic E): # For morphisms ############### -cdef _backend_morphism(f): +cdef _backend_morphism(f) noexcept: r""" Return the backend morphism of ``f``. @@ -243,7 +243,7 @@ cdef _backend_morphism(f): return ring.coerce_map_from(domain) raise NotImplementedError -cpdef backend_morphism(f, forget="all"): +cpdef backend_morphism(f, forget="all") noexcept: r""" Return the backend morphism of ``f``. @@ -299,7 +299,7 @@ cpdef backend_morphism(f, forget="all"): g = RingExtensionBackendReverseIsomorphism(f.codomain().Hom(ring)) * g return g -cpdef from_backend_morphism(f, RingExtension_generic E): +cpdef from_backend_morphism(f, RingExtension_generic E) noexcept: r""" Try to reconstruct a morphism between ring extensions (somehow related to ``E``) whose backend is ``f``. @@ -336,7 +336,7 @@ cpdef from_backend_morphism(f, RingExtension_generic E): # Generic ######### -cpdef to_backend(arg): +cpdef to_backend(arg) noexcept: r""" Return the backend of ``arg``. @@ -392,7 +392,7 @@ cpdef to_backend(arg): return (arg)._backend return arg -cpdef from_backend(arg, E): +cpdef from_backend(arg, E) noexcept: r""" Try to reconstruct something (somehow related to ``E``) whose backend is ``arg``. diff --git a/src/sage/rings/ring_extension_element.pxd b/src/sage/rings/ring_extension_element.pxd index 6b62ad58c06..32ce1385248 100644 --- a/src/sage/rings/ring_extension_element.pxd +++ b/src/sage/rings/ring_extension_element.pxd @@ -13,10 +13,10 @@ cdef class RingExtensionFractionFieldElement(RingExtensionElement): pass cdef class RingExtensionWithBasisElement(RingExtensionElement): - cdef _vector(self, CommutativeRing base) - cdef _matrix(self, CommutativeRing base) - cdef _trace(self, CommutativeRing base) - cdef _norm(self, CommutativeRing base) - cpdef minpoly(self, base=*, var=*) + cdef _vector(self, CommutativeRing base) noexcept + cdef _matrix(self, CommutativeRing base) noexcept + cdef _trace(self, CommutativeRing base) noexcept + cdef _norm(self, CommutativeRing base) noexcept + cpdef minpoly(self, base=*, var=*) noexcept diff --git a/src/sage/rings/ring_extension_element.pyx b/src/sage/rings/ring_extension_element.pyx index fb80ba84e6e..cfc6b19cf2b 100644 --- a/src/sage/rings/ring_extension_element.pyx +++ b/src/sage/rings/ring_extension_element.pyx @@ -358,7 +358,7 @@ cdef class RingExtensionElement(CommutativeAlgebraElement): return parent.base()(base(self._backend)) raise NotImplementedError("cannot cast %s to the base" % self) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: r""" Compare this element with ``right`` according to the rich comparison operator ``op``. @@ -386,7 +386,7 @@ cdef class RingExtensionElement(CommutativeAlgebraElement): """ return left._backend._richcmp_(backend_element(right), op) - cpdef _add_(self,other): + cpdef _add_(self,other) noexcept: r""" Return the sum of this element and ``other``. @@ -406,7 +406,7 @@ cdef class RingExtensionElement(CommutativeAlgebraElement): ans._backend = self._backend + (other)._backend return ans - cpdef _neg_(self): + cpdef _neg_(self) noexcept: r""" Return the opposite of this element. @@ -426,7 +426,7 @@ cdef class RingExtensionElement(CommutativeAlgebraElement): ans._backend = -self._backend return ans - cpdef _sub_(self,other): + cpdef _sub_(self,other) noexcept: r""" Return the difference of this element and ``other``. @@ -446,7 +446,7 @@ cdef class RingExtensionElement(CommutativeAlgebraElement): ans._backend = self._backend - (other)._backend return ans - cpdef _mul_(self,other): + cpdef _mul_(self,other) noexcept: r""" Return the product of this element and ``other``. @@ -466,7 +466,7 @@ cdef class RingExtensionElement(CommutativeAlgebraElement): ans._backend = self._backend * (other)._backend return ans - cpdef _div_(self,other): + cpdef _div_(self,other) noexcept: r""" Return the quotient of this element by ``other``, considered as an element of the fraction field. @@ -1033,7 +1033,7 @@ cdef class RingExtensionWithBasisElement(RingExtensionElement): base = (self._parent)._check_base(base) return self._vector(base) - cdef _vector(self, CommutativeRing base): + cdef _vector(self, CommutativeRing base) noexcept: r""" Return the vector of coordinates of this element over ``base`` (in the basis output by the method :meth:`basis_over`). @@ -1198,7 +1198,7 @@ cdef class RingExtensionWithBasisElement(RingExtensionElement): raise ValueError("the extension is not finite free") return self._matrix(base) - cdef _matrix(self, CommutativeRing base): + cdef _matrix(self, CommutativeRing base) noexcept: r""" Return the matrix of the multiplication by this element (in the basis output by :meth:`basis_over`). @@ -1286,7 +1286,7 @@ cdef class RingExtensionWithBasisElement(RingExtensionElement): raise ValueError("the extension is not finite free") return self._trace(base) - cdef _trace(self, CommutativeRing base): + cdef _trace(self, CommutativeRing base) noexcept: r""" Return the trace of this element over ``base``. @@ -1379,7 +1379,7 @@ cdef class RingExtensionWithBasisElement(RingExtensionElement): raise ValueError("the extension is not finite free") return self._norm(base) - cdef _norm(self, CommutativeRing base): + cdef _norm(self, CommutativeRing base) noexcept: r""" Return the norm of this element over ``base``. @@ -1483,7 +1483,7 @@ cdef class RingExtensionWithBasisElement(RingExtensionElement): """ return self.matrix(base).charpoly(var) - cpdef minpoly(self, base=None, var='x'): + cpdef minpoly(self, base=None, var='x') noexcept: r""" Return the minimal polynomial of this element over ``base``. diff --git a/src/sage/rings/ring_extension_morphism.pxd b/src/sage/rings/ring_extension_morphism.pxd index a02aff31a50..f3d88ec3891 100644 --- a/src/sage/rings/ring_extension_morphism.pxd +++ b/src/sage/rings/ring_extension_morphism.pxd @@ -4,7 +4,7 @@ from sage.rings.morphism cimport RingMap from sage.rings.ring_extension_element cimport RingExtensionElement -cdef are_equal_morphisms(f, g) +cdef are_equal_morphisms(f, g) noexcept cdef class RingExtensionHomomorphism(RingMap): @@ -31,4 +31,4 @@ cdef class MapRelativeRingToFreeModule(Map): cdef Map _jL cdef _matrix - cdef list backend_coefficients(self, RingExtensionElement x) + cdef list backend_coefficients(self, RingExtensionElement x) noexcept diff --git a/src/sage/rings/ring_extension_morphism.pyx b/src/sage/rings/ring_extension_morphism.pyx index f861d015a35..4d78ee1c5d0 100644 --- a/src/sage/rings/ring_extension_morphism.pyx +++ b/src/sage/rings/ring_extension_morphism.pyx @@ -29,7 +29,7 @@ from sage.rings.ring_extension_conversion cimport backend_parent, backend_elemen # I don't trust the operator == -cdef are_equal_morphisms(f, g): +cdef are_equal_morphisms(f, g) noexcept: r""" Return ``True`` if ``f`` and ``g`` coincide on the generators of the domain, ``False`` otherwise. @@ -227,7 +227,7 @@ cdef class RingExtensionHomomorphism(RingMap): """ return "Ring" - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: r""" Return the image of ``x`` under this morphism. @@ -318,7 +318,7 @@ cdef class RingExtensionHomomorphism(RingMap): base_map = base_map.extend_codomain(self.codomain()) return base_map - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: r""" Compare this element with ``other`` according to the rich comparison operator ``op``. @@ -494,7 +494,7 @@ cdef class RingExtensionHomomorphism(RingMap): else: return backend - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper function for copying and pickling. @@ -512,7 +512,7 @@ cdef class RingExtensionHomomorphism(RingMap): self._backend = _slots['_backend'] RingMap._update_slots(self, _slots) - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper function for copying and pickling. @@ -598,7 +598,7 @@ cdef class RingExtensionBackendIsomorphism(RingExtensionHomomorphism): """ return "" - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: r""" Return the image of ``x`` under this morphism. @@ -688,7 +688,7 @@ cdef class RingExtensionBackendReverseIsomorphism(RingExtensionHomomorphism): """ return "" - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: r""" Return the image of ``x`` under this morphism. @@ -771,7 +771,7 @@ cdef class MapFreeModuleToRelativeRing(Map): """ return True - cpdef Element _call_(self, v): + cpdef Element _call_(self, v) noexcept: r""" Return the image of ``x`` under this morphism. @@ -880,7 +880,7 @@ cdef class MapRelativeRingToFreeModule(Map): """ return True - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: r""" Return the image of ``x`` under this morphism. @@ -898,7 +898,7 @@ cdef class MapRelativeRingToFreeModule(Map): coeffs = self.backend_coefficients(x) return self.codomain()(coeffs) - cdef list backend_coefficients(self, RingExtensionElement x): + cdef list backend_coefficients(self, RingExtensionElement x) noexcept: r""" Return the coordinates of the image of ``x`` as elements of the backend ring. diff --git a/src/sage/rings/semirings/tropical_semiring.pyx b/src/sage/rings/semirings/tropical_semiring.pyx index 2922298e286..3f25fb8af98 100644 --- a/src/sage/rings/semirings/tropical_semiring.pyx +++ b/src/sage/rings/semirings/tropical_semiring.pyx @@ -38,7 +38,7 @@ cdef class TropicalSemiringElement(Element): """ cdef ModuleElement _val - cdef TropicalSemiringElement _new(self): + cdef TropicalSemiringElement _new(self) noexcept: """ Return a new tropical semiring element with parent ``self`. """ @@ -132,7 +132,7 @@ cdef class TropicalSemiringElement(Element): return hash(self._val) # Comparisons - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: r""" Return the standard comparison of ``left`` and ``right``. @@ -206,7 +206,7 @@ cdef class TropicalSemiringElement(Element): return rich_to_bool(op, 1) return rich_to_bool(op, 0) - cpdef _add_(left, right): + cpdef _add_(left, right) noexcept: """ Add ``left`` to ``right``. @@ -274,7 +274,7 @@ cdef class TropicalSemiringElement(Element): return self raise ArithmeticError("cannot negate any non-infinite element") - cpdef _mul_(left, right): + cpdef _mul_(left, right) noexcept: """ Multiply ``left`` and ``right``. @@ -300,7 +300,7 @@ cdef class TropicalSemiringElement(Element): x._val = self._val + rhs._val return x - cpdef _div_(left, right): + cpdef _div_(left, right) noexcept: """ Divide ``left`` by ``right``. @@ -398,7 +398,7 @@ cdef class TropicalSemiringElement(Element): from sage.rings.infinity import infinity return infinity - cpdef ModuleElement lift(self): + cpdef ModuleElement lift(self) noexcept: """ Return the value of ``self`` lifted to the base. @@ -656,7 +656,7 @@ cdef class TropicalToTropical(Map): Map from the tropical semiring to itself (possibly with different bases). Used in coercion. """ - cpdef TropicalSemiringElement _call_(self, x): + cpdef TropicalSemiringElement _call_(self, x) noexcept: """ EXAMPLES:: diff --git a/src/sage/rings/sum_of_squares.pxd b/src/sage/rings/sum_of_squares.pxd index 47d43124f8b..d9f2e5ae4fd 100644 --- a/src/sage/rings/sum_of_squares.pxd +++ b/src/sage/rings/sum_of_squares.pxd @@ -1,2 +1,2 @@ from libc.stdint cimport uint_fast32_t, uint32_t -cdef int two_squares_c(uint_fast32_t n, uint_fast32_t res[2]) +cdef int two_squares_c(uint_fast32_t n, uint_fast32_t res[2]) noexcept diff --git a/src/sage/rings/sum_of_squares.pyx b/src/sage/rings/sum_of_squares.pyx index b8f719d4dac..737911ad53e 100644 --- a/src/sage/rings/sum_of_squares.pyx +++ b/src/sage/rings/sum_of_squares.pyx @@ -24,7 +24,7 @@ from cysignals.signals cimport sig_on, sig_off cimport sage.rings.integer as integer from . import integer -cdef int two_squares_c(uint_fast32_t n, uint_fast32_t res[2]): +cdef int two_squares_c(uint_fast32_t n, uint_fast32_t res[2]) noexcept: r""" Return ``1`` if ``n`` is a sum of two squares and ``0`` otherwise. @@ -94,7 +94,7 @@ cdef int two_squares_c(uint_fast32_t n, uint_fast32_t res[2]): return 0 -cdef int three_squares_c(uint_fast32_t n, uint_fast32_t res[3]): +cdef int three_squares_c(uint_fast32_t n, uint_fast32_t res[3]) noexcept: r""" Return `1` if `n` is a sum of three squares and `0` otherwise. diff --git a/src/sage/rings/tate_algebra_element.pxd b/src/sage/rings/tate_algebra_element.pxd index 20aff3a7fc1..5c529825e4c 100644 --- a/src/sage/rings/tate_algebra_element.pxd +++ b/src/sage/rings/tate_algebra_element.pxd @@ -13,19 +13,19 @@ cdef class TateAlgebraTerm(MonoidElement): cdef pAdicGenericElement _coeff cdef ETuple _exponent - cpdef _mul_(self, other) - cdef TateAlgebraTerm _floordiv_c(self, TateAlgebraTerm other) - cpdef _floordiv_(self, other) + cpdef _mul_(self, other) noexcept + cdef TateAlgebraTerm _floordiv_c(self, TateAlgebraTerm other) noexcept + cpdef _floordiv_(self, other) noexcept - cdef TateAlgebraTerm _new_c(self) - cdef long _valuation_c(self) + cdef TateAlgebraTerm _new_c(self) noexcept + cdef long _valuation_c(self) noexcept cdef long _cmp_c(self, TateAlgebraTerm other) except? 300 - cdef Element _call_c(self, list arg) - cpdef TateAlgebraTerm monomial(self) - cpdef TateAlgebraTerm monic(self) - cdef TateAlgebraTerm _gcd_c(self, TateAlgebraTerm other) - cdef TateAlgebraTerm _lcm_c(self, TateAlgebraTerm other) - cdef bint _divides_c(self, TateAlgebraTerm other, bint integral) + cdef Element _call_c(self, list arg) noexcept + cpdef TateAlgebraTerm monomial(self) noexcept + cpdef TateAlgebraTerm monic(self) noexcept + cdef TateAlgebraTerm _gcd_c(self, TateAlgebraTerm other) noexcept + cdef TateAlgebraTerm _lcm_c(self, TateAlgebraTerm other) noexcept + cdef bint _divides_c(self, TateAlgebraTerm other, bint integral) noexcept cdef class TateAlgebraElement(CommutativeAlgebraElement): @@ -35,15 +35,15 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): cdef list _terms_nonzero cdef bint _is_normalized - cdef _normalize(self) - cdef TateAlgebraElement _new_c(self) - cdef list _terms_c(self, bint include_zero=*) - cpdef valuation(self) - cdef TateAlgebraElement _term_mul_c(self, TateAlgebraTerm term) - cdef TateAlgebraElement _positive_lshift_c(self, n) - cdef TateAlgebraElement _lshift_c(self, n) - cpdef TateAlgebraElement monic(self) - cdef _quo_rem_c(self, list divisors, bint quo, bint rem, bint integral) - cdef _quo_rem_check(self, divisors, bint quo, bint rem) - cdef TateAlgebraElement _Spoly_c(self, TateAlgebraElement other) + cdef _normalize(self) noexcept + cdef TateAlgebraElement _new_c(self) noexcept + cdef list _terms_c(self, bint include_zero=*) noexcept + cpdef valuation(self) noexcept + cdef TateAlgebraElement _term_mul_c(self, TateAlgebraTerm term) noexcept + cdef TateAlgebraElement _positive_lshift_c(self, n) noexcept + cdef TateAlgebraElement _lshift_c(self, n) noexcept + cpdef TateAlgebraElement monic(self) noexcept + cdef _quo_rem_c(self, list divisors, bint quo, bint rem, bint integral) noexcept + cdef _quo_rem_check(self, divisors, bint quo, bint rem) noexcept + cdef TateAlgebraElement _Spoly_c(self, TateAlgebraElement other) noexcept diff --git a/src/sage/rings/tate_algebra_element.pyx b/src/sage/rings/tate_algebra_element.pyx index b9be89b99b6..e812a0a7f5f 100644 --- a/src/sage/rings/tate_algebra_element.pyx +++ b/src/sage/rings/tate_algebra_element.pyx @@ -167,7 +167,7 @@ cdef class TateAlgebraTerm(MonoidElement): """ return hash((self._coeff, self._exponent)) - cdef TateAlgebraTerm _new_c(self): + cdef TateAlgebraTerm _new_c(self) noexcept: r""" Fast creation of a Tate algebra term. @@ -309,7 +309,7 @@ cdef class TateAlgebraTerm(MonoidElement): """ return self._exponent - cpdef _mul_(self, other): + cpdef _mul_(self, other) noexcept: r""" Return the product of this Tate algebra term with ``other``. @@ -385,7 +385,7 @@ cdef class TateAlgebraTerm(MonoidElement): c = (ks > ko) - (ks < ko) return c - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: r""" Compare the Tate algebra term with ``other`` according to the rich comparison operator ``op``. @@ -446,7 +446,7 @@ cdef class TateAlgebraTerm(MonoidElement): c = (self)._cmp_c(other) return rich_to_bool_sgn(op, c) - cpdef TateAlgebraTerm monomial(self): + cpdef TateAlgebraTerm monomial(self) noexcept: r""" Return this term divided by its coefficient. @@ -466,7 +466,7 @@ cdef class TateAlgebraTerm(MonoidElement): ans._exponent = self._exponent return ans - cpdef TateAlgebraTerm monic(self): + cpdef TateAlgebraTerm monic(self) noexcept: r""" Return this term normalized so that it has valuation 0 and its coefficient is a power of the uniformizer. @@ -540,7 +540,7 @@ cdef class TateAlgebraTerm(MonoidElement): """ return ZZ(self._valuation_c()) - cdef long _valuation_c(self): + cdef long _valuation_c(self) noexcept: r""" Return the valuation of this term. @@ -557,7 +557,7 @@ cdef class TateAlgebraTerm(MonoidElement): """ return (self._coeff).valuation_c() - self._exponent.dotprod(self._parent._log_radii) - cdef Element _call_c(self, list arg): + cdef Element _call_c(self, list arg) noexcept: """ Return this term evaluated at ``args``. @@ -725,7 +725,7 @@ cdef class TateAlgebraTerm(MonoidElement): """ return self._gcd_c(other) - cdef TateAlgebraTerm _gcd_c(self, TateAlgebraTerm other): + cdef TateAlgebraTerm _gcd_c(self, TateAlgebraTerm other) noexcept: r""" Return the greatest common divisor of this term and ``other``. @@ -795,7 +795,7 @@ cdef class TateAlgebraTerm(MonoidElement): """ return self._lcm_c(other) - cdef TateAlgebraTerm _lcm_c(self, TateAlgebraTerm other): + cdef TateAlgebraTerm _lcm_c(self, TateAlgebraTerm other) noexcept: r""" Return the least common multiple of two Tate terms. @@ -948,7 +948,7 @@ cdef class TateAlgebraTerm(MonoidElement): """ return self._divides_c(other, integral) - cdef bint _divides_c(self, TateAlgebraTerm other, bint integral): + cdef bint _divides_c(self, TateAlgebraTerm other, bint integral) noexcept: r""" Return ``True`` if this term divides ``other``. @@ -980,7 +980,7 @@ cdef class TateAlgebraTerm(MonoidElement): return False return True - cpdef _floordiv_(self, other): + cpdef _floordiv_(self, other) noexcept: r""" Return the result of the exact division of this term by ``other``. @@ -1013,7 +1013,7 @@ cdef class TateAlgebraTerm(MonoidElement): return (self)._floordiv_c(other) - cdef TateAlgebraTerm _floordiv_c(self, TateAlgebraTerm other): + cdef TateAlgebraTerm _floordiv_c(self, TateAlgebraTerm other) noexcept: r""" Return the result of the exact division of this term by ``other``. @@ -1120,7 +1120,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): if not parent.base_ring().is_field() and self.valuation() < 0: raise ValueError("this series is not in the ring of integers") - cdef TateAlgebraElement _new_c(self): + cdef TateAlgebraElement _new_c(self) noexcept: """ Fast creation of a new Tate series. @@ -1138,7 +1138,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): ans._terms = ans._terms_nonzero = None return ans - cdef _normalize(self): + cdef _normalize(self) noexcept: """ Normalize this series. @@ -1279,7 +1279,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): s += "O\\left(%s^{%s} %s\\right)" % (self._parent._uniformizer_latex, self._prec, self._parent.integer_ring()._latex_()) return s - cpdef _add_(self, other): + cpdef _add_(self, other) noexcept: r""" Return the sum of this series and ``other``. @@ -1314,7 +1314,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): ans._normalize() return ans - cpdef _neg_(self): + cpdef _neg_(self) noexcept: r""" Return the opposite of this series. @@ -1334,7 +1334,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): ans._prec = self._prec return ans - cpdef _sub_(self, other): + cpdef _sub_(self, other) noexcept: r""" Return the difference of this series and ``other``. @@ -1367,7 +1367,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): ans._normalize() return ans - cpdef _mul_(self, other): + cpdef _mul_(self, other) noexcept: r""" Return the product of this series with ``other``. @@ -1402,7 +1402,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): ans._normalize() return ans - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: r""" Return the product of this series by ``right``. @@ -1783,7 +1783,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): return root - cpdef _richcmp_(self, other, int op): + cpdef _richcmp_(self, other, int op) noexcept: r""" Compare this series with ``other`` according to the rich comparison operator ``op``. @@ -1922,7 +1922,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): pass return res - cdef TateAlgebraElement _term_mul_c(self, TateAlgebraTerm term): + cdef TateAlgebraElement _term_mul_c(self, TateAlgebraTerm term) noexcept: r""" Return the product of this series by the term ``term``. @@ -1943,7 +1943,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): ans._prec = self._prec + term._valuation_c() return ans - cdef TateAlgebraElement _positive_lshift_c(self, n): + cdef TateAlgebraElement _positive_lshift_c(self, n) noexcept: r""" Return the product of this series by the ``n``-th power of the uniformizer. @@ -1972,7 +1972,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): ans._prec = self._prec + n return ans - cdef TateAlgebraElement _lshift_c(self, n): + cdef TateAlgebraElement _lshift_c(self, n) noexcept: r""" Return the product of this series by the ``n``-th power of the uniformizer. @@ -2190,7 +2190,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): self._terms = None return self._terms_c() - cdef list _terms_c(self, bint include_zero=True): + cdef list _terms_c(self, bint include_zero=True) noexcept: r""" Return a list of the terms of this series sorted in descending order. @@ -2453,7 +2453,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): """ return self._prec - cpdef valuation(self): + cpdef valuation(self) noexcept: r""" Return the valuation of this series. @@ -2941,7 +2941,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): """ return self.leading_term(secure=secure).monomial() - cpdef TateAlgebraElement monic(self): + cpdef TateAlgebraElement monic(self) noexcept: r""" Return this series normalized so that it has valuation 0 and its leading coefficient is a power of the uniformizer. @@ -3162,7 +3162,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): poly = self._parent._polynomial_ring(self._poly) return poly.change_ring(Rn) - cdef _quo_rem_c(self, list divisors, bint quo, bint rem, bint integral): + cdef _quo_rem_c(self, list divisors, bint quo, bint rem, bint integral) noexcept: r""" Perform the division of this series by ``divisors``. @@ -3235,7 +3235,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): f._terms = None return quos, f - cdef _quo_rem_check(self, divisors, bint quo, bint rem): + cdef _quo_rem_check(self, divisors, bint quo, bint rem) noexcept: """ Perform the division of this series by ``divisors``. @@ -3491,7 +3491,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): except IndexError: raise ValueError("the S-polynomial of zero is not defined") - cdef TateAlgebraElement _Spoly_c(self, TateAlgebraElement other): + cdef TateAlgebraElement _Spoly_c(self, TateAlgebraElement other) noexcept: """ Return the S-polynomial of this series and ``other``. diff --git a/src/sage/rings/tate_algebra_ideal.pxd b/src/sage/rings/tate_algebra_ideal.pxd index e5581e06b8c..d6c239b9a0c 100644 --- a/src/sage/rings/tate_algebra_ideal.pxd +++ b/src/sage/rings/tate_algebra_ideal.pxd @@ -1,6 +1,6 @@ from sage.rings.tate_algebra_element cimport TateAlgebraTerm from sage.rings.tate_algebra_element cimport TateAlgebraElement -cdef Jpair(p1, p2) -cdef TateAlgebraElement regular_reduce(sgb, TateAlgebraTerm s, TateAlgebraElement v, stopval) -cdef TateAlgebraElement reduce(gb, TateAlgebraElement v, stopval) +cdef Jpair(p1, p2) noexcept +cdef TateAlgebraElement regular_reduce(sgb, TateAlgebraTerm s, TateAlgebraElement v, stopval) noexcept +cdef TateAlgebraElement reduce(gb, TateAlgebraElement v, stopval) noexcept diff --git a/src/sage/rings/tate_algebra_ideal.pyx b/src/sage/rings/tate_algebra_ideal.pyx index e230a411397..982d9581635 100644 --- a/src/sage/rings/tate_algebra_ideal.pyx +++ b/src/sage/rings/tate_algebra_ideal.pyx @@ -567,7 +567,7 @@ def groebner_basis_buchberger(I, prec, py_integral): # F5 algorithms -cdef Jpair(p1, p2): +cdef Jpair(p1, p2) noexcept: r""" Return the J-pair of ``p1`` and ``p2`` @@ -605,7 +605,7 @@ cdef Jpair(p1, p2): return su2, t2*v2 -cdef TateAlgebraElement regular_reduce(sgb, TateAlgebraTerm s, TateAlgebraElement v, stopval): +cdef TateAlgebraElement regular_reduce(sgb, TateAlgebraTerm s, TateAlgebraElement v, stopval) noexcept: r""" Return the result of the regular reduction of the pair ``(s,v)`` by ``sgb`` @@ -689,7 +689,7 @@ cdef TateAlgebraElement regular_reduce(sgb, TateAlgebraTerm s, TateAlgebraElemen return f -cdef TateAlgebraElement reduce(gb, TateAlgebraElement v, stopval): +cdef TateAlgebraElement reduce(gb, TateAlgebraElement v, stopval) noexcept: r""" Return the result of the reduction of ``v`` by ``gb`` diff --git a/src/sage/schemes/affine/affine_homset.py b/src/sage/schemes/affine/affine_homset.py index 52ea3f83c85..b6570bd6f6d 100644 --- a/src/sage/schemes/affine/affine_homset.py +++ b/src/sage/schemes/affine/affine_homset.py @@ -393,7 +393,7 @@ def numerical_points(self, F=None, **kwds): EXAMPLES:: - sage: # needs sage.rings.number_field + sage: # needs sage.libs.singular sage.rings.number_field sage: K. = QuadraticField(3) sage: A. = AffineSpace(K, 2) sage: X = A.subscheme([x^3 - v^2*y, y - v*x^2 + 3]) diff --git a/src/sage/schemes/affine/affine_morphism.py b/src/sage/schemes/affine/affine_morphism.py index 1fc3f207464..dd9eb7cf844 100644 --- a/src/sage/schemes/affine/affine_morphism.py +++ b/src/sage/schemes/affine/affine_morphism.py @@ -48,6 +48,8 @@ import sys +import sage.rings.abc + from sage.calculus.functions import jacobian from sage.categories.homset import Hom, End @@ -68,10 +70,7 @@ from sage.schemes.generic.morphism import SchemeMorphism_polynomial -from sage.ext.fast_callable import fast_callable - from sage.categories.number_fields import NumberFields -from sage.rings.number_field.order import is_NumberFieldOrder _NumberFields = NumberFields() _Fields = Fields() @@ -361,6 +360,8 @@ def _fastpolys(self): 1), ('load_arg', ...), ('ipow', 1), 'mul', 'add', ('load_const', 1), 'add', 'return']] """ + from sage.ext.fast_callable import fast_callable + polys = self._polys R = self.domain().ambient_space().coordinate_ring() @@ -800,7 +801,7 @@ def local_height(self, v, prec=None): 1.09861228866811 """ K = FractionField(self.domain().base_ring()) - if K not in _NumberFields or is_NumberFieldOrder(K): + if K not in _NumberFields: raise TypeError("must be over a number field or a number field order") return max([K(c).local_height(v, prec=prec) for f in self for c in f.coefficients()]) @@ -848,7 +849,7 @@ def local_height_arch(self, i, prec=None): 0.6931471805599453094172321214582 """ K = FractionField(self.domain().base_ring()) - if K not in _NumberFields or is_NumberFieldOrder(K): + if K not in _NumberFields: raise TypeError("must be over a number field or a number field order") if K == QQ: @@ -1068,7 +1069,7 @@ def weil_restriction(self): sage: A. = AffineSpace(K, 2) sage: H = End(A) sage: f = H([x^2 - y^2, y^2]) - sage: f.weil_restriction() + sage: f.weil_restriction() # needs sage.libs.singular Scheme endomorphism of Affine Space of dimension 4 over Rational Field Defn: Defined on coordinates by sending (z0, z1, z2, z3) to (z0^2 + 5*z1^2 - z2^2 - 5*z3^2, 2*z0*z1 - 2*z2*z3, z2^2 + 5*z3^2, 2*z2*z3) @@ -1083,7 +1084,7 @@ def weil_restriction(self): sage: F = f.weil_restriction() sage: P = PS(2, 1) sage: Q = P.weil_restriction() - sage: f(P).weil_restriction() == F(Q) + sage: f(P).weil_restriction() == F(Q) # needs sage.libs.singular True """ if any(isinstance(f, FractionFieldElement) for f in self): diff --git a/src/sage/schemes/affine/affine_point.py b/src/sage/schemes/affine/affine_point.py index a665ba6881a..dabcaa134f9 100644 --- a/src/sage/schemes/affine/affine_point.py +++ b/src/sage/schemes/affine/affine_point.py @@ -31,9 +31,7 @@ from sage.categories.number_fields import NumberFields from sage.rings.integer_ring import ZZ -from sage.rings.number_field.order import is_NumberFieldOrder -from sage.rings.real_mpfr import RealField -from sage.schemes.generic.morphism import (SchemeMorphism_point, SchemeMorphism, is_SchemeMorphism) +from sage.schemes.generic.morphism import SchemeMorphism_point, SchemeMorphism, is_SchemeMorphism from sage.structure.sequence import Sequence _NumberFields = NumberFields() @@ -206,13 +204,14 @@ def global_height(self, prec=None): P-adic heights. """ if self.domain().base_ring() == ZZ: + from sage.rings.real_mpfr import RealField if prec is None: R = RealField() else: R = RealField(prec) H = max([self[i].abs() for i in range(self.codomain().ambient_space().dimension_relative())]) - return R(max(H, 1)).log() - if self.domain().base_ring() in _NumberFields or is_NumberFieldOrder(self.domain().base_ring()): + return R(max(H,1)).log() + if self.domain().base_ring() in _NumberFields or isinstance(self.domain().base_ring(), sage.rings.abc.Order): return max([self[i].global_height(prec) for i in range(self.codomain().ambient_space().dimension_relative())]) else: raise NotImplementedError("must be over a number field or a number field Order") diff --git a/src/sage/schemes/affine/affine_space.py b/src/sage/schemes/affine/affine_space.py index 42de0a0ec16..ef1ae326a43 100644 --- a/src/sage/schemes/affine/affine_space.py +++ b/src/sage/schemes/affine/affine_space.py @@ -11,7 +11,6 @@ # **************************************************************************** from itertools import product -from sage.functions.orthogonal_polys import chebyshev_T, chebyshev_U from sage.rings.integer import Integer from sage.rings.integer_ring import ZZ from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing @@ -23,7 +22,6 @@ from sage.categories.fields import Fields from sage.categories.number_fields import NumberFields from sage.misc.latex import latex -from sage.matrix.constructor import matrix from sage.structure.category_object import normalize_names from sage.schemes.generic.scheme import AffineScheme from sage.schemes.generic.ambient_space import AmbientSpace @@ -938,9 +936,13 @@ def chebyshev_polynomial(self, n, kind='first', monic=False): if self.dimension_relative() != 1: raise TypeError("affine space must be of dimension 1") n = ZZ(n) - if (n < 0): + if n < 0: raise ValueError("first parameter 'n' must be a non-negative integer") + from sage.dynamics.arithmetic_dynamics.affine_ds import DynamicalSystem_affine + from sage.functions.orthogonal_polys import chebyshev_T, chebyshev_U + from sage.matrix.constructor import matrix + if kind == 'first': if monic and self.base().characteristic() != 2: f = DynamicalSystem_affine([chebyshev_T(n, self.gen(0))], domain=self) @@ -1149,7 +1151,7 @@ def curve(self, F): EXAMPLES:: sage: A. = AffineSpace(QQ, 3) - sage: A.curve([y - x^4, z - y^5]) # needs sage.libs.pari + sage: A.curve([y - x^4, z - y^5]) # needs sage.schemes Affine Curve over Rational Field defined by -x^4 + y, -y^5 + z """ from sage.schemes.curves.constructor import Curve diff --git a/src/sage/schemes/affine/affine_subscheme.py b/src/sage/schemes/affine/affine_subscheme.py index 8baee490b88..6f4b3d786f3 100644 --- a/src/sage/schemes/affine/affine_subscheme.py +++ b/src/sage/schemes/affine/affine_subscheme.py @@ -374,7 +374,7 @@ def intersection_multiplicity(self, X, P): ....: -7*b^5 + 21*b^4 - 28*b^3 + 21*b^2 - 21*b + 14, ....: -b^5 + 2*b^4 - 3*b^3 + 2*b^2 - 2*b, ....: 0]) - sage: X.intersection_multiplicity(Y, Q) + sage: X.intersection_multiplicity(Y, Q) # needs sage.libs.singular 3 :: @@ -470,10 +470,10 @@ def multiplicity(self, P): sage: A. = AffineSpace(K, 5) sage: X = A.subscheme([y^7 - x^2*z^5 + z^3*t^8 - x^2*y^4*z - t^8]) sage: Q1 = A([1,1,0,1,-1]) - sage: X.multiplicity(Q1) + sage: X.multiplicity(Q1) # needs sage.libs.singular 1 sage: Q2 = A([0,0,0,-a,0]) - sage: X.multiplicity(Q2) + sage: X.multiplicity(Q2) # needs sage.libs.singular 7 Check that :trac:`27479` is fixed:: diff --git a/src/sage/schemes/curves/affine_curve.py b/src/sage/schemes/curves/affine_curve.py index 326c0d86e77..ce8c0ff0655 100644 --- a/src/sage/schemes/curves/affine_curve.py +++ b/src/sage/schemes/curves/affine_curve.py @@ -125,6 +125,8 @@ # https://www.gnu.org/licenses/ # **************************************************************************** +import sage.rings.abc + from sage.misc.lazy_attribute import lazy_attribute from sage.misc.cachefunc import cached_method @@ -139,10 +141,11 @@ from sage.matrix.constructor import matrix +from sage.misc.lazy_import import lazy_import + from sage.rings.polynomial.multi_polynomial_element import degree_lowest_rational_function from sage.rings.number_field.number_field import NumberField from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing -from sage.rings.qqbar import number_field_elements_from_algebraics, QQbar from sage.rings.rational_field import is_RationalField from sage.rings.infinity import infinity @@ -162,6 +165,8 @@ from .closed_point import IntegralAffineCurveClosedPoint +lazy_import('sage.rings.qqbar', 'number_field_elements_from_algebraics') + class AffineCurve(Curve_generic, AlgebraicScheme_subscheme_affine): """ @@ -671,7 +676,7 @@ def tangents(self, P, factor=True): T = sum([binomial(r, i)*deriv[i]*(vars[0])**i*(vars[1])**(r-i) for i in range(r+1)]) if not factor: return [T(coords)] - if self.base_ring() == QQbar: + if isinstance(self.base_ring(), sage.rings.abc.AlgebraicField): fact = [] # first add tangents corresponding to vars[0], vars[1] if they divide T t = min([e[0] for e in T.exponents()]) @@ -1534,6 +1539,7 @@ def resolution_of_singularities(self, extend=False): def extension(self): F = self.base_ring() + from sage.rings.qqbar import QQbar pts = self.change_ring(F.embeddings(QQbar)[0]).rational_points() L = [t for pt in pts for t in pt] K = number_field_elements_from_algebraics(L)[0] diff --git a/src/sage/schemes/elliptic_curves/descent_two_isogeny.pyx b/src/sage/schemes/elliptic_curves/descent_two_isogeny.pyx index 458ce65a61d..66d679a1241 100644 --- a/src/sage/schemes/elliptic_curves/descent_two_isogeny.pyx +++ b/src/sage/schemes/elliptic_curves/descent_two_isogeny.pyx @@ -38,7 +38,7 @@ from sage.libs.pari.convert_gmp cimport _new_GEN_from_mpz_t DEF N_RES_CLASSES_BSD = 10 -cdef unsigned long valuation(mpz_t a, mpz_t p): +cdef unsigned long valuation(mpz_t a, mpz_t p) noexcept: """ Return the number of times p divides a. """ @@ -85,7 +85,7 @@ def test_valuation(a, p): return valuation(A.value, P.value) -cdef int padic_square(mpz_t a, mpz_t p): +cdef int padic_square(mpz_t a, mpz_t p) noexcept: """ Test if a is a p-adic square. """ @@ -130,7 +130,7 @@ def test_padic_square(a, p): cdef int lemma6(mpz_t a, mpz_t b, mpz_t c, mpz_t d, mpz_t e, - mpz_t x, mpz_t p, unsigned long nu): + mpz_t x, mpz_t p, unsigned long nu) noexcept: """ Implements Lemma 6 of BSD's "Notes on elliptic curves, I" for odd p. @@ -180,7 +180,7 @@ cdef int lemma6(mpz_t a, mpz_t b, mpz_t c, mpz_t d, mpz_t e, cdef int lemma7(mpz_t a, mpz_t b, mpz_t c, mpz_t d, mpz_t e, - mpz_t x, mpz_t p, unsigned long nu): + mpz_t x, mpz_t p, unsigned long nu) noexcept: """ Implements Lemma 7 of BSD's "Notes on elliptic curves, I" for p=2. @@ -246,7 +246,7 @@ cdef int lemma7(mpz_t a, mpz_t b, mpz_t c, mpz_t d, mpz_t e, cdef int Zp_soluble_BSD(mpz_t a, mpz_t b, mpz_t c, mpz_t d, mpz_t e, - mpz_t x_k, mpz_t p, unsigned long k): + mpz_t x_k, mpz_t p, unsigned long k) noexcept: """ Uses the approach of BSD's "Notes on elliptic curves, I" to test for solubility of y^2 == ax^4 + bx^3 + cx^2 + dx + e over Zp, with @@ -283,7 +283,7 @@ cdef int Zp_soluble_BSD(mpz_t a, mpz_t b, mpz_t c, mpz_t d, mpz_t e, cdef bint Zp_soluble_siksek(mpz_t a, mpz_t b, mpz_t c, mpz_t d, mpz_t e, mpz_t pp, unsigned long pp_ui, nmod_poly_factor_t f_factzn, nmod_poly_t f, - fmpz_poly_t f1, fmpz_poly_t linear): + fmpz_poly_t f1, fmpz_poly_t linear) noexcept: """ Uses the approach of Algorithm 5.3.1 of Siksek's thesis to test for solubility of y^2 == ax^4 + bx^3 + cx^2 + dx + e over Zp. @@ -523,7 +523,7 @@ cdef bint Zp_soluble_siksek(mpz_t a, mpz_t b, mpz_t c, mpz_t d, mpz_t e, return result cdef bint Zp_soluble_siksek_large_p(mpz_t a, mpz_t b, mpz_t c, mpz_t d, mpz_t e, mpz_t pp, - fmpz_poly_t f1, fmpz_poly_t linear): + fmpz_poly_t f1, fmpz_poly_t linear) noexcept: """ Uses the approach of Algorithm 5.3.1 of Siksek's thesis to test for solubility of y^2 == ax^4 + bx^3 + cx^2 + dx + e over Zp. @@ -790,7 +790,7 @@ cdef bint Zp_soluble_siksek_large_p(mpz_t a, mpz_t b, mpz_t c, mpz_t d, mpz_t e, cdef bint Qp_soluble_siksek(mpz_t A, mpz_t B, mpz_t C, mpz_t D, mpz_t E, mpz_t p, unsigned long P, nmod_poly_factor_t f_factzn, fmpz_poly_t f1, - fmpz_poly_t linear): + fmpz_poly_t linear) noexcept: """ Uses Samir Siksek's thesis results to determine whether the quartic is locally soluble at p. @@ -829,7 +829,7 @@ cdef bint Qp_soluble_siksek(mpz_t A, mpz_t B, mpz_t C, mpz_t D, mpz_t E, cdef bint Qp_soluble_siksek_large_p(mpz_t A, mpz_t B, mpz_t C, mpz_t D, mpz_t E, - mpz_t p, fmpz_poly_t f1, fmpz_poly_t linear): + mpz_t p, fmpz_poly_t f1, fmpz_poly_t linear) noexcept: """ Uses Samir Siksek's thesis results to determine whether the quartic is locally soluble at p, when p is bigger than wordsize, and we can't use @@ -863,7 +863,7 @@ cdef bint Qp_soluble_siksek_large_p(mpz_t A, mpz_t B, mpz_t C, mpz_t D, mpz_t E, mpz_clear(e) return result -cdef bint Qp_soluble_BSD(mpz_t a, mpz_t b, mpz_t c, mpz_t d, mpz_t e, mpz_t p): +cdef bint Qp_soluble_BSD(mpz_t a, mpz_t b, mpz_t c, mpz_t d, mpz_t e, mpz_t p) noexcept: """ Uses the original test of Birch and Swinnerton-Dyer to test for local solubility of the quartic at p. @@ -880,7 +880,7 @@ cdef bint Qp_soluble_BSD(mpz_t a, mpz_t b, mpz_t c, mpz_t d, mpz_t e, mpz_t p): mpz_clear(zero) return result -cdef bint Qp_soluble(mpz_t a, mpz_t b, mpz_t c, mpz_t d, mpz_t e, mpz_t p): +cdef bint Qp_soluble(mpz_t a, mpz_t b, mpz_t c, mpz_t d, mpz_t e, mpz_t p) noexcept: """ Try the BSD approach for a few residue classes and if no solution is found, switch to Siksek to try to prove insolubility. diff --git a/src/sage/schemes/elliptic_curves/mod_sym_num.pyx b/src/sage/schemes/elliptic_curves/mod_sym_num.pyx index 296a6b5d075..33e509dca96 100644 --- a/src/sage/schemes/elliptic_curves/mod_sym_num.pyx +++ b/src/sage/schemes/elliptic_curves/mod_sym_num.pyx @@ -200,7 +200,7 @@ fa = sage.rings.fast_arith.arith_llong() cdef llong llgcd(llong a, llong b) except -1: return fa.gcd_longlong(a,b) -cdef llong llinvmod(llong a, llong m): +cdef llong llinvmod(llong a, llong m) noexcept: return fa.inverse_mod_longlong(a, m) DEF TWOPI = 6.28318530717958647 @@ -602,7 +602,7 @@ cdef class _CuspsForModularSymbolNumerical: # from sage.modular.cusps import Cusp # Cusp.__init__(self, a,m) - cdef public int is_unitary(self): + cdef public int is_unitary(self) noexcept: r""" Return whether the cusp is unitary, i.e. whether there exists an Atkin- @@ -1437,7 +1437,7 @@ cdef class ModularSymbolNumerical: # the version using double is 70-80 times faster it seems. cdef complex _integration_to_tau_double(self, complex tau, - int number_of_terms): + int number_of_terms) noexcept: r""" Given a point `\tau` in the upper half plane this returns a complex number that is a close @@ -2014,7 +2014,7 @@ cdef class ModularSymbolNumerical: Integer epsQ, Integer epsQQ, llong* wQ, llong* wQQ, int T, int prec, double eps, - int use_partials=2): + int use_partials=2) noexcept: r""" This is just a helper function for _from_r_to_rr_approx. In case the integral is evaluated directly this function is called. diff --git a/src/sage/schemes/elliptic_curves/period_lattice_region.pyx b/src/sage/schemes/elliptic_curves/period_lattice_region.pyx index b0914d6347a..06e6525f5c3 100644 --- a/src/sage/schemes/elliptic_curves/period_lattice_region.pyx +++ b/src/sage/schemes/elliptic_curves/period_lattice_region.pyx @@ -665,7 +665,7 @@ cdef class PeriodicRegion: return sum(L, F) -cdef frame_data(data, bint full=True): +cdef frame_data(data, bint full=True) noexcept: """ Helper function for PeriodicRegion.expand() and PeriodicRegion.border(). This makes "wrapping around" work @@ -695,7 +695,7 @@ cdef frame_data(data, bint full=True): framed[-1,:] = framed[-3,:] return framed -cdef unframe_data(framed, bint full=True): +cdef unframe_data(framed, bint full=True) noexcept: """ Helper function for PeriodicRegion.expand(). This glues the borders together using the "or" operator. diff --git a/src/sage/schemes/generic/algebraic_scheme.py b/src/sage/schemes/generic/algebraic_scheme.py index 5d071f2bd49..0648ad2a9f4 100644 --- a/src/sage/schemes/generic/algebraic_scheme.py +++ b/src/sage/schemes/generic/algebraic_scheme.py @@ -113,15 +113,14 @@ # https://www.gnu.org/licenses/ # **************************************************************************** +import sage.rings.abc from sage.categories.number_fields import NumberFields from sage.rings.ideal import is_Ideal from sage.rings.integer_ring import ZZ -from sage.rings.qqbar import QQbar from sage.rings.rational_field import is_RationalField from sage.rings.finite_rings.finite_field_base import FiniteField -from sage.rings.number_field.order import is_NumberFieldOrder from sage.misc.latex import latex from sage.misc.misc import is_iterator @@ -129,8 +128,6 @@ from sage.structure.all import Sequence from sage.structure.richcmp import richcmp, richcmp_method -from sage.calculus.functions import jacobian - from sage.arith.functions import lcm from sage.arith.misc import gcd @@ -278,9 +275,10 @@ def is_projective(self): projective spaces. This is why this method returns ``False`` for toric varieties:: - sage: PP. = toric_varieties.P(3) # needs sage.geometry.polyhedron + sage: # needs sage.geometry.polyhedron sage.graphs + sage: PP. = toric_varieties.P(3) sage: V = PP.subscheme(x^3 + y^3 + z^3 + w^3) - sage: V.is_projective() # needs sage.geometry.polyhedron + sage: V.is_projective() False """ return self.ambient_space().is_projective() @@ -386,9 +384,11 @@ def embedding_morphism(self): defined by: x^2 + y^2 - 1 To: Affine Space of dimension 2 over Rational Field Defn: Defined on coordinates by sending (x, y) to (x, y) - sage: P1xP1. = toric_varieties.P1xP1() # needs sage.geometry.polyhedron - sage: P1 = P1xP1.subscheme(x - y) # needs sage.geometry.polyhedron sage.libs.singular - sage: P1.embedding_morphism() # needs sage.geometry.polyhedron sage.libs.singular + + sage: # needs sage.graphs sage.geometry.polyhedron sage.libs.singular + sage: P1xP1. = toric_varieties.P1xP1() + sage: P1 = P1xP1.subscheme(x - y) + sage: P1.embedding_morphism() Scheme morphism: From: Closed subscheme of 2-d CPR-Fano toric variety covered by 4 affine patches defined by: x - y @@ -427,18 +427,18 @@ def embedding_morphism(self): A couple more examples:: - sage: # needs sage.geometry.polyhedron + sage: # needs sage.geometry.polyhedron sage.graphs sage.libs.singular sage: patch1 = P1xP1.affine_patch(1); patch1 2-d affine toric variety - sage: patch1.embedding_morphism() # needs sage.libs.singular + sage: patch1.embedding_morphism() Scheme morphism: From: 2-d affine toric variety To: 2-d CPR-Fano toric variety covered by 4 affine patches Defn: Defined on coordinates by sending [y : u] to [1 : y : u : 1] - sage: subpatch = P1.affine_patch(1); subpatch # needs sage.libs.singular + sage: subpatch = P1.affine_patch(1); subpatch Closed subscheme of 2-d affine toric variety defined by: -y + 1 - sage: subpatch.embedding_morphism() # needs sage.libs.singular + sage: subpatch.embedding_morphism() Scheme morphism: From: Closed subscheme of 2-d affine toric variety defined by: -y + 1 To: Closed subscheme of 2-d CPR-Fano toric variety covered @@ -543,7 +543,7 @@ def _homset(self, *args, **kwds): EXAMPLES:: - sage: # needs sage.geometry.polyhedron + sage: # needs sage.geometry.polyhedron sage.graphs sage: P1. = toric_varieties.P1() sage: type(P1.Hom(P1)) @@ -553,9 +553,10 @@ def _homset(self, *args, **kwds): :: - sage: P1xP1 = toric_varieties.P1xP1() # needs sage.geometry.polyhedron - sage: P1 = toric_varieties.P1() # needs sage.geometry.polyhedron - sage: P1xP1._homset(P1xP1, P1) # needs sage.geometry.polyhedron + sage: # needs sage.geometry.polyhedron sage.graphs + sage: P1xP1 = toric_varieties.P1xP1() + sage: P1 = toric_varieties.P1() + sage: P1xP1._homset(P1xP1, P1) Set of morphisms From: 2-d CPR-Fano toric variety covered by 4 affine patches To: 1-d CPR-Fano toric variety covered by 2 affine patches @@ -1121,7 +1122,9 @@ def normalize_defining_polynomials(self): """ BR = self.base_ring() - if BR == QQbar or BR in NumberFields() or is_NumberFieldOrder(BR): + if (BR == ZZ + or isinstance(BR, (sage.rings.abc.AlgebraicField, sage.rings.abc.Order)) + or BR in NumberFields()): normalized_polys = [] initial_polys = list(self.__polys) @@ -1279,7 +1282,7 @@ def is_irreducible(self): sage: K = QuadraticField(-3) sage: P. = ProjectiveSpace(K, 5) sage: X = P.subscheme([x*y - z^2 - K.0*t^2, t*w*x + y*z^2 - u^3]) - sage: X.is_irreducible() + sage: X.is_irreducible() # needs sage.libs.singular True :: @@ -1296,7 +1299,7 @@ def is_irreducible(self): ....: x*y*z^2 - x*y*z*w - z*w^2 + w^3, ....: x^3*y*z*w - x*y^3*z - x^2*y*z*w - x^2*w^3 + y^2*w^2 + x*w^3 ....: ]) - sage: X.is_irreducible() # needs sage.rings.finite_rings + sage: X.is_irreducible() # needs sage.libs.singular False """ return self.defining_ideal().is_prime() @@ -1330,6 +1333,9 @@ def Jacobian_matrix(self): l = self.defining_polynomials() if len(l) == 0: return sage.matrix.constructor.Matrix(R, 0) + + from sage.calculus.functions import jacobian + return jacobian(l, R.gens()) def Jacobian(self): @@ -1769,7 +1775,7 @@ def rational_points(self, **kwds): sage: K. = NumberField(u^2 + 3) sage: A. = ProjectiveSpace(K, 1) sage: X = A.subscheme(x^2 - y^2) - sage: X.rational_points(bound=3) + sage: X.rational_points(bound=3) # needs sage.libs.singular [(-1 : 1), (1 : 1)] One can enumerate points up to a given bound on a projective scheme diff --git a/src/sage/schemes/generic/homset.py b/src/sage/schemes/generic/homset.py index 5db57860f7d..60e840619ac 100644 --- a/src/sage/schemes/generic/homset.py +++ b/src/sage/schemes/generic/homset.py @@ -36,6 +36,7 @@ # ***************************************************************************** from sage.categories.homset import HomsetWithBase +from sage.misc.lazy_import import lazy_import from sage.structure.factory import UniqueFactory from sage.structure.parent import Set_generic @@ -49,6 +50,11 @@ SchemeMorphism_structure_map, SchemeMorphism_spec ) +lazy_import('sage.schemes.affine.affine_space', 'AffineSpace_generic', as_='AffineSpace') +lazy_import('sage.schemes.generic.algebraic_scheme', 'AlgebraicScheme_subscheme') +lazy_import('sage.schemes.product_projective.space', 'ProductProjectiveSpaces_ring', as_='ProductProjectiveSpaces') +lazy_import('sage.schemes.projective.projective_space', 'ProjectiveSpace_ring', as_='ProjectiveSpace') + def is_SchemeHomset(H): r""" @@ -568,9 +574,8 @@ def _coerce_map_from_(self, other): # and the base rings are coercible if isinstance(other, CommutativeRing): try: - from sage.schemes.affine.affine_space import is_AffineSpace - if is_AffineSpace(target.ambient_space())\ - and target.ambient_space().dimension_relative() == 1: + if (isinstance(target.ambient_space(), AffineSpace) + and target.ambient_space().dimension_relative() == 1): return target.base_ring().has_coerce_map_from(other) else: return False @@ -578,7 +583,6 @@ def _coerce_map_from_(self, other): return False elif isinstance(other, SchemeHomset_points): #we are converting between scheme points - from sage.schemes.generic.algebraic_scheme import AlgebraicScheme_subscheme source = other.codomain() if isinstance(target, AlgebraicScheme_subscheme): #subscheme coerce when there is containment @@ -592,9 +596,6 @@ def _coerce_map_from_(self, other): #if the target is an ambient space, we can coerce if the base rings coerce #and they are the same type: affine, projective, etc and have the same #variable names - from sage.schemes.projective.projective_space import is_ProjectiveSpace - from sage.schemes.affine.affine_space import is_AffineSpace - from sage.schemes.product_projective.space import is_ProductProjectiveSpaces try: ta = target.ambient_space() sa = source.ambient_space() @@ -602,15 +603,15 @@ def _coerce_map_from_(self, other): return False #for projective and affine varieties, we check dimension #and matching variable names - if (is_ProjectiveSpace(ta) and is_ProjectiveSpace(sa))\ - or (is_AffineSpace(ta) and is_AffineSpace(sa)): + if ((isinstance(ta, ProjectiveSpace) and isinstance(sa, ProjectiveSpace)) + or (isinstance(ta, AffineSpace) and isinstance(sa, AffineSpace))): if (ta.variable_names() == sa.variable_names()): return self.domain().coordinate_ring().has_coerce_map_from(other.domain().coordinate_ring()) else: return False #for products of projective spaces, we check dimension of #components and matching variable names - elif (is_ProductProjectiveSpaces(ta) and is_ProductProjectiveSpaces(sa)): + elif isinstance(ta, ProductProjectiveSpaces) and isinstance(sa, ProductProjectiveSpaces): if (ta.dimension_relative_components() == sa.dimension_relative_components()) \ and (ta.variable_names() == sa.variable_names()): return self.domain().coordinate_ring().has_coerce_map_from(other.domain().coordinate_ring()) @@ -737,11 +738,11 @@ def cardinality(self): EXAMPLES:: - sage: toric_varieties.P2().point_set().cardinality() # needs sage.geometry.polyhedron + sage: toric_varieties.P2().point_set().cardinality() # needs sage.geometry.polyhedron sage.graphs +Infinity - sage: P2 = toric_varieties.P2(base_ring=GF(3)) # needs sage.geometry.polyhedron - sage: P2.point_set().cardinality() # needs sage.geometry.polyhedron + sage: P2 = toric_varieties.P2(base_ring=GF(3)) # needs sage.geometry.polyhedron sage.graphs + sage: P2.point_set().cardinality() # needs sage.geometry.polyhedron sage.graphs 13 """ if hasattr(self, 'is_finite') and not self.is_finite(): @@ -761,8 +762,8 @@ def list(self): EXAMPLES:: - sage: P1 = toric_varieties.P1(base_ring=GF(3)) # needs sage.geometry.polyhedron - sage: P1.point_set().list() # needs sage.geometry.polyhedron + sage: P1 = toric_varieties.P1(base_ring=GF(3)) # needs sage.geometry.polyhedron sage.graphs + sage: P1.point_set().list() # needs sage.geometry.polyhedron sage.graphs ([0 : 1], [1 : 0], [1 : 1], [1 : 2]) """ return tuple(self) diff --git a/src/sage/schemes/generic/morphism.py b/src/sage/schemes/generic/morphism.py index f42e8f4a680..4405268fed6 100644 --- a/src/sage/schemes/generic/morphism.py +++ b/src/sage/schemes/generic/morphism.py @@ -513,7 +513,7 @@ def base_ring(self): :: - sage: # needs sage.rings.finite_rings + sage: # needs sage.rings.finite_rings sage.schemes sage: E = EllipticCurve(GF((17,2)), [1,2,3,4,5]) sage: P = E.random_point() sage: P.base_ring() @@ -1349,8 +1349,8 @@ def change_ring(self, R, check=True): sage: K2. = NumberField(t**4 - 2) sage: P. = ProjectiveSpace(QQ, 1) sage: phi = K.embeddings(K2)[0] - sage: f = DynamicalSystem_projective([x**2 + 3*y**2, y**2]) - sage: f.change_ring(phi) + sage: f = DynamicalSystem_projective([x**2 + 3*y**2, y**2]) # needs sage.schemes + sage: f.change_ring(phi) # needs sage.schemes Dynamical System of Projective Space of dimension 1 over Number Field in w with defining polynomial t^4 - 2 Defn: Defined on coordinates by sending (x : y) to (x^2 + 3*y^2 : y^2) @@ -1364,8 +1364,8 @@ def change_ring(self, R, check=True): sage: K2. = NumberField(t^8 - 2) sage: P. = ProjectiveSpace(K, 1) sage: phi = K1.embeddings(K2)[0] - sage: f = DynamicalSystem_projective([x^2 + 3*y^2, y^2]) - sage: f.change_ring(phi) + sage: f = DynamicalSystem_projective([x^2 + 3*y^2, y^2]) # needs sage.schemes + sage: f.change_ring(phi) # needs sage.schemes Traceback (most recent call last): ... ValueError: no canonical coercion of base ring of morphism to domain of embedding diff --git a/src/sage/schemes/generic/scheme.py b/src/sage/schemes/generic/scheme.py index fe55bca9117..da188ac63b3 100644 --- a/src/sage/schemes/generic/scheme.py +++ b/src/sage/schemes/generic/scheme.py @@ -684,7 +684,7 @@ def count_points(self, n): sage: P. = ProjectiveSpace(GF(4, 't'), 2) # needs sage.rings.finite_rings sage: X = P.subscheme([y^2*z - x^3 - z^3]) # needs sage.rings.finite_rings - sage: X.count_points(2) # needs sage.rings.finite_rings + sage: X.count_points(2) # needs sage.libs.singular sage.rings.finite_rings [5, 17] """ F = self.base_ring() diff --git a/src/sage/schemes/hyperelliptic_curves/hypellfrob.pyx b/src/sage/schemes/hyperelliptic_curves/hypellfrob.pyx index 50730d1081f..b4144780c1d 100644 --- a/src/sage/schemes/hyperelliptic_curves/hypellfrob.pyx +++ b/src/sage/schemes/hyperelliptic_curves/hypellfrob.pyx @@ -6,6 +6,7 @@ # distutils: extra_compile_args = NTL_CFLAGS # distutils: library_dirs = NTL_LIBDIR # distutils: extra_link_args = NTL_LIBEXTRA +# sage.doctest: needs sage.libs.ntl sage.modules sage.rings.padics r""" Frobenius on Monsky-Washnitzer cohomology of a hyperelliptic curve over a @@ -75,8 +76,8 @@ def interval_products(M0, M1, target): INPUT: - - M0, M1 -- matrices over `\ZZ/N\ZZ`, so that `M = M0 + M1*x` - - target -- a list of integers + - ``M0``, ``M1`` -- matrices over `\ZZ/N\ZZ`, so that `M = M0 + M1*x` + - ``target`` -- a list of integers ALGORITHM: @@ -173,10 +174,10 @@ def hypellfrob(p, N, Q): INPUT: - - p -- a prime - - Q -- a monic polynomial in `\ZZ[x]` of odd degree. - Must have no multiple roots mod p. - - N -- precision parameter; the output matrix will be correct modulo `p^N`. + - ``p`` -- a prime + - ``Q`` -- a monic polynomial in `\ZZ[x]` of odd degree. + Must have no multiple roots mod `p`. + - ``N`` -- precision parameter; the output matrix will be correct modulo `p^N`. PRECONDITIONS: diff --git a/src/sage/schemes/hyperelliptic_curves/monsky_washnitzer.py b/src/sage/schemes/hyperelliptic_curves/monsky_washnitzer.py index 321928f1464..f8c8f847350 100644 --- a/src/sage/schemes/hyperelliptic_curves/monsky_washnitzer.py +++ b/src/sage/schemes/hyperelliptic_curves/monsky_washnitzer.py @@ -84,7 +84,7 @@ class SpecialCubicQuotientRingElement(CommutativeAlgebraElement): """ - An element of a SpecialCubicQuotientRing. + An element of a :class:`SpecialCubicQuotientRing`. """ def __init__(self, parent, p0, p1, p2, check=True): """ @@ -93,7 +93,7 @@ def __init__(self, parent, p0, p1, p2, check=True): INPUT: - - ``parent`` -- a SpecialCubicQuotientRing + - ``parent`` -- a :class:`SpecialCubicQuotientRing` - ``p0, p1, p2`` -- coefficients; must be coercible into parent.poly_ring() @@ -306,7 +306,9 @@ def square(self): sage: f = R.create_element(1 + 2*t + 3*t^2, 4 + 7*t + 9*t^2, 3 + 5*t + 11*t^2) sage: f.square() - (73*T^5 + 16*T^4 + 38*T^3 + 39*T^2 + 70*T + 120) + (121*T^5 + 113*T^4 + 73*T^3 + 8*T^2 + 51*T + 61)*x + (18*T^4 + 60*T^3 + 22*T^2 + 108*T + 31)*x^2 + (73*T^5 + 16*T^4 + 38*T^3 + 39*T^2 + 70*T + 120) + + (121*T^5 + 113*T^4 + 73*T^3 + 8*T^2 + 51*T + 61)*x + + (18*T^4 + 60*T^3 + 22*T^2 + 108*T + 31)*x^2 """ return self * self @@ -323,7 +325,9 @@ def _mul_(self, other): sage: f = R.create_element(1 + 2*t + 3*t^2, 4 + 7*t + 9*t^2, 3 + 5*t + 11*t^2) sage: g = R.create_element(4 + 3*t + 7*t^2, 2 + 3*t + t^2, 8 + 4*t + 6*t^2) sage: f * g - (65*T^5 + 27*T^4 + 33*T^3 + 75*T^2 + 120*T + 57) + (66*T^5 + T^4 + 123*T^3 + 95*T^2 + 24*T + 50)*x + (45*T^4 + 75*T^3 + 37*T^2 + 2*T + 52)*x^2 + (65*T^5 + 27*T^4 + 33*T^3 + 75*T^2 + 120*T + 57) + + (66*T^5 + T^4 + 123*T^3 + 95*T^2 + 24*T + 50)*x + + (45*T^4 + 75*T^3 + 37*T^2 + 2*T + 52)*x^2 """ # Here we do Toom-Cook three-way multiplication, which reduces # the naive 9 polynomial multiplications to only 5 polynomial @@ -470,8 +474,8 @@ def __init__(self, Q, laurent_series=False): `Q(x) = x^3 + ax + b`, where `a`, `b` belong to a ring in which 2, 3 are invertible. - - ``laurent_series`` -- whether or not to allow - negative powers of `T` (default=False) + - ``laurent_series`` -- boolean (default: ``False``); whether or not to allow + negative powers of `T` EXAMPLES:: @@ -494,7 +498,8 @@ def __init__(self, Q, laurent_series=False): sage: R = monsky_washnitzer.SpecialCubicQuotientRing(t^3 - t + 1) Traceback (most recent call last): ... - ArithmeticError: 2 and 3 must be invertible in the coefficient ring (=Ring of integers modulo 10) of Q + ArithmeticError: 2 and 3 must be invertible in the coefficient ring + (=Ring of integers modulo 10) of Q """ if not isinstance(Q, Polynomial): raise TypeError("Q (=%s) must be a polynomial" % Q) @@ -679,11 +684,11 @@ def transpose_list(input): def helper_matrix(Q): - """ + r""" Compute the (constant) matrix used to calculate the linear combinations of the `d(x^i y^j)` needed to eliminate the - negative powers of `y` in the cohomology (i.e. in - reduce_negative()). + negative powers of `y` in the cohomology (i.e., in + :func:`reduce_negative`). INPUT: @@ -717,25 +722,25 @@ def helper_matrix(Q): def lift(x): r""" - Try to call x.lift(), presumably from the `p`-adics to ZZ. + Try to call ``x.lift()``, presumably from the `p`-adics to `\ZZ`. If this fails, it assumes the input is a power series, and tries to - lift it to a power series over QQ. + lift it to a power series over `\QQ`. This function is just a very kludgy solution to the problem of - trying to make the reduction code (below) work over both Zp and - Zp[[t]]. + trying to make the reduction code (below) work over both `\ZZ_p` and + `\ZZ_p[[t]]`. EXAMPLES:: + sage: # needs sage.rings.padics sage: from sage.schemes.hyperelliptic_curves.monsky_washnitzer import lift sage: l = lift(Qp(13)(131)); l 131 sage: l.parent() Integer Ring - - sage: x=PowerSeriesRing(Qp(17),'x').gen() - sage: l = lift(4+5*x+17*x**6); l + sage: x = PowerSeriesRing(Qp(17),'x').gen() + sage: l = lift(4 + 5*x + 17*x**6); l 4 + 5*t + 17*t^6 sage: l.parent() Power Series Ring in t over Rational Field @@ -758,7 +763,7 @@ def reduce_negative(Q, p, coeffs, offset, exact_form=None): - ``Q`` -- cubic polynomial - ``coeffs`` -- list of length 3 lists. The - `i^{th}` list [a, b, c] represents + `i`-th list ``[a, b, c]`` represents `y^{2(i - offset)} (a + bx + cx^2) dx/y`. - ``offset`` -- nonnegative integer @@ -861,7 +866,7 @@ def reduce_positive(Q, p, coeffs, offset, exact_form=None): - ``Q`` -- cubic polynomial - ``coeffs`` -- list of length 3 lists. The - `i^{th}` list [a, b, c] represents + `i`-th list [a, b, c] represents `y^{2(i - offset)} (a + bx + cx^2) dx/y`. - ``offset`` -- nonnegative integer @@ -955,7 +960,7 @@ def reduce_zero(Q, coeffs, offset, exact_form=None): - ``Q`` -- cubic polynomial - ``coeffs`` -- list of length 3 lists. The - `i^{th}` list [a, b, c] represents + `i`-th list [a, b, c] represents `y^{2(i - offset)} (a + bx + cx^2) dx/y`. - ``offset`` -- nonnegative integer @@ -1007,7 +1012,7 @@ def reduce_all(Q, p, coeffs, offset, compute_exact_form=False): - ``Q`` -- cubic polynomial - ``coeffs`` -- list of length 3 lists. The - `i^{th}` list [a, b, c] represents + `i`-th list [a, b, c] represents `y^{2(i - offset)} (a + bx + cx^2) dx/y`. - ``offset`` -- nonnegative integer @@ -1083,7 +1088,7 @@ def frobenius_expansion_by_newton(Q, p, M): coefficient ring of `Q`.) `F_0` and `F_1` are computed in the - SpecialCubicQuotientRing associated to `Q`, so all powers + :class:`SpecialCubicQuotientRing` associated to `Q`, so all powers of `x^j` for `j \geq 3` are reduced to powers of `T`. @@ -1101,7 +1106,7 @@ def frobenius_expansion_by_newton(Q, p, M): OUTPUT: - ``F0, F1`` -- elements of - SpecialCubicQuotientRing(Q), as described above + ``SpecialCubicQuotientRing(Q)``, as described above - ``r`` -- non-negative integer, as described above @@ -1256,7 +1261,7 @@ def frobenius_expansion_by_series(Q, p, M): and `R` is the coefficient ring of `Q`.) `F_0` and `F_1` are computed in the - SpecialCubicQuotientRing associated to `Q`, so all powers + :class:`SpecialCubicQuotientRing` associated to `Q`, so all powers of `x^j` for `j \geq 3` are reduced to powers of `T`. @@ -1289,7 +1294,7 @@ def frobenius_expansion_by_series(Q, p, M): OUTPUT: - ``F0, F1`` -- elements of - SpecialCubicQuotientRing(Q), as described above + ``SpecialCubicQuotientRing(Q)``, as described above - ``r`` -- non-negative integer, as described above @@ -1298,7 +1303,7 @@ def frobenius_expansion_by_series(Q, p, M): sage: from sage.schemes.hyperelliptic_curves.monsky_washnitzer import frobenius_expansion_by_series sage: R. = Integers(5^3)['x'] sage: Q = x^3 - x + R(1/4) - sage: frobenius_expansion_by_series(Q,5,3) + sage: frobenius_expansion_by_series(Q,5,3) # needs sage.libs.pari ((25*T^5 + 75*T^3 + 100*T^2 + 100*T + 100) + (5*T^6 + 80*T^5 + 100*T^3 + 25*T + 50)*x + (55*T^5 + 50*T^4 + 75*T^3 + 25*T^2 + 25*T + 25)*x^2, (5*T^8 + 15*T^7 + 95*T^6 + 10*T^5 + 25*T^4 + 25*T^3 + 100*T^2 + 50) @@ -1494,6 +1499,7 @@ def matrix_of_frobenius(Q, p, M, trace=None, compute_exact_forms=False): Here is an example that is particularly badly conditioned for using the trace trick:: + sage: # needs sage.libs.pari sage: p = 11 sage: prec = 3 sage: M = monsky_washnitzer.adjusted_prec(p, prec) @@ -1521,56 +1527,55 @@ def matrix_of_frobenius(Q, p, M, trace=None, compute_exact_forms=False): factors), so it is feasible to run on fairly large primes, or precision (or both?!?!):: + sage: # long time, needs sage.libs.pari sage: p = 10007 sage: prec = 2 sage: M = monsky_washnitzer.adjusted_prec(p, prec) sage: R. = PolynomialRing(Integers(p**M)) - sage: A = monsky_washnitzer.matrix_of_frobenius( # long time - ....: x^3 - x + R(1/4), p, M) - sage: B = A.change_ring(Integers(p**prec)); B # long time + sage: A = monsky_washnitzer.matrix_of_frobenius(x^3 - x + R(1/4), p, M) + sage: B = A.change_ring(Integers(p**prec)); B [74311982 57996908] [95877067 25828133] - sage: B.det() # long time + sage: B.det() 10007 - sage: B.trace() # long time + sage: B.trace() 66 - sage: EllipticCurve([-1, 1/4]).ap(10007) # long time + sage: EllipticCurve([-1, 1/4]).ap(10007) 66 :: + sage: # long time, needs sage.libs.pari sage: p = 5 sage: prec = 300 sage: M = monsky_washnitzer.adjusted_prec(p, prec) sage: R. = PolynomialRing(Integers(p**M)) - sage: A = monsky_washnitzer.matrix_of_frobenius( # long time - ....: x^3 - x + R(1/4), p, M) - sage: B = A.change_ring(Integers(p**prec)) # long time - sage: B.det() # long time + sage: A = monsky_washnitzer.matrix_of_frobenius(x^3 - x + R(1/4), p, M) + sage: B = A.change_ring(Integers(p**prec)) + sage: B.det() 5 - sage: -B.trace() # long time + sage: -B.trace() 2 - sage: EllipticCurve([-1, 1/4]).ap(5) # long time + sage: EllipticCurve([-1, 1/4]).ap(5) -2 Let us check consistency of the results for a range of precisions:: + sage: # long time, needs sage.libs.pari sage: p = 5 sage: max_prec = 60 sage: M = monsky_washnitzer.adjusted_prec(p, max_prec) sage: R. = PolynomialRing(Integers(p**M)) - sage: A = monsky_washnitzer.matrix_of_frobenius(x^3 - x + R(1/4), p, M) # long time - sage: A = A.change_ring(Integers(p**max_prec)) # long time - sage: result = [] # long time - sage: for prec in range(1, max_prec): # long time + sage: A = monsky_washnitzer.matrix_of_frobenius(x^3 - x + R(1/4), p, M) + sage: A = A.change_ring(Integers(p**max_prec)) + sage: result = [] + sage: for prec in range(1, max_prec): ....: M = monsky_washnitzer.adjusted_prec(p, prec) ....: R. = PolynomialRing(Integers(p^M),'x') - ....: B = monsky_washnitzer.matrix_of_frobenius( - ....: x^3 - x + R(1/4), p, M) + ....: B = monsky_washnitzer.matrix_of_frobenius(x^3 - x + R(1/4), p, M) ....: B = B.change_ring(Integers(p**prec)) - ....: result.append(B == A.change_ring( - ....: Integers(p**prec))) - sage: result == [True] * (max_prec - 1) # long time + ....: result.append(B == A.change_ring(Integers(p**prec))) + sage: result == [True] * (max_prec - 1) True The remaining examples discuss what happens when you take the @@ -1581,6 +1586,7 @@ def matrix_of_frobenius(Q, p, M, trace=None, compute_exact_forms=False): :: + sage: # needs sage.libs.pari sage: p = 11 sage: prec = 3 sage: M = monsky_washnitzer.adjusted_prec(p, prec) @@ -1589,9 +1595,9 @@ def matrix_of_frobenius(Q, p, M, trace=None, compute_exact_forms=False): sage: b = 8 - 6*t + 17*t^2 sage: R. = PolynomialRing(S) sage: Q = x**3 + a*x + b - sage: A = monsky_washnitzer.matrix_of_frobenius(Q, p, M) # long time - sage: B = A.change_ring(PowerSeriesRing(Integers(p**prec), 't', default_prec=4)) # long time - sage: B # long time + sage: A = monsky_washnitzer.matrix_of_frobenius(Q, p, M) # long time + sage: B = A.change_ring(PowerSeriesRing(Integers(p**prec), 't', # long time + ....: default_prec=4)); B [1144 + 264*t + 841*t^2 + 1025*t^3 + O(t^4) 176 + 1052*t + 216*t^2 + 523*t^3 + O(t^4)] [ 847 + 668*t + 81*t^2 + 424*t^3 + O(t^4) 185 + 341*t + 171*t^2 + 642*t^3 + O(t^4)] @@ -1786,6 +1792,7 @@ def matrix_of_frobenius_hyperelliptic(Q, p=None, prec=None, M=None): EXAMPLES:: + sage: # needs sage.rings.padics sage: p = 5 sage: prec = 3 sage: R. = QQ['x'] @@ -1854,10 +1861,10 @@ class SpecialHyperellipticQuotientElement(CommutativeAlgebraElement): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-36*x+1) + sage: E = HyperellipticCurve(x^5 - 36*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: MW = x.parent() - sage: MW(x+x**2+y-77) + sage: MW(x + x**2 + y - 77) -(77-y)*1 + x + x^2 """ def __init__(self, parent, val=0, offset=0, check=True): @@ -1867,10 +1874,10 @@ def __init__(self, parent, val=0, offset=0, check=True): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-36*x+1) + sage: E = HyperellipticCurve(x^5 - 36*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: MW = x.parent() - sage: elt = MW(x+x**2+y-77) + sage: elt = MW(x + x**2 + y - 77) sage: TestSuite(elt).run() """ CommutativeAlgebraElement.__init__(self, parent) @@ -1896,7 +1903,7 @@ def _richcmp_(self, other, op): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-36*x+1) + sage: E = HyperellipticCurve(x^5 - 36*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x == x True @@ -1912,12 +1919,13 @@ def change_ring(self, R): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-36*x+1) + sage: E = HyperellipticCurve(x^5 - 36*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: MW = x.parent() - sage: z = MW(x+x**2+y-77) - sage: z.change_ring(AA).parent() - SpecialHyperellipticQuotientRing K[x,y,y^-1] / (y^2 = x^5 - 36*x + 1) over Algebraic Real Field + sage: z = MW(x + x**2 + y - 77) + sage: z.change_ring(AA).parent() # needs sage.rings.number_field + SpecialHyperellipticQuotientRing K[x,y,y^-1] / (y^2 = x^5 - 36*x + 1) + over Algebraic Real Field """ return self.parent().change_ring(R)(self) @@ -1928,10 +1936,10 @@ def __call__(self, *x): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-36*x+1) + sage: E = HyperellipticCurve(x^5 - 36*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: MW = x.parent() - sage: z = MW(x+x**2+y-77); z + sage: z = MW(x + x**2 + y - 77); z -(77-y)*1 + x + x^2 sage: z(66) 4345 + y @@ -1950,14 +1958,15 @@ def __invert__(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-36*x+1) + sage: E = HyperellipticCurve(x^5 - 36*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: MW = x.parent() - sage: z = y**(-1) # indirect doctest + sage: z = y**(-1) # indirect doctest sage: z.parent() - SpecialHyperellipticQuotientRing K[x,y,y^-1] / (y^2 = x^5 - 36*x + 1) over Rational Field + SpecialHyperellipticQuotientRing K[x,y,y^-1] / (y^2 = x^5 - 36*x + 1) + over Rational Field - sage: z = (x+y)**(-1) # indirect doctest + sage: z = (x+y)**(-1) # indirect doctest Traceback (most recent call last): ... ZeroDivisionError: element not invertible @@ -1975,7 +1984,7 @@ def __bool__(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: bool(x) True @@ -1989,7 +1998,7 @@ def __eq__(self, other): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x == y # indirect doctest False @@ -2005,9 +2014,9 @@ def _add_(self, other): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-36*x+1) + sage: E = HyperellipticCurve(x^5 - 36*x + 1) sage: x,y = E.monsky_washnitzer_gens() - sage: x+y + sage: x + y y*1 + x """ P = self.parent() @@ -2020,9 +2029,9 @@ def _sub_(self, other): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-36*x+1) + sage: E = HyperellipticCurve(x^5 - 36*x + 1) sage: x,y = E.monsky_washnitzer_gens() - sage: y-x + sage: y - x y*1 - x """ P = self.parent() @@ -2035,7 +2044,7 @@ def _mul_(self, other): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-36*x+1) + sage: E = HyperellipticCurve(x^5 - 36*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: y*x y*x @@ -2066,9 +2075,9 @@ def _rmul_(self, c): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() - sage: x._rmul_(y) + sage: x._rmul_(y) # needs sage.rings.real_interval_field y*1*x """ P = self.parent() @@ -2088,7 +2097,7 @@ def _lmul_(self, c): sage: R. = QQ['x'] sage: E = HyperellipticCurve(x^5-3*x+1) sage: x,y = E.monsky_washnitzer_gens() - sage: x._lmul_(y) + sage: x._lmul_(y) # needs sage.rings.real_interval_field y*1*x """ P = self.parent() @@ -2106,7 +2115,7 @@ def __lshift__(self, k): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x.__lshift__(3) y^3*x @@ -2122,7 +2131,7 @@ def __rshift__(self, k): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: y.__rshift__(3) (y^-2)*1 @@ -2138,9 +2147,9 @@ def truncate_neg(self, n): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() - sage: (x+3*y+7*x*2*y**4).truncate_neg(1) + sage: (x + 3*y + 7*x*2*y**4).truncate_neg(1) 3*y*1 + 14*y^4*x """ coeffs = self._f.list(copy=False) @@ -2154,9 +2163,9 @@ def _repr_(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() - sage: (x+3*y)._repr_() + sage: (x + 3*y)._repr_() '3*y*1 + x' """ x = PolynomialRing(QQ, 'x').gen(0) @@ -2170,9 +2179,9 @@ def _latex_(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() - sage: (x+3*y)._latex_() + sage: (x + 3*y)._latex_() '3y 1 + x' """ x = PolynomialRing(QQ, 'x').gen(0) @@ -2186,9 +2195,9 @@ def diff(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() - sage: (x+3*y).diff() + sage: (x + 3*y).diff() (-(9-2*y)*1 + 15*x^4) dx/2y """ # try: @@ -2216,9 +2225,9 @@ def extract_pow_y(self, k): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() - sage: (x+3*y+9*x*y).extract_pow_y(1) + sage: (x + 3*y + 9*x*y).extract_pow_y(1) [3, 9, 0, 0, 0] """ v = [a[k] for a in self._f.list()] @@ -2232,9 +2241,9 @@ def min_pow_y(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() - sage: (x+3*y).min_pow_y() + sage: (x + 3*y).min_pow_y() 0 """ if self._f.degree() == -1: @@ -2248,9 +2257,9 @@ def max_pow_y(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() - sage: (x+3*y).max_pow_y() + sage: (x + 3*y).max_pow_y() 1 """ if self._f.degree() == -1: @@ -2276,7 +2285,7 @@ def coeffs(self, R=None): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x.coeffs() ([(0, 1, 0, 0, 0)], 0) @@ -2287,7 +2296,7 @@ def coeffs(self, R=None): x + 2*x^2 + 3*x^3 + 4*x^4 sage: a.coeffs() ([(0, 1, 2, 3, 4)], 0) - sage: a.coeffs(Qp(7)) + sage: a.coeffs(Qp(7)) # needs sage.rings.padics ([(0, 1 + O(7^20), 2 + O(7^20), 3 + O(7^20), 4 + O(7^20))], 0) sage: (a*y).coeffs() ([(0, 0, 0, 0, 0), (0, 1, 2, 3, 4)], 0) @@ -2304,7 +2313,8 @@ def coeffs(self, R=None): sage: a = x^20*y^-3 - x^11*y^2; a (y^-3-4*y^-1+6*y-4*y^3+y^5)*1 - (12*y^-3-36*y^-1+36*y+y^2-12*y^3-2*y^4+y^6)*x - + (54*y^-3-108*y^-1+54*y+6*y^2-6*y^4)*x^2 - (108*y^-3-108*y^-1+9*y^2)*x^3 + (81*y^-3)*x^4 + + (54*y^-3-108*y^-1+54*y+6*y^2-6*y^4)*x^2 - (108*y^-3-108*y^-1+9*y^2)*x^3 + + (81*y^-3)*x^4 sage: raw, offset = a.coeffs() sage: a.min_pow_y() -3 @@ -2321,7 +2331,8 @@ def coeffs(self, R=None): (0, 2, -6, 0, 0), (1, 0, 0, 0, 0), (0, -1, 0, 0, 0)] - sage: sum(c * x^i * y^(j+offset) for j, L in enumerate(raw) for i, c in enumerate(L)) == a + sage: sum(c * x^i * y^(j+offset) + ....: for j, L in enumerate(raw) for i, c in enumerate(L)) == a True Can also be used to construct elements:: @@ -2360,10 +2371,10 @@ def __init__(self, Q, R=None, invert_y=True): TESTS:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: from sage.schemes.hyperelliptic_curves.monsky_washnitzer import SpecialHyperellipticQuotientRing sage: HQR = SpecialHyperellipticQuotientRing(E) - sage: TestSuite(HQR).run() + sage: TestSuite(HQR).run() # needs sage.rings.real_interval_field Check that caching works:: @@ -2441,7 +2452,7 @@ def _repr_(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x.parent() # indirect doctest SpecialHyperellipticQuotientRing K[x,y,y^-1] / (y^2 = x^5 - 3*x + 1) over Rational Field @@ -2456,10 +2467,11 @@ def base_extend(self, R): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() - sage: x.parent().base_extend(UniversalCyclotomicField()) - SpecialHyperellipticQuotientRing K[x,y,y^-1] / (y^2 = x^5 - 3*x + 1) over Universal Cyclotomic Field + sage: x.parent().base_extend(UniversalCyclotomicField()) # needs sage.libs.gap + SpecialHyperellipticQuotientRing K[x,y,y^-1] / (y^2 = x^5 - 3*x + 1) + over Universal Cyclotomic Field sage: x.parent().base_extend(ZZ) Traceback (most recent call last): ... @@ -2476,10 +2488,11 @@ def change_ring(self, R): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x.parent().change_ring(ZZ) - SpecialHyperellipticQuotientRing K[x,y,y^-1] / (y^2 = x^5 - 3*x + 1) over Integer Ring + SpecialHyperellipticQuotientRing K[x,y,y^-1] / (y^2 = x^5 - 3*x + 1) + over Integer Ring """ return SpecialHyperellipticQuotientRing(self._Q.change_ring(R), R, is_LaurentSeriesRing(self._series_ring)) @@ -2491,7 +2504,7 @@ def _element_constructor_(self, val, offset=0, check=True): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x.parent()(x^6) -(1-y^2)*x + 3*x^2 @@ -2513,7 +2526,7 @@ def one(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x.parent().one() 1 @@ -2528,7 +2541,7 @@ def zero(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x.parent().zero() 0 @@ -2542,7 +2555,7 @@ def gens(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x.parent().gens() (x, y*1) @@ -2556,7 +2569,7 @@ def x(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x.parent().x() x @@ -2570,7 +2583,7 @@ def y(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x.parent().y() y*1 @@ -2584,7 +2597,7 @@ def monomial(self, i, j, b=None): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x.parent().monomial(4,5) y^5*x^4 @@ -2623,7 +2636,7 @@ def monomial_diff_coeffs(self, i, j): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x.parent().monomial_diff_coeffs(2,3) ((0, -15, 36, 0, 0), (0, 19, 0, 0, 0)) @@ -2656,7 +2669,7 @@ def monomial_diff_coeffs_matrices(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x.parent().monomial_diff_coeffs_matrices() ( @@ -2684,7 +2697,7 @@ def _precompute_monomial_diffs(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x.parent()._precompute_monomial_diffs() [((-3, 0, 0, 0, 5), (0, 0, 0, 0, 0), (0, 0, 0, 0, 0)), @@ -2725,7 +2738,7 @@ def curve(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x.parent().curve() Hyperelliptic Curve over Rational Field defined by y^2 = x^5 - 3*x + 1 @@ -2739,7 +2752,7 @@ def degree(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x.parent().degree() 5 @@ -2753,7 +2766,7 @@ def prime(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x.parent().prime() is None True @@ -2767,7 +2780,7 @@ def monsky_washnitzer(self): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: type(x.parent().monsky_washnitzer()) @@ -2781,7 +2794,7 @@ def is_field(self, proof=True): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = E.monsky_washnitzer_gens() sage: x.parent().is_field() False @@ -2846,7 +2859,7 @@ def _add_(self, other): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x + 4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: x,y = C.monsky_washnitzer_gens() sage: w = C.invariant_differential() sage: w + w @@ -2867,7 +2880,7 @@ def _sub_(self, other): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: x,y = C.monsky_washnitzer_gens() sage: w = C.invariant_differential() sage: w-w @@ -2887,7 +2900,7 @@ def __neg__(self): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: x,y = C.monsky_washnitzer_gens() sage: w = C.invariant_differential() sage: -w @@ -2905,7 +2918,7 @@ def _lmul_(self, a): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: x,y = C.monsky_washnitzer_gens() sage: w = C.invariant_differential() sage: w*x @@ -2927,7 +2940,7 @@ def _rmul_(self, a): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: x,y = C.monsky_washnitzer_gens() sage: w = C.invariant_differential() sage: x*w @@ -2949,7 +2962,7 @@ def coeff(self): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: x,y = C.monsky_washnitzer_gens() sage: w = C.invariant_differential() sage: w @@ -2966,7 +2979,7 @@ def __bool__(self): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: x,y = C.monsky_washnitzer_gens() sage: w = C.invariant_differential() sage: not w @@ -2983,7 +2996,7 @@ def _repr_(self): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: x,y = C.monsky_washnitzer_gens() sage: w = C.invariant_differential() sage: w @@ -3003,7 +3016,7 @@ def _latex_(self): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: x,y = C.monsky_washnitzer_gens() sage: w = C.invariant_differential() sage: latex(w) @@ -3030,7 +3043,7 @@ def _richcmp_(self, other, op): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-3*x+1) + sage: C = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = C.monsky_washnitzer_gens() sage: (y^-1).diff() == (y^-1).diff() True @@ -3053,7 +3066,7 @@ def extract_pow_y(self, k): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-3*x+1) + sage: C = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = C.monsky_washnitzer_gens() sage: A = y^5 - x*y^3 sage: A.extract_pow_y(5) @@ -3070,7 +3083,7 @@ def min_pow_y(self): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-3*x+1) + sage: C = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = C.monsky_washnitzer_gens() sage: w = y^5 * C.invariant_differential() sage: w.min_pow_y() @@ -3088,7 +3101,7 @@ def max_pow_y(self): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-3*x+1) + sage: C = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = C.monsky_washnitzer_gens() sage: w = y^5 * C.invariant_differential() sage: w.max_pow_y() @@ -3106,7 +3119,7 @@ def reduce_neg_y(self): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-3*x+1) + sage: C = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = C.monsky_washnitzer_gens() sage: (y^-1).diff().reduce_neg_y() ((y^-1)*1, 0 dx/2y) @@ -3142,7 +3155,7 @@ def reduce_neg_y_fast(self, even_degree_only=False): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: x, y = E.monsky_washnitzer_gens() sage: (y^-1).diff().reduce_neg_y_fast() ((y^-1)*1, 0 dx/2y) @@ -3206,7 +3219,7 @@ def reduce_neg_y_faster(self, even_degree_only=False): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-3*x+1) + sage: C = HyperellipticCurve(x^5 - 3*x + 1) sage: x,y = C.monsky_washnitzer_gens() sage: (y^-1).diff().reduce_neg_y() ((y^-1)*1, 0 dx/2y) @@ -3301,7 +3314,7 @@ def reduce_pos_y_fast(self, even_degree_only=False): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^3-4*x+4) + sage: E = HyperellipticCurve(x^3 - 4*x + 4) sage: x, y = E.monsky_washnitzer_gens() sage: y.diff().reduce_pos_y_fast() (y*1, 0 dx/2y) @@ -3370,7 +3383,7 @@ def reduce(self): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: x,y = C.monsky_washnitzer_gens() sage: w = (y*x).diff() sage: w.reduce() @@ -3380,7 +3393,8 @@ def reduce(self): sage: w.reduce() (1/5*y*1, 4/5*1 dx/2y) - sage: w = sum(QQ.random_element() * x^i * y^j for i in [0..4] for j in [-3..3]) * C.invariant_differential() + sage: w = sum(QQ.random_element() * x^i * y^j + ....: for i in [0..4] for j in [-3..3]) * C.invariant_differential() sage: f, a = w.reduce() sage: f.diff() + a - w 0 dx/2y @@ -3409,7 +3423,7 @@ def reduce_fast(self, even_degree_only=False): EXAMPLES:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^3-4*x+4) + sage: E = HyperellipticCurve(x^3 - 4*x + 4) sage: x, y = E.monsky_washnitzer_gens() sage: x.diff().reduce_fast() (x, (0, 0)) @@ -3447,7 +3461,7 @@ def coeffs(self, R=None): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: x,y = C.monsky_washnitzer_gens() sage: w = C.invariant_differential() sage: w.coeffs() @@ -3506,11 +3520,11 @@ def __init__(self, base_ring): TESTS:: sage: R. = QQ['x'] - sage: E = HyperellipticCurve(x^5-3*x+1) + sage: E = HyperellipticCurve(x^5 - 3*x + 1) sage: from sage.schemes.hyperelliptic_curves.monsky_washnitzer import SpecialHyperellipticQuotientRing, MonskyWashnitzerDifferentialRing sage: S = SpecialHyperellipticQuotientRing(E) sage: DR = MonskyWashnitzerDifferentialRing(S) - sage: TestSuite(DR).run() + sage: TestSuite(DR).run() # needs sage.rings.real_interval_field Check that caching works:: @@ -3526,7 +3540,7 @@ def invariant_differential(self): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: MW = C.invariant_differential().parent() sage: MW.invariant_differential() 1 dx/2y @@ -3548,12 +3562,14 @@ def base_extend(self, R): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: MW = C.invariant_differential().parent() sage: MW.base_ring() - SpecialHyperellipticQuotientRing K[x,y,y^-1] / (y^2 = x^5 - 4*x + 4) over Rational Field - sage: MW.base_extend(Qp(5,5)).base_ring() - SpecialHyperellipticQuotientRing K[x,y,y^-1] / (y^2 = (1 + O(5^5))*x^5 + (1 + 4*5 + 4*5^2 + 4*5^3 + 4*5^4 + O(5^5))*x + 4 + O(5^5)) + SpecialHyperellipticQuotientRing K[x,y,y^-1] / (y^2 = x^5 - 4*x + 4) + over Rational Field + sage: MW.base_extend(Qp(5,5)).base_ring() # needs sage.rings.padics + SpecialHyperellipticQuotientRing K[x,y,y^-1] / (y^2 = (1 + O(5^5))*x^5 + + (1 + 4*5 + 4*5^2 + 4*5^3 + 4*5^4 + O(5^5))*x + 4 + O(5^5)) over 5-adic Field with capped relative precision 5 """ return MonskyWashnitzerDifferentialRing(self.base_ring().base_extend(R)) @@ -3574,12 +3590,14 @@ def change_ring(self, R): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: MW = C.invariant_differential().parent() sage: MW.base_ring() - SpecialHyperellipticQuotientRing K[x,y,y^-1] / (y^2 = x^5 - 4*x + 4) over Rational Field - sage: MW.change_ring(Qp(5,5)).base_ring() - SpecialHyperellipticQuotientRing K[x,y,y^-1] / (y^2 = (1 + O(5^5))*x^5 + (1 + 4*5 + 4*5^2 + 4*5^3 + 4*5^4 + O(5^5))*x + 4 + O(5^5)) + SpecialHyperellipticQuotientRing K[x,y,y^-1] / (y^2 = x^5 - 4*x + 4) + over Rational Field + sage: MW.change_ring(Qp(5,5)).base_ring() # needs sage.rings.padics + SpecialHyperellipticQuotientRing K[x,y,y^-1] / (y^2 = (1 + O(5^5))*x^5 + + (1 + 4*5 + 4*5^2 + 4*5^3 + 4*5^4 + O(5^5))*x + 4 + O(5^5)) over 5-adic Field with capped relative precision 5 """ return MonskyWashnitzerDifferentialRing(self.base_ring().change_ring(R)) @@ -3592,7 +3610,7 @@ def degree(self): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: MW = C.invariant_differential().parent() sage: MW.Q() x^5 - 4*x + 4 @@ -3607,8 +3625,9 @@ def dimension(self): EXAMPLES:: + sage: # needs sage.rings.padics sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: K = Qp(7,5) sage: CK = C.change_ring(K) sage: MW = CK.invariant_differential().parent() @@ -3625,7 +3644,7 @@ def Q(self): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: MW = C.invariant_differential().parent() sage: MW.Q() x^5 - 4*x + 4 @@ -3641,7 +3660,7 @@ def x_to_p(self, p): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: MW = C.invariant_differential().parent() sage: MW.x_to_p(3) x^3 @@ -3661,11 +3680,11 @@ def frob_Q(self, p): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: MW = C.invariant_differential().parent() sage: MW.frob_Q(3) -(60-48*y^2+12*y^4-y^6)*1 + (192-96*y^2+12*y^4)*x - (192-48*y^2)*x^2 + 60*x^3 - sage: MW.Q()(MW.x_to_p(3)) + sage: MW.Q()(MW.x_to_p(3)) # needs sage.rings.real_interval_field -(60-48*y^2+12*y^4-y^6)*1 + (192-96*y^2+12*y^4)*x - (192-48*y^2)*x^2 + 60*x^3 sage: MW.frob_Q(11) is MW.frob_Q(11) True @@ -3696,11 +3715,11 @@ def frob_invariant_differential(self, prec, p): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: prec = 2 sage: p = 7 sage: MW = C.invariant_differential().parent() - sage: MW.frob_invariant_differential(prec,p) + sage: MW.frob_invariant_differential(prec, p) ((67894400*y^-20-81198880*y^-18+40140800*y^-16-10035200*y^-14+1254400*y^-12-62720*y^-10)*1 - (119503944*y^-20-116064242*y^-18+43753472*y^-16-7426048*y^-14+514304*y^-12-12544*y^-10+1568*y^-8-70*y^-6-7*y^-4)*x + (78905288*y^-20-61014016*y^-18+16859136*y^-16-2207744*y^-14+250880*y^-12-37632*y^-10+3136*y^-8-70*y^-6)*x^2 @@ -3766,11 +3785,11 @@ def frob_basis_elements(self, prec, p): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: prec = 1 sage: p = 5 sage: MW = C.invariant_differential().parent() - sage: MW.frob_basis_elements(prec,p) + sage: MW.frob_basis_elements(prec, p) [((92000*y^-14-74200*y^-12+32000*y^-10-8000*y^-8+1000*y^-6-50*y^-4)*1 - (194400*y^-14-153600*y^-12+57600*y^-10-9600*y^-8+600*y^-6)*x + (204800*y^-14-153600*y^-12+38400*y^-10-3200*y^-8)*x^2 @@ -3808,7 +3827,7 @@ def helper_matrix(self): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: MW = C.invariant_differential().parent() sage: MW.helper_matrix() [ 256/2101 320/2101 400/2101 500/2101 625/2101] @@ -3850,7 +3869,7 @@ def _element_constructor_(self, val=0, offset=0): EXAMPLES:: sage: R. = QQ['x'] - sage: C = HyperellipticCurve(x^5-4*x+4) + sage: C = HyperellipticCurve(x^5 - 4*x + 4) sage: MW = C.invariant_differential().parent() sage: MW(3) 3*1 dx/2y diff --git a/src/sage/schemes/plane_conics/con_field.py b/src/sage/schemes/plane_conics/con_field.py index 9794790e1ae..97bd54408ac 100644 --- a/src/sage/schemes/plane_conics/con_field.py +++ b/src/sage/schemes/plane_conics/con_field.py @@ -103,7 +103,7 @@ def base_extend(self, S): sage: c = Conic([1, 1, 1]); c Projective Conic Curve over Rational Field defined by x^2 + y^2 + z^2 - sage: c.has_rational_point() + sage: c.has_rational_point() # needs sage.libs.pari False sage: d = c.base_extend(QuadraticField(-1, 'i')); d # needs sage.rings.number_field Projective Conic Curve over Number Field in i @@ -142,7 +142,9 @@ def cache_point(self, p): (15/8 : 17/8 : 1) sage: c.rational_point() (15/8 : 17/8 : 1) - sage: c.cache_point(c.rational_point(read_cache = False)) + + sage: # needs sage.libs.pari + sage: c.cache_point(c.rational_point(read_cache=False)) sage: c.rational_point() (-1 : 1 : 0) """ @@ -270,10 +272,11 @@ def diagonal_matrix(self): :: - sage: c = Conic(GF(4, 'a'), [0, 1, 1, 1, 1, 1]) # needs sage.rings.finite_rings - sage: c.is_smooth() # needs sage.rings.finite_rings + sage: # needs sage.rings.finite_rings + sage: c = Conic(GF(4, 'a'), [0, 1, 1, 1, 1, 1]) + sage: c.is_smooth() True - sage: c.diagonal_matrix() # needs sage.rings.finite_rings + sage: c.diagonal_matrix() Traceback (most recent call last): ... ValueError: The conic self (= Projective Conic Curve over Finite Field @@ -385,17 +388,16 @@ def gens(self): sage: P. = QQ[] sage: c = Conic(x^2 + y^2 + z^2) - sage: c.gens() + sage: c.gens() # needs sage.libs.singular (xbar, ybar, zbar) - sage: c.defining_polynomial()(c.gens()) + sage: c.defining_polynomial()(c.gens()) # needs sage.libs.singular 0 The function ``gens()`` is required for the following construction: :: - sage: C. = Conic(GF(3), [1, 1, 1]) - sage: C + sage: C. = Conic(GF(3), [1, 1, 1]); C # needs sage.libs.singular Projective Conic Curve over Finite Field of size 3 defined by a^2 + b^2 + c^2 @@ -439,8 +441,8 @@ def has_rational_point(self, point=False, Conics over polynomial rings can be solved internally:: sage: R. = QQ[] - sage: C = Conic([-2,t^2+1,t^2-1]) - sage: C.has_rational_point() + sage: C = Conic([-2, t^2 + 1, t^2 - 1]) + sage: C.has_rational_point() # needs sage.libs.pari True And they can also be solved with Magma:: @@ -450,7 +452,7 @@ def has_rational_point(self, point=False, sage: C.has_rational_point(algorithm='magma', point=True) # optional - magma (True, (-t : 1 : 1)) - sage: D = Conic([t,1,t^2]) + sage: D = Conic([t, 1, t^2]) sage: D.has_rational_point(algorithm='magma') # optional - magma False @@ -603,10 +605,10 @@ def has_singular_point(self, point=False): (True, (a + 1 : 0 : 1)) sage: P. = GF(2)[] - sage: C = Conic(P, [t,t,1]); C # needs sage.libs.ntl + sage: C = Conic(P, [t,t,1]); C Projective Conic Curve over Fraction Field of Univariate Polynomial Ring - in t over Finite Field of size 2 (using GF2X) defined by t*x^2 + t*y^2 + z^2 - sage: C.has_singular_point(point=False) # needs sage.libs.ntl + in t over Finite Field of size 2... defined by t*x^2 + t*y^2 + z^2 + sage: C.has_singular_point(point=False) Traceback (most recent call last): ... NotImplementedError: Sorry, find singular point on conics not implemented @@ -656,7 +658,7 @@ def hom(self, x, Y=None): From: Projective Conic Curve over Rational Field defined by -x^2 + y^2 + z^2 To: Projective Conic Curve over Rational Field defined by -x^2 + 2*x*y + z^2 Defn: Defined on coordinates by sending (x : y : z) to (x + y : y : z) - sage: h([-1, 1, 0]) + sage: h([-1, 1, 0]) # needs sage.libs.singular (0 : 1 : 0) sage: c = Conic([-1, 1, 1]) @@ -667,7 +669,7 @@ def hom(self, x, Y=None): To: Projective Conic Curve over Rational Field defined by 4*x^2 + y^2 - z^2 Defn: Defined on coordinates by sending (x : y : z) to (1/2*z : y : x) - ``ValueError`` is raised if the wrong codomain ``Y`` is specified: + :class:`ValueError` is raised if the wrong codomain ``Y`` is specified: :: @@ -853,6 +855,7 @@ def parametrization(self, point=None, morphism=True): An example over a finite field :: + sage: # needs sage.libs.pari sage: c = Conic(GF(2), [1,1,1,1,1,0]) sage: f, g = c.parametrization(); f, g (Scheme morphism: @@ -870,7 +873,7 @@ def parametrization(self, point=None, morphism=True): Verfication of the example :: - sage: # needs sage.rings.finite_rings + sage: # needs sage.libs.pari sage: h = g*f; h Scheme endomorphism of Projective Space of dimension 1 over Finite Field of size 2 @@ -892,7 +895,7 @@ def parametrization(self, point=None, morphism=True): The morphisms are mathematically defined in all points, but don't work completely in SageMath (see :trac:`31892`) :: - sage: # needs sage.rings.finite_rings + sage: # needs sage.libs.pari sage: f, g = c.parametrization([0,0,1]) sage: g([0,1,1]) (1 : 0) @@ -905,6 +908,7 @@ def parametrization(self, point=None, morphism=True): An example with ``morphism = False`` :: + sage: # needs sage.libs.pari sage: R. = QQ[] sage: C = Curve(7*x^2 + 2*y*z + z^2) sage: (p, i) = C.parametrization(morphism=False); (p, i) @@ -914,8 +918,9 @@ def parametrization(self, point=None, morphism=True): sage: i[0](p) / i[1](p) x/y - A ``ValueError`` is raised if ``self`` has no rational point :: + A :class:`ValueError` is raised if ``self`` has no rational point :: + sage: # needs sage.libs.pari sage: C = Conic(x^2 + y^2 + 7*z^2) sage: C.parametrization() Traceback (most recent call last): @@ -923,8 +928,9 @@ def parametrization(self, point=None, morphism=True): ValueError: Conic Projective Conic Curve over Rational Field defined by x^2 + y^2 + 7*z^2 has no rational points over Rational Field! - A ``ValueError`` is raised if ``self`` is not smooth :: + A :class:`ValueError` is raised if ``self`` is not smooth :: + sage: # needs sage.libs.pari sage: C = Conic(x^2 + y^2) sage: C.parametrization() Traceback (most recent call last): @@ -983,7 +989,7 @@ def point(self, v, check=True): sage: c.rational_point() (15/8 : 17/8 : 1) sage: d = Conic([1, -1, 1]) - sage: d.rational_point() + sage: d.rational_point() # needs sage.libs.pari (-1 : 1 : 0) """ if is_Vector(v): @@ -1009,19 +1015,18 @@ def random_rational_point(self, *args1, **args2): are passed to ``random_element``. If the base field is a finite field, then the - output is uniformly distributed over the points of self. + output is uniformly distributed over the points of ``self``. EXAMPLES:: + sage: # needs sage.libs.pari sage: c = Conic(GF(2), [1,1,1,1,1,0]) sage: [c.random_rational_point() for i in range(10)] # random [(1 : 0 : 1), (1 : 0 : 1), (1 : 0 : 1), (0 : 1 : 1), (1 : 0 : 1), (0 : 0 : 1), (1 : 0 : 1), (1 : 0 : 1), (0 : 0 : 1), (1 : 0 : 1)] - sage: d = Conic(QQ, [1, 1, -1]) sage: d.random_rational_point(den_bound=1, num_bound=5) # random (-24/25 : 7/25 : 1) - sage: Conic(QQ, [1, 1, 1]).random_rational_point() Traceback (most recent call last): ... @@ -1055,10 +1060,11 @@ def rational_point(self, algorithm='default', read_cache=True): Examples over `\QQ` :: sage: R. = QQ[] + + sage: # needs sage.libs.pari sage: C = Conic(7*x^2 + 2*y*z + z^2) sage: C.rational_point() (0 : 1 : 0) - sage: C = Conic(x^2 + 2*y^2 + z^2) sage: C.rational_point() Traceback (most recent call last): @@ -1090,7 +1096,7 @@ def rational_point(self, algorithm='default', read_cache=True): sage: D.rational_point(algorithm='rnfisnorm') # output is random # needs sage.rings.number_field (-3 : 4*i : 1) - sage: # needs sage.rings.number_field + sage: # needs sage.libs.pari sage.rings.number_field sage: L. = QuadraticField(2) sage: Conic(QQ, [1, 1, -3]).has_rational_point() False @@ -1117,7 +1123,7 @@ def rational_point(self, algorithm='default', read_cache=True): ....: read_cache=False) (-s : 1 : 1) - sage: # needs sage.rings.number_field + sage: # needs sage.libs.pari sage.rings.number_field sage: F = Conic([L.gen(), 30, -20]) sage: q = F.rational_point(algorithm='magma') # optional - magma sage: q # random # optional - magma @@ -1132,7 +1138,7 @@ def rational_point(self, algorithm='default', read_cache=True): sage: G = Conic([L.gen(), 30, -21]) sage: G.has_rational_point(algorithm='magma') # optional - magma False - sage: G.has_rational_point(read_cache=False) + sage: G.has_rational_point(read_cache=False) # needs sage.libs.pari False sage: G.has_rational_point(algorithm='local', ....: read_cache=False) @@ -1286,8 +1292,7 @@ def variable_names(self): :: - sage: C. = Conic(QQ, [1, 1, 1]) - sage: C + sage: C. = Conic(QQ, [1, 1, 1]); C # needs sage.libs.singular Projective Conic Curve over Rational Field defined by p^2 + q^2 + r^2 """ diff --git a/src/sage/schemes/plane_conics/con_rational_field.py b/src/sage/schemes/plane_conics/con_rational_field.py index c6c76df0820..f59468d3b90 100644 --- a/src/sage/schemes/plane_conics/con_rational_field.py +++ b/src/sage/schemes/plane_conics/con_rational_field.py @@ -115,6 +115,7 @@ def has_rational_point(self, point=False, obstruction=False, EXAMPLES:: + sage: # needs sage.libs.pari sage: C = Conic(QQ, [1, 2, -3]) sage: C.has_rational_point(point=True) (True, (1 : 1 : 1)) @@ -131,7 +132,7 @@ def has_rational_point(self, point=False, obstruction=False, ``algorithm = 'rnfisnorm'`` :: sage: C = Conic(QQ, [1, 113922743, -310146482690273725409]) - sage: C.has_rational_point(point=True) + sage: C.has_rational_point(point=True) # needs sage.libs.pari (True, (-76842858034579/5424 : -5316144401/5424 : 1)) sage: C.has_rational_point(algorithm='local', read_cache=False) True @@ -144,10 +145,11 @@ def has_rational_point(self, point=False, obstruction=False, Create a bunch of conics over `\QQ`, check if ``has_rational_point`` runs without errors and returns consistent answers for all algorithms. Check if all points returned are valid. :: + sage: # needs sage.libs.pari sage: l = Sequence(cartesian_product_iterator([[-1, 0, 1] for i in range(6)])) sage: c = [Conic(QQ, a) for a in l if a != [0,0,0] and a != (0,0,0,0,0,0)] sage: d = [] - sage: d = [[C] + [C.has_rational_point(algorithm=algorithm, read_cache=False, # long time: 7 seconds + sage: d = [[C] + [C.has_rational_point(algorithm=algorithm, read_cache=False, # long time (7 s) ....: obstruction=(algorithm != 'rnfisnorm'), ....: point=(algorithm != 'local')) ....: for algorithm in ['local', 'qfsolve', 'rnfisnorm']] @@ -214,6 +216,7 @@ def is_locally_solvable(self, p) -> bool: EXAMPLES:: + sage: # needs sage.libs.pari sage: C = Conic(QQ, [1,2,3]) sage: C.is_locally_solvable(-1) False @@ -272,6 +275,7 @@ def local_obstructions(self, finite=True, infinite=True, read_cache=True): EXAMPLES:: + sage: # needs sage.libs.pari sage: Conic(QQ, [1, 1, 1]).local_obstructions() [2, -1] sage: Conic(QQ, [1, 2, -3]).local_obstructions() @@ -330,6 +334,7 @@ def parametrization(self, point=None, morphism=True): EXAMPLES:: + sage: # needs sage.libs.pari sage: c = Conic([1,1,-1]) sage: c.parametrization() (Scheme morphism: @@ -345,6 +350,7 @@ def parametrization(self, point=None, morphism=True): An example with ``morphism = False`` :: + sage: # needs sage.libs.pari sage: R. = QQ[] sage: C = Curve(7*x^2 + 2*y*z + z^2) sage: (p, i) = C.parametrization(morphism=False); (p, i) @@ -354,8 +360,9 @@ def parametrization(self, point=None, morphism=True): sage: i[0](p) / i[1](p) x/y - A ``ValueError`` is raised if ``self`` has no rational point :: + A :class:`ValueError` is raised if ``self`` has no rational point :: + sage: # needs sage.libs.pari sage: C = Conic(x^2 + 2*y^2 + z^2) sage: C.parametrization() Traceback (most recent call last): @@ -363,8 +370,9 @@ def parametrization(self, point=None, morphism=True): ValueError: Conic Projective Conic Curve over Rational Field defined by x^2 + 2*y^2 + z^2 has no rational points over Rational Field! - A ``ValueError`` is raised if ``self`` is not smooth :: + A :class:`ValueError` is raised if ``self`` is not smooth :: + sage: # needs sage.libs.pari sage: C = Conic(x^2 + y^2) sage: C.parametrization() Traceback (most recent call last): diff --git a/src/sage/schemes/plane_conics/con_rational_function_field.py b/src/sage/schemes/plane_conics/con_rational_function_field.py index 1b3f0ac412a..05d24e78a85 100644 --- a/src/sage/schemes/plane_conics/con_rational_function_field.py +++ b/src/sage/schemes/plane_conics/con_rational_function_field.py @@ -25,7 +25,7 @@ sage: K. = FractionField(QQ['t']) sage: C = Conic([1, -t, t]) - sage: C.has_rational_point(point=True) + sage: C.has_rational_point(point=True) # needs sage.libs.singular (True, (0 : 1 : 1)) """ @@ -128,37 +128,37 @@ def has_rational_point(self, point=False, algorithm='default', sage: K. = FractionField(PolynomialRing(QQ, 't')) sage: C = Conic(K, [t^2 - 2, 2*t^3, -2*t^3 - 13*t^2 - 2*t + 18]) - sage: C.has_rational_point(point=True) + sage: C.has_rational_point(point=True) # needs sage.libs.singular (True, (-3 : (t + 1)/t : 1)) sage: R. = FiniteField(23)[] sage: C = Conic([2, t^2 + 1, t^2 + 5]) - sage: C.has_rational_point() + sage: C.has_rational_point() # needs sage.libs.singular True - sage: C.has_rational_point(point=True) + sage: C.has_rational_point(point=True) # needs sage.libs.singular (True, (5*t : 8 : 1)) sage: # needs sage.rings.number_field sage: F. = QuadraticField(-1) sage: R. = F[] sage: C = Conic([1, i*t, -t^2 + 4]) - sage: C.has_rational_point(point=True) + sage: C.has_rational_point(point=True) # needs sage.libs.singular (True, (-t - 2*i : -2*i : 1)) It works on non-diagonal conics as well:: sage: K. = QQ[] sage: C = Conic([4, -4, 8, 1, -4, t + 4]) - sage: C.has_rational_point(point=True) + sage: C.has_rational_point(point=True) # needs sage.libs.singular (True, (1/2 : 1 : 0)) If no point exists output still depends on the argument ``point``:: sage: K. = QQ[] sage: C = Conic(K, [t^2, (t-1), -2*(t-1)]) - sage: C.has_rational_point() + sage: C.has_rational_point() # needs sage.libs.singular False - sage: C.has_rational_point(point=True) + sage: C.has_rational_point(point=True) # needs sage.libs.singular (False, None) Due to limitations in Sage of algorithms we depend on, it is not @@ -171,7 +171,7 @@ def has_rational_point(self, point=False, algorithm='default', sage: b = 2*t2^2 + 2*t1*t2 - t1^2 sage: c = -3*t2^4 - 4*t1*t2^3 + 8*t1^2*t2^2 + 16*t1^3 - t2 - 48*t1^4 sage: C = Conic([a,b,c]) - sage: C.has_rational_point() + sage: C.has_rational_point() # needs sage.libs.singular Traceback (most recent call last): ... NotImplementedError: is_square() not implemented for elements of @@ -204,7 +204,7 @@ def has_rational_point(self, point=False, algorithm='default', sage: K. = PolynomialRing(GF(7)) sage: C = Conic([5*t^2 + 4, t^2 + 3*t + 3, 6*t^2 + 3*t + 2, ....: 5*t^2 + 5, 4*t + 3, 4*t^2 + t + 5]) - sage: C.has_rational_point() + sage: C.has_rational_point() # needs sage.libs.singular Traceback (most recent call last): ... TypeError: self (=Scheme morphism: @@ -237,7 +237,7 @@ def has_rational_point(self, point=False, algorithm='default', sage: b = (1/2*t^2 + 1/3)/(-73*t^2 - 2*t + 11/4) sage: c = (6934/3*t^6 + 8798/3*t^5 - 947/18*t^4 + 3949/9*t^3 + 20983/18*t^2 + 28/3*t - 131/3)/(-2701/3*t^4 - 293/3*t^3 + 301/6*t^2 + 13/4*t - 11/16) sage: C = Conic([a,b,c]) - sage: C.has_rational_point(point=True) + sage: C.has_rational_point(point=True) # needs sage.libs.singular (True, (4*t + 4 : 2*t + 2 : 1)) A long time test:: @@ -247,7 +247,7 @@ def has_rational_point(self, point=False, algorithm='default', sage: b = (-3*t^3 + 8*t + 1/2)/(-1/3*t^3 + 3/2*t^2 + 1/12*t + 1/2) sage: c = (1232009/225*t^25 - 1015925057/8100*t^24 + 1035477411553/1458000*t^23 + 7901338091/30375*t^22 - 1421379260447/729000*t^21 + 266121260843/972000*t^20 + 80808723191/486000*t^19 - 516656082523/972000*t^18 + 21521589529/40500*t^17 + 4654758997/21600*t^16 - 20064038625227/9720000*t^15 - 173054270347/324000*t^14 + 536200870559/540000*t^13 - 12710739349/50625*t^12 - 197968226971/135000*t^11 - 134122025657/810000*t^10 + 22685316301/120000*t^9 - 2230847689/21600*t^8 - 70624099679/270000*t^7 - 4298763061/270000*t^6 - 41239/216000*t^5 - 13523/36000*t^4 + 493/36000*t^3 + 83/2400*t^2 + 1/300*t + 1/200)/(-27378/125*t^17 + 504387/500*t^16 - 97911/2000*t^15 + 1023531/4000*t^14 + 1874841/8000*t^13 + 865381/12000*t^12 + 15287/375*t^11 + 6039821/6000*t^10 + 599437/1500*t^9 + 18659/250*t^8 + 1218059/6000*t^7 + 2025127/3000*t^6 + 1222759/6000*t^5 + 38573/200*t^4 + 8323/125*t^3 + 15453/125*t^2 + 17031/500*t + 441/10) sage: C = Conic([a,b,c]) - sage: C.has_rational_point(point = True) # long time (4 seconds) + sage: C.has_rational_point(point=True) # long time (4 seconds) # needs sage.libs.singular (True, ((-2/117*t^8 + 304/1053*t^7 + 40/117*t^6 - 1/27*t^5 - 110/351*t^4 - 2/195*t^3 + 11/351*t^2 + 1/117)/(t^4 + 2/39*t^3 + 4/117*t^2 + 2/39*t + 14/39) : -5/3*t^4 + 19*t^3 : 1)) """ @@ -475,7 +475,7 @@ def find_point(self, supports, roots, case, solution=0): sage: K. = FractionField(QQ['t']) sage: C = Conic(K, [t^2 - 2, 2*t^3, -2*t^3 - 13*t^2 - 2*t + 18]) - sage: C.has_rational_point(point=True) # indirect test + sage: C.has_rational_point(point=True) # indirect test # needs sage.libs.singular (True, (-3 : (t + 1)/t : 1)) Different solubility certificates give different points:: diff --git a/src/sage/schemes/product_projective/morphism.py b/src/sage/schemes/product_projective/morphism.py index 74b424022a2..d5b1974164b 100644 --- a/src/sage/schemes/product_projective/morphism.py +++ b/src/sage/schemes/product_projective/morphism.py @@ -19,12 +19,15 @@ # the License, or (at your option) any later version. # https://www.gnu.org/licenses/ # **************************************************************************** -from sage.schemes.generic.morphism import SchemeMorphism_polynomial + +import sage.rings.abc + from sage.categories.fields import Fields from sage.categories.number_fields import NumberFields -from sage.rings.number_field.order import is_NumberFieldOrder from sage.rings.fraction_field import FractionField -from sage.rings.qqbar import QQbar +from sage.rings.integer_ring import ZZ +from sage.schemes.generic.morphism import SchemeMorphism_polynomial + _Fields = Fields() @@ -460,14 +463,14 @@ def global_height(self, prec=None): 2.56494935746154 """ K = self.domain().base_ring() - if K in NumberFields() or is_NumberFieldOrder(K): + if K in NumberFields() or K == ZZ or isinstance(K, sage.rings.abc.Order): H = 0 for i in range(self.domain().ambient_space().ngens()): C = self[i].coefficients() h = max(c.global_height(prec=prec) for c in C) H = max(H, h) return H - elif K == QQbar: + elif isinstance(K, sage.rings.abc.AlgebraicField): raise NotImplementedError("not implemented for QQbar") else: raise TypeError("Must be over a Numberfield or a Numberfield Order or QQbar") diff --git a/src/sage/schemes/product_projective/point.py b/src/sage/schemes/product_projective/point.py index d51d5d369bf..70cc344806f 100644 --- a/src/sage/schemes/product_projective/point.py +++ b/src/sage/schemes/product_projective/point.py @@ -21,11 +21,13 @@ # https://www.gnu.org/licenses/ # **************************************************************************** from copy import copy + +import sage.rings.abc + from sage.categories.integral_domains import IntegralDomains from sage.categories.number_fields import NumberFields from sage.rings.fraction_field import FractionField -from sage.rings.number_field.order import is_NumberFieldOrder -from sage.rings.qqbar import QQbar +from sage.rings.integer_ring import ZZ from sage.schemes.generic.morphism import SchemeMorphism from sage.schemes.generic.morphism import SchemeMorphism_point from sage.structure.sequence import Sequence @@ -339,7 +341,7 @@ def dehomogenize(self, L): :: - sage: # needs sage.rings.real_mpfr + sage: # needs sage.rings.real_mpfr sage.symbolic sage: PP. = ProductProjectiveSpaces([1, 2], CC) sage: X = PP.subscheme([a^2 + b^2]) sage: P = X([2, 2*i, -3, 6*i, 3 - 6*i]) @@ -466,7 +468,7 @@ def global_height(self, prec=None): 0.536479304144700 """ K = self.codomain().base_ring() - if K not in NumberFields() and not is_NumberFieldOrder(K) and K != QQbar: + if K not in NumberFields() and K != ZZ and not isinstance(K, (sage.rings.abc.Order, sage.rings.abc.AlgebraicField)): raise TypeError("must be over a number field or a number field order or QQbar") n = self.codomain().ambient_space().num_components() diff --git a/src/sage/schemes/product_projective/rational_point.py b/src/sage/schemes/product_projective/rational_point.py index 5375ffb4535..c9a2cf6b25f 100644 --- a/src/sage/schemes/product_projective/rational_point.py +++ b/src/sage/schemes/product_projective/rational_point.py @@ -57,15 +57,17 @@ from sage.schemes.generic.scheme import is_Scheme from sage.schemes.product_projective.space import is_ProductProjectiveSpaces +from sage.misc.lazy_import import lazy_import from sage.misc.mrange import xmrange from sage.misc.misc_c import prod from sage.arith.misc import next_prime, previous_prime, crt from sage.rings.integer_ring import ZZ -from sage.rings.real_mpfr import RR from sage.rings.finite_rings.finite_field_constructor import FiniteField as GF from sage.parallel.ncpus import ncpus from sage.parallel.use_fork import p_iter_fork -from sage.matrix.constructor import matrix + +lazy_import('sage.matrix.constructor', 'matrix') +lazy_import('sage.rings.real_mpfr', 'RR') def enum_product_projective_rational_field(X, B): diff --git a/src/sage/schemes/projective/projective_homset.py b/src/sage/schemes/projective/projective_homset.py index e1031e71fcf..2a61c1dd17c 100644 --- a/src/sage/schemes/projective/projective_homset.py +++ b/src/sage/schemes/projective/projective_homset.py @@ -581,7 +581,7 @@ class SchemeHomset_points_abelian_variety_field(SchemeHomset_points_projective_f The bug reported at :trac:`1785` is fixed:: - sage: # needs sage.rings.number_field + sage: # needs sage.rings.number_field sage.schemes sage: x = polygen(ZZ, 'x') sage: K. = NumberField(x^2 + x - (3^3-3)) sage: E = EllipticCurve('37a') diff --git a/src/sage/schemes/projective/projective_morphism.py b/src/sage/schemes/projective/projective_morphism.py index c0f3fb20fdf..2983b03796e 100644 --- a/src/sage/schemes/projective/projective_morphism.py +++ b/src/sage/schemes/projective/projective_morphism.py @@ -62,26 +62,18 @@ import sys from sage.arith.misc import GCD as gcd from sage.arith.functions import lcm -from sage.interfaces.singular import singular from sage.misc.misc_c import prod from sage.misc.cachefunc import cached_method from sage.misc.lazy_attribute import lazy_attribute -from sage.ext.fast_callable import fast_callable -from sage.calculus.functions import jacobian import sage.rings.abc from sage.rings.integer import Integer from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField_generic from sage.rings.finite_rings.finite_field_base import FiniteField -from sage.rings.finite_rings.finite_field_constructor import GF from sage.rings.fraction_field import FractionField from sage.rings.integer_ring import ZZ -from sage.rings.number_field.order import is_NumberFieldOrder from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing -from sage.rings.qqbar import QQbar, number_field_elements_from_algebraics from sage.rings.quotient_ring import QuotientRing_generic from sage.rings.rational_field import QQ -from sage.modules.free_module_element import vector -from sage.matrix.constructor import matrix from sage.schemes.generic.morphism import SchemeMorphism_polynomial from sage.categories.finite_fields import FiniteFields from sage.categories.number_fields import NumberFields @@ -430,6 +422,8 @@ def _fastpolys(self): [[('load_const', 0), ('load_const', 1), ('load_arg', ...), ('ipow', 2), 'mul', 'add', ('load_const', 1), ('load_arg', ...), ('ipow', 2), 'mul', 'add', 'return'], [('load_const', 0), ('load_const', 1), ('load_arg', 1), ('ipow', 2), 'mul', 'add', 'return']] """ + from sage.ext.fast_callable import fast_callable + polys = self._polys fastpolys = [] @@ -627,6 +621,7 @@ def _matrix_times_polymap_(self, mat, h): """ from sage.modules.free_module_element import vector from sage.dynamics.arithmetic_dynamics.generic_ds import DynamicalSystem + if not mat.is_square(): raise ValueError("matrix must be square") if mat.ncols() != self.codomain().ngens(): @@ -1366,7 +1361,7 @@ def global_height(self, prec=None): :: - sage: # needs sage.rings.number_field + sage: # needs sage.rings.number_field sage.symbolic sage: P. = ProjectiveSpace(QQbar, 1) sage: P2. = ProjectiveSpace(QQbar, 2) sage: H = Hom(P, P2) @@ -1402,9 +1397,9 @@ def global_height(self, prec=None): 6.43775164973640 """ K = self.domain().base_ring() - if K in _NumberFields or is_NumberFieldOrder(K): + if K in _NumberFields or K == ZZ or isinstance(K, sage.rings.abc.Order): f = self - elif K is QQbar: + elif isinstance(K, sage.rings.abc.AlgebraicField): f = self._number_field_from_algebraics() else: raise TypeError("Must be over a Numberfield or a Numberfield Order or QQbar") @@ -1472,7 +1467,7 @@ def local_height(self, v, prec=None): 1.09861228866811 """ K = FractionField(self.domain().base_ring()) - if K not in _NumberFields or is_NumberFieldOrder(K): + if K not in _NumberFields: raise TypeError("must be over a number field or a number field order") return max([K(c).local_height(v, prec=prec) for f in self for c in f.coefficients()]) @@ -1520,7 +1515,7 @@ def local_height_arch(self, i, prec=None): 0.6931471805599453094172321214582 """ K = FractionField(self.domain().base_ring()) - if K not in _NumberFields or is_NumberFieldOrder(K): + if K not in _NumberFields: raise TypeError("must be over a number field or a number field order") if K == QQ: return max([K(c).local_height_arch(prec=prec) for f in self for c in f.coefficients()]) @@ -1559,6 +1554,8 @@ def wronskian_ideal(self): Ideal (4*x*y, 2*x^2 + 4*y^2, -2*y^2) of Multivariate Polynomial Ring in x, y over Rational Field """ + from sage.calculus.functions import jacobian + dom = self.domain() from sage.schemes.projective.projective_space import is_ProjectiveSpace if not (is_ProjectiveSpace(dom) and is_ProjectiveSpace(self.codomain())): @@ -1799,7 +1796,9 @@ def _number_field_from_algebraics(self): Defn: Defined on coordinates by sending (x : y) to ((-0.6823278038280193?)*x^3 + (-13)*y^3 : (-14)*y^3) """ + from sage.rings.qqbar import number_field_elements_from_algebraics from sage.schemes.projective.projective_space import is_ProjectiveSpace + if not (is_ProjectiveSpace(self.domain()) and is_ProjectiveSpace(self.domain())): raise NotImplementedError("not implemented for subschemes") @@ -1809,7 +1808,7 @@ def _number_field_from_algebraics(self): if K_pre is QQ: if K_pre is self.base_ring(): return self - elif self.base_ring() != QQbar and K_pre.is_isomorphic(self.base_ring()): + elif not isinstance(self.base_ring(), sage.rings.abc.AlgebraicField) and K_pre.is_isomorphic(self.base_ring()): return self # Issue 23808: The field K_pre returned above does not have its embedding set to be phi # and phi is forgotten, so we redefine K_pre to be a field K with phi as the specified @@ -2082,18 +2081,18 @@ def reduce_base_field(self): sage: H2 = Hom(P, P2) sage: H3 = Hom(P2, P) sage: f = H([x^2 + (2*t^3 + 2*t^2 + 1)*y^2, y^2]) - sage: f.reduce_base_field() + sage: f.reduce_base_field() # needs sage.libs.singular sage.modules Scheme endomorphism of Projective Space of dimension 1 over Finite Field in t2 of size 3^2 Defn: Defined on coordinates by sending (x : y) to (x^2 + t2*y^2 : y^2) sage: f2 = H2([x^2 + 5*y^2, y^2, 2*x*y]) - sage: f2.reduce_base_field() + sage: f2.reduce_base_field() # needs sage.libs.singular sage.modules Scheme morphism: From: Projective Space of dimension 1 over Finite Field of size 3 To: Projective Space of dimension 2 over Finite Field of size 3 Defn: Defined on coordinates by sending (x : y) to (x^2 - y^2 : y^2 : -x*y) sage: f3 = H3([a^2 + t*b^2, c^2]) - sage: f3.reduce_base_field() + sage: f3.reduce_base_field() # needs sage.libs.singular sage.modules Scheme morphism: From: Projective Space of dimension 2 over Finite Field in t of size 3^4 To: Projective Space of dimension 1 over Finite Field in t of size 3^4 @@ -2106,7 +2105,7 @@ def reduce_base_field(self): sage: P. = ProjectiveSpace(K, 1) sage: H = End(P) sage: f = H([x^2 + 2*y^2, y^2]) - sage: f.reduce_base_field() + sage: f.reduce_base_field() # needs sage.libs.singular Scheme endomorphism of Projective Space of dimension 1 over Rational Field Defn: Defined on coordinates by sending (x : y) to (x^2 + 2*y^2 : y^2) @@ -2118,13 +2117,13 @@ def reduce_base_field(self): sage: P. = ProjectiveSpace(L, 1) sage: H = End(P) sage: f = H([(L.gen(2))*x^2 + L.gen(4)*y^2, x*y]) - sage: f.reduce_base_field() + sage: f.reduce_base_field() # needs sage.libs.singular Scheme endomorphism of Projective Space of dimension 1 over Finite Field in z4 of size 5^4 Defn: Defined on coordinates by sending (x : y) to ((z4^3 + z4^2 + z4 - 2)*x^2 + z4*y^2 : x*y) - sage: f = DynamicalSystem_projective([L.gen(3)*x^2 + L.gen(2)*y^2, x*y]) - sage: f.reduce_base_field() + sage: f = DynamicalSystem_projective([L.gen(3)*x^2 + L.gen(2)*y^2, x*y]) # needs sage.schemes + sage: f.reduce_base_field() # needs sage.libs.singular sage.schemes Dynamical System of Projective Space of dimension 1 over Finite Field in z6 of size 5^6 Defn: Defined on coordinates by sending (x : y) to @@ -2138,19 +2137,21 @@ def reduce_base_field(self): sage: P. = ProjectiveSpace(F, 1) sage: H = Hom(P, P) sage: f = H([x^2 + y^2, y^2]) - sage: f.reduce_base_field() + sage: f.reduce_base_field() # needs sage.libs.singular Scheme endomorphism of Projective Space of dimension 1 over Finite Field of size 3 Defn: Defined on coordinates by sending (x : y) to (x^2 + y^2 : y^2) """ K = self.base_ring() - if K in NumberFields() or K is QQbar: + if K in NumberFields() or isinstance(K, sage.rings.abc.AlgebraicField): return self._number_field_from_algebraics() if K in FiniteFields(): #find the degree of the extension containing the coefficients c = [v for g in self for v in g.coefficients()] d = lcm([a.minpoly().degree() for a in c]) if d == 1: + from sage.rings.finite_rings.finite_field_constructor import GF + return self.change_ring(GF(K.characteristic())) if d == K.degree(): return self @@ -2310,7 +2311,7 @@ def __call__(self, x): TESTS:: - sage: # needs sage.schemes + sage: # needs sage.libs.pari sage.schemes sage: R. = QQ[] sage: C = Curve(7*x^2 + 2*y*z + z^2) sage: f, g = C.parametrization() @@ -2325,7 +2326,7 @@ def __call__(self, x): reprs = self.representatives() except NotImplementedError: # Singular does not support the base field try: - return super(SchemeMorphism_polynomial_projective_subscheme_field, self).__call__(x) + return super().__call__(x) except ValueError: raise ValueError('cannot apply the morphism to this point') @@ -2341,9 +2342,11 @@ def __eq__(self, other): EXAMPLES:: sage: R. = QQ[] - sage: C = Curve(7*x^2 + 2*y*z + z^2) # conic # needs sage.schemes - sage: f, g = C.parametrization() # needs sage.schemes - sage: f*g == C.identity_morphism() # needs sage.schemes + + sage: # needs sage.libs.pari sage.schemes + sage: C = Curve(7*x^2 + 2*y*z + z^2) # conic + sage: f, g = C.parametrization() + sage: f*g == C.identity_morphism() True sage: # needs sage.schemes @@ -2368,6 +2371,8 @@ def __eq__(self, other): e = Y.projective_embedding(0) return (e * self) == (e * other) + from sage.matrix.constructor import matrix + R = self.domain().coordinate_ring() mat = matrix([self.defining_polynomials(), other.defining_polynomials()]) return all(R(minor).is_zero() for minor in mat.minors(2)) @@ -2475,6 +2480,7 @@ def representatives(self): raise ValueError("domain is not an irreducible scheme") # prepare homogeneous coordinate ring of X in Singular + from sage.interfaces.singular import singular from sage.rings.polynomial.term_order import TermOrder T = TermOrder('degrevlex') T._singular_ringorder_column = 1 # (c,dp) in Singular @@ -2776,6 +2782,8 @@ def projective_degrees(self): G = self.graph() I = G.defining_ideal() # a bihomogeneous ideal + from sage.modules.free_module_element import vector + degrees = xn * [vector([1, 0])] + yn * [vector([0, 1])] res = I.graded_free_resolution(degrees=degrees, algorithm='shreyer') kpoly = res.K_polynomial() diff --git a/src/sage/schemes/projective/projective_point.py b/src/sage/schemes/projective/projective_point.py index 53038b21efe..e22e0a858b1 100644 --- a/src/sage/schemes/projective/projective_point.py +++ b/src/sage/schemes/projective/projective_point.py @@ -728,8 +728,8 @@ def global_height(self, prec=None): :: sage: P. = ProjectiveSpace(QQbar, 2) # needs sage.rings.number_field - sage: Q = P([QQbar(sqrt(3)), QQbar(sqrt(-2)), 1]) # needs sage.rings.number_field - sage: Q.global_height() # needs sage.rings.number_field + sage: Q = P([QQbar(sqrt(3)), QQbar(sqrt(-2)), 1]) # needs sage.rings.number_field sage.symbolic + sage: Q.global_height() # needs sage.rings.number_field sage.symbolic 0.549306144334055 :: @@ -1074,6 +1074,7 @@ class SchemeMorphism_point_projective_field(SchemeMorphism_point_projective_ring EXAMPLES:: + sage: # needs sage.rings.real_mpfr sage: P = ProjectiveSpace(3, RR) sage: P(2, 3, 4, 5) (0.400000000000000 : 0.600000000000000 : 0.800000000000000 : 1.00000000000000) diff --git a/src/sage/schemes/projective/projective_rational_point.py b/src/sage/schemes/projective/projective_rational_point.py index 0525883886d..cc99ba389ac 100644 --- a/src/sage/schemes/projective/projective_rational_point.py +++ b/src/sage/schemes/projective/projective_rational_point.py @@ -190,7 +190,7 @@ def enum_projective_number_field(X, **kwds): sage: K = NumberField(u^3 - 5, 'v') sage: P. = ProjectiveSpace(K, 2) sage: X = P.subscheme([x - y]) - sage: enum_projective_number_field(X(K), bound=RR(5^(1/3)), prec=2^10) + sage: enum_projective_number_field(X(K), bound=RR(5^(1/3)), prec=2^10) # needs sage.symbolic [(0 : 0 : 1), (1 : 1 : 0), (-1 : -1 : 1), (1 : 1 : 1)] :: diff --git a/src/sage/schemes/projective/projective_space.py b/src/sage/schemes/projective/projective_space.py index 622f9ef911c..c1402654a87 100644 --- a/src/sage/schemes/projective/projective_space.py +++ b/src/sage/schemes/projective/projective_space.py @@ -2247,7 +2247,7 @@ def line_through(self, p, q): sage: P3. = ProjectiveSpace(3, QQ) sage: p1 = P3(1, 2, 3, 4) sage: p2 = P3(4, 3, 2, 1) - sage: P3.line_through(p1, p2) # needs sage.schemes + sage: P3.line_through(p1, p2) # needs sage.libs.singular sage.schemes Projective Curve over Rational Field defined by -5/4*x0 + 5/2*x1 - 5/4*x2, -5/2*x0 + 15/4*x1 - 5/4*x3, -5/4*x0 + 15/4*x2 - 5/2*x3, -5/4*x1 + 5/2*x2 - 5/4*x3 diff --git a/src/sage/schemes/projective/projective_subscheme.py b/src/sage/schemes/projective/projective_subscheme.py index 8970637882d..df649db61a6 100644 --- a/src/sage/schemes/projective/projective_subscheme.py +++ b/src/sage/schemes/projective/projective_subscheme.py @@ -469,10 +469,11 @@ def orbit(self, f, N): EXAMPLES:: + sage: # needs sage.libs.singular sage.schemes sage: P. = ProjectiveSpace(QQ, 3) - sage: f = DynamicalSystem_projective([(x-2*y)^2, (x-2*z)^2, # needs sage.schemes + sage: f = DynamicalSystem_projective([(x-2*y)^2, (x-2*z)^2, ....: (x-2*w)^2, x^2]) - sage: f.orbit(P.subscheme([x]), 5) # needs sage.schemes + sage: f.orbit(P.subscheme([x]), 5) [Closed subscheme of Projective Space of dimension 3 over Rational Field defined by: x, Closed subscheme of Projective Space of dimension 3 over Rational Field @@ -548,7 +549,7 @@ def nth_iterate(self, f, n): sage: P. = ProjectiveSpace(QQ, 3) sage: f = DynamicalSystem_projective([y^2, z^2, x^2, w^2]) # needs sage.schemes - sage: f.nth_iterate(P.subscheme([x - w, y - z]), 3) # needs sage.schemes + sage: f.nth_iterate(P.subscheme([x - w, y - z]), 3) # needs sage.libs.singular sage.schemes Closed subscheme of Projective Space of dimension 3 over Rational Field defined by: y - z, @@ -559,7 +560,7 @@ def nth_iterate(self, f, n): sage: PS. = ProjectiveSpace(ZZ, 2) sage: f = DynamicalSystem_projective([x^2, y^2, z^2]) # needs sage.schemes sage: X = PS.subscheme([x - y]) - sage: X.nth_iterate(f, -2) # needs sage.schemes + sage: X.nth_iterate(f, -2) # needs sage.libs.singular sage.schemes Traceback (most recent call last): ... TypeError: must be a forward orbit @@ -1039,9 +1040,10 @@ def degree(self): sage: X.degree() # needs sage.libs.singular 3 + sage: # needs sage.libs.singular sage.schemes sage: P. = ProjectiveSpace(QQ, 4) - sage: C = P.curve([x^7 - y*z^3*w^2*u, w*x^2 - y*u^2, z^3 + y^3]) # needs sage.schemes - sage: C.degree() # needs sage.libs.singular sage.schemes + sage: C = P.curve([x^7 - y*z^3*w^2*u, w*x^2 - y*u^2, z^3 + y^3]) + sage: C.degree() 63 """ P = self.defining_ideal().hilbert_polynomial() @@ -1157,10 +1159,11 @@ def multiplicity(self, P): :: + sage: # needs sage.libs.singular sage.schemes sage: P. = ProjectiveSpace(GF(29), 3) - sage: C = Curve([y^17 - x^5*w^4*z^8, x*y - z^2], P) # needs sage.schemes + sage: C = Curve([y^17 - x^5*w^4*z^8, x*y - z^2], P) sage: Q = P([3,0,0,1]) - sage: C.multiplicity(Q) # needs sage.libs.singular sage.schemes + sage: C.multiplicity(Q) 8 """ if self.base_ring() not in Fields(): @@ -1432,18 +1435,19 @@ def global_height(self, prec=None): EXAMPLES:: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: NF. = NumberField(x^2 - 5) sage: P. = ProjectiveSpace(NF, 2) sage: X = P.subscheme([x^2 + y*z, 2*y*z, 3*x*y]) - sage: X.global_height() + sage: X.global_height() # needs sage.libs.singular 0.000000000000000 :: sage: P. = ProjectiveSpace(QQ, 2) sage: X = P.subscheme([z^2 - 101*y^2 - 3*x*z]) - sage: X.global_height() # long time + sage: X.global_height() # long time # needs sage.libs.singular 4.61512051684126 """ return self.Chow_form().global_height(prec) @@ -1465,19 +1469,20 @@ def local_height(self, v, prec=None): EXAMPLES:: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: NF. = NumberField(x^2 - 5) sage: I = NF.ideal(3) sage: P. = ProjectiveSpace(NF, 2) sage: X = P.subscheme([3*x*y - 5*x*z, y^2]) - sage: X.local_height(I) + sage: X.local_height(I) # needs sage.libs.singular 0.000000000000000 :: sage: P. = ProjectiveSpace(QQ, 2) sage: X = P.subscheme([z^2 - 101*y^2 - 3*x*z]) - sage: X.local_height(2) + sage: X.local_height(2) # needs sage.libs.singular 0.000000000000000 """ return self.Chow_form().local_height(v, prec) @@ -1499,18 +1504,19 @@ def local_height_arch(self, i, prec=None): EXAMPLES:: + sage: # needs sage.rings.number_field sage: R. = QQ[] sage: NF. = NumberField(x^2 - 5) sage: P. = ProjectiveSpace(NF, 2) sage: X = P.subscheme([x^2 + y*z, 3*x*y]) - sage: X.local_height_arch(1) + sage: X.local_height_arch(1) # needs sage.libs.singular 0.0000000000000000000000000000000 :: sage: P. = ProjectiveSpace(QQ, 2) sage: X = P.subscheme([z^2 - 101*y^2 - 3*x*z]) - sage: X.local_height_arch(1) + sage: X.local_height_arch(1) # needs sage.libs.singular 4.61512051684126 """ - return self.Chow_form().local_height_arch(i, prec) \ No newline at end of file + return self.Chow_form().local_height_arch(i, prec) diff --git a/src/sage/schemes/toric/chow_group.py b/src/sage/schemes/toric/chow_group.py index ae3d245c744..dac091a4f6f 100644 --- a/src/sage/schemes/toric/chow_group.py +++ b/src/sage/schemes/toric/chow_group.py @@ -317,7 +317,7 @@ def count_points(self): sage: aD = a.intersection_with_divisor(D) sage: aD.count_points() 1 - sage: P2.integrate( aD.cohomology_class() ) + sage: P2.integrate(aD.cohomology_class()) # needs sage.libs.singular 1 For toric varieties with at most orbifold singularities, the @@ -333,7 +333,7 @@ def count_points(self): V(y) sage: Dt.Chow_cycle(QQ).intersection_with_divisor(Dy).count_points() 1/2 - sage: P1xP1_Z2.integrate( Dt.cohomology_class() * Dy.cohomology_class() ) + sage: P1xP1_Z2.integrate(Dt.cohomology_class() * Dy.cohomology_class()) # needs sage.libs.singular 1/2 """ return sum(self.project_to_degree(0).lift()) @@ -476,6 +476,7 @@ def cohomology_class(self): EXAMPLES:: + sage: # needs sage.libs.singular sage: dP6 = toric_varieties.dP6() sage: cone = dP6.fan().cone_containing(2,3) sage: HH = dP6.cohomology_ring() @@ -491,6 +492,7 @@ def cohomology_class(self): singularities, where we can also use the isomorphism with the rational cohomology ring:: + sage: # needs sage.libs.singular sage: WP4 = toric_varieties.P4_11169() sage: A = WP4.Chow_group() sage: HH = WP4.cohomology_ring() @@ -499,13 +501,11 @@ def cohomology_class(self): ( 0 | -1 | 0 | 0 | 0 ) sage: HH(cone3d) [3*z4^3] - sage: D = -WP4.K() # the anticanonical divisor sage: A(D) ( 0 | 0 | 0 | -18 | 0 ) sage: HH(D) [18*z4] - sage: WP4.integrate( A(cone3d).cohomology_class() * D.cohomology_class() ) 1 sage: WP4.integrate( HH(cone3d) * D.cohomology_class() ) diff --git a/src/sage/schemes/toric/divisor.py b/src/sage/schemes/toric/divisor.py index 3fbdae4cdb5..796d667c518 100644 --- a/src/sage/schemes/toric/divisor.py +++ b/src/sage/schemes/toric/divisor.py @@ -818,7 +818,7 @@ def cohomology_class(self): sage: dP6 = toric_varieties.dP6() sage: D = dP6.divisor(dP6.fan().ray(0)) - sage: D.cohomology_class() + sage: D.cohomology_class() # needs sage.libs.singular [y + v - w] """ divisor = vector(self) @@ -841,9 +841,9 @@ def Chern_character(self): sage: D5 = dP6.divisor(dP6.fan().cone_containing( N(-1,-1) )) sage: D6 = dP6.divisor(dP6.fan().cone_containing( N(0,-1) )) sage: D = -D3 + 2*D5 - D6 - sage: D.Chern_character() + sage: D.Chern_character() # needs sage.libs.singular [5*w^2 + y - 2*v + w + 1] - sage: dP6.integrate( D.ch() * dP6.Td() ) + sage: dP6.integrate(D.ch() * dP6.Td()) # needs sage.libs.singular -4 """ return self.cohomology_class().exp() @@ -1063,7 +1063,7 @@ def polyhedron(self): (A vertex at (0, 0),) sage: D.is_nef() False - sage: dP7.integrate( D.ch() * dP7.Td() ) + sage: dP7.integrate(D.ch() * dP7.Td()) # needs sage.libs.singular 1 sage: P_antiK = (-dP7.K()).polyhedron(); P_antiK A 2-dimensional polyhedron in QQ^2 defined as the convex hull of 5 vertices @@ -1267,7 +1267,7 @@ def Kodaira_map(self, names='z'): sage: P1. = toric_varieties.P1() sage: D = -P1.K() - sage: D.Kodaira_map() + sage: D.Kodaira_map() # needs fpylll sage.libs.singular Scheme morphism: From: 1-d CPR-Fano toric variety covered by 2 affine patches To: Closed subscheme of Projective Space of dimension 2 @@ -1276,7 +1276,7 @@ def Kodaira_map(self, names='z'): sage: dP6 = toric_varieties.dP6() sage: D = -dP6.K() - sage: D.Kodaira_map(names='x') + sage: D.Kodaira_map(names='x') # needs fpylll sage.libs.singular Scheme morphism: From: 2-d CPR-Fano toric variety covered by 6 affine patches To: Closed subscheme of Projective Space of dimension 6 @@ -1531,7 +1531,7 @@ def cohomology(self, weight=None, deg=None, dim=False): 2: Vector space of dimension 0 over Rational Field} sage: D.cohomology( weight=M(0,0), deg=1 ) Vector space of dimension 1 over Rational Field - sage: dP6.integrate( D.ch() * dP6.Td() ) + sage: dP6.integrate(D.ch() * dP6.Td()) # needs sage.libs.singular -4 Note the different output options:: diff --git a/src/sage/schemes/toric/divisor_class.pyx b/src/sage/schemes/toric/divisor_class.pyx index 5a92fe5b38d..3c9a9143eaf 100644 --- a/src/sage/schemes/toric/divisor_class.pyx +++ b/src/sage/schemes/toric/divisor_class.pyx @@ -137,7 +137,7 @@ cdef class ToricRationalDivisorClass(Vector_rational_dense): (self._parent, list(self), self._degree, not self._is_immutable)) - cpdef _act_on_(self, other, bint self_on_left): + cpdef _act_on_(self, other, bint self_on_left) noexcept: """ Act on ``other``. @@ -202,7 +202,7 @@ cdef class ToricRationalDivisorClass(Vector_rational_dense): # Now let the standard framework work... return Vector_rational_dense._act_on_(self, other, self_on_left) - cpdef _dot_product_(self, Vector right): + cpdef _dot_product_(self, Vector right) noexcept: r""" Raise a ``TypeError`` exception. diff --git a/src/sage/schemes/toric/fano_variety.py b/src/sage/schemes/toric/fano_variety.py index a1405c966ec..b7f2c2ab6ac 100644 --- a/src/sage/schemes/toric/fano_variety.py +++ b/src/sage/schemes/toric/fano_variety.py @@ -1518,7 +1518,7 @@ def cohomology_class(self): covered by 8 affine patches defined by: a2*z0^2*z1 + a5*z0*z1*z3 + a1*z1*z3^2 + a3*z0^2*z4 + a4*z0*z3*z4 + a0*z3^2*z4, b1*z1*z2^2 + b2*z2^2*z4 + b5*z1*z2*z5 + b4*z2*z4*z5 + b3*z1*z5^2 + b0*z4*z5^2 - sage: CI.cohomology_class() + sage: CI.cohomology_class() # needs sage.libs.singular [2*z3*z4 + 4*z3*z5 + 2*z4*z5] """ X = self.ambient_space() diff --git a/src/sage/schemes/toric/homset.py b/src/sage/schemes/toric/homset.py index bd535edf932..e02d0b92078 100644 --- a/src/sage/schemes/toric/homset.py +++ b/src/sage/schemes/toric/homset.py @@ -621,6 +621,7 @@ def __iter__(self): EXAMPLES:: + sage: # needs sage.libs.singular sage: P2. = toric_varieties.P2(base_ring=GF(5)) sage: cubic = P2.subscheme([x^3 + y^3 + z^3]) sage: list(cubic.point_set()) @@ -641,6 +642,7 @@ def cardinality(self): EXAMPLES:: + sage: # needs sage.libs.singular sage: P2. = toric_varieties.P2(base_ring=GF(5)) sage: cubic = P2.subscheme([x^3 + y^3 + z^3]) sage: list(cubic.point_set()) diff --git a/src/sage/schemes/toric/ideal.py b/src/sage/schemes/toric/ideal.py index bf9eb94e331..6d611719c14 100644 --- a/src/sage/schemes/toric/ideal.py +++ b/src/sage/schemes/toric/ideal.py @@ -1,4 +1,4 @@ -# sage.doctest: needs sage.geometry.polyhedron sage.graphs +# sage.doctest: needs sage.geometry.polyhedron sage.graphs sage.libs.singular r""" Toric ideals diff --git a/src/sage/schemes/toric/points.py b/src/sage/schemes/toric/points.py index f9563bd0acc..4a40aa82ef7 100644 --- a/src/sage/schemes/toric/points.py +++ b/src/sage/schemes/toric/points.py @@ -1007,7 +1007,7 @@ def cardinality(self): sage: X. = ToricVariety(fan, base_ring=GF(7)) sage: Y = X.subscheme(u^3 + v^3 + w^3 + u*v*w) sage: point_set = Y.point_set() - sage: list(point_set) + sage: list(point_set) # needs fpylll [[0 : 1 : 3], [1 : 0 : 3], [1 : 3 : 0], @@ -1015,8 +1015,8 @@ def cardinality(self): [1 : 1 : 4], [1 : 3 : 2], [1 : 3 : 5]] - sage: ffe = point_set._enumerator() - sage: ffe.cardinality() + sage: ffe = point_set._enumerator() # needs fpylll + sage: ffe.cardinality() # needs fpylll 7 """ n = 0 diff --git a/src/sage/schemes/toric/toric_subscheme.py b/src/sage/schemes/toric/toric_subscheme.py index acdfd05d0d1..6b3645d0e4a 100644 --- a/src/sage/schemes/toric/toric_subscheme.py +++ b/src/sage/schemes/toric/toric_subscheme.py @@ -123,8 +123,8 @@ def _morphism(self, *args, **kwds): Defn: Defined on coordinates by sending [s : t : x : y] to [s : s : x : y] - sage: sbar, tbar, xbar, ybar = P1.coordinate_ring().gens() - sage: P1._morphism(H, [sbar, sbar, xbar, ybar]) + sage: sbar, tbar, xbar, ybar = P1.coordinate_ring().gens() # needs sage.libs.singular + sage: P1._morphism(H, [sbar, sbar, xbar, ybar]) # needs sage.libs.singular Scheme morphism: From: Closed subscheme of 2-d CPR-Fano toric variety covered by 4 affine patches defined by: @@ -270,6 +270,7 @@ def affine_algebraic_patch(self, cone=None, names=None): Closed subscheme of Affine Space of dimension 2 over Rational Field defined by: z0^3 + z1^3 + 1 + sage: # needs fpylll sage.libs.singular sage: cone = Cone([(0,1), (2,1)]) sage: A2Z2. = AffineToricVariety(cone) sage: A2Z2.affine_algebraic_patch() @@ -425,6 +426,7 @@ def neighborhood(self, point): EXAMPLES:: + sage: # needs sage.libs.singular sage: P. = toric_varieties.P2() sage: S = P.subscheme(x + 2*y + 3*z) sage: s = S.point([0,-3,2]); s @@ -445,6 +447,7 @@ def neighborhood(self, point): A more complicated example:: + sage: # needs sage.libs.singular sage: dP6. = toric_varieties.dP6() sage: twoP1 = dP6.subscheme(x0*x3) sage: patch = twoP1.neighborhood([0,1,2, 3,4,5]); patch @@ -496,6 +499,7 @@ def dimension(self): EXAMPLES:: + sage: # needs sage.libs.singular sage: P1xP1 = toric_varieties.P1xP1() sage: P1xP1.inject_variables() Defining s, t, x, y @@ -531,6 +535,7 @@ def is_smooth(self, point=None): EXAMPLES:: + sage: # needs sage.libs.singular sage: P2. = toric_varieties.P2() sage: cuspidal_curve = P2.subscheme([y^2*z - x^3]) sage: cuspidal_curve @@ -545,11 +550,12 @@ def is_smooth(self, point=None): Any sufficiently generic cubic hypersurface is smooth:: - sage: P2.subscheme([y^2*z-x^3+z^3+1/10*x*y*z]).is_smooth() + sage: P2.subscheme([y^2*z-x^3+z^3+1/10*x*y*z]).is_smooth() # needs sage.libs.singular True A more complicated example:: + sage: # needs sage.libs.singular sage: dP6. = toric_varieties.dP6() sage: disjointP1s = dP6.subscheme(x0*x3) sage: disjointP1s.is_smooth() @@ -560,6 +566,7 @@ def is_smooth(self, point=None): A smooth hypersurface in a compact singular toric variety:: + sage: # needs sage.libs.singular sage: lp = LatticePolytope([(1,0,0), (1,1,0), (1,1,1), (1,0,1), (-2,-1,-1)], ....: lattice=ToricLattice(3)) sage: X. = CPRFanoToricVariety(Delta_polar=lp) @@ -703,6 +710,7 @@ def is_schon(self): EXAMPLES:: + sage: # needs sage.libs.singular sage: P2. = toric_varieties.P2() sage: X = P2.subscheme([(x-y)^2*(x+y) + x*y*z + z^3]) sage: X.is_smooth() @@ -791,6 +799,7 @@ def dimension(self): EXAMPLES:: + sage: # needs sage.libs.singular sage: P1xP1. = toric_varieties.P1xP1() sage: P1 = P1xP1.subscheme(s0 - s1) sage: P1.dimension() @@ -799,11 +808,11 @@ def dimension(self): A more complicated example where the ambient toric variety is not smooth:: + sage: # needs sage.libs.singular sage: X. = toric_varieties.A2_Z2() sage: X.is_smooth() False - sage: Y = X.subscheme([x*y, x^2]) - sage: Y + sage: Y = X.subscheme([x*y, x^2]); Y Closed subscheme of 2-d affine toric variety defined by: x*y, x^2 @@ -836,6 +845,7 @@ def is_smooth(self, point=None): EXAMPLES:: + sage: # needs sage.libs.singular sage: A2. = toric_varieties.A2() sage: cuspidal_curve = A2.subscheme([y^2 - x^3]) sage: cuspidal_curve @@ -856,6 +866,7 @@ def is_smooth(self, point=None): A more complicated example where the ambient toric variety is not smooth:: + sage: # needs sage.libs.singular sage: X. = toric_varieties.A2_Z2() # 2-d affine space mod Z/2 sage: X.is_smooth() False diff --git a/src/sage/schemes/toric/variety.py b/src/sage/schemes/toric/variety.py index 82d2ec7769a..3635e7abbd4 100644 --- a/src/sage/schemes/toric/variety.py +++ b/src/sage/schemes/toric/variety.py @@ -66,7 +66,7 @@ sage: C2 = AffineToricVariety(quadrant, base_field=CC) sage: C2.base_ring() Complex Field with 53 bits of precision - sage: C2(1,2+i) + sage: C2(1, 2+i) # needs sage.symbolic [1.00000000000000 : 2.00000000000000 + 1.00000000000000*I] or even :: @@ -232,7 +232,7 @@ (False, True) sage: HH = P4_11133.cohomology_ring(); HH Rational cohomology ring of a 4-d CPR-Fano toric variety covered by 5 affine patches - sage: P4_11133.cohomology_basis() + sage: P4_11133.cohomology_basis() # needs sage.libs.singular (([1],), ([z4],), ([z4^2],), ([z4^3],), ([z4^4],)) Every cone defines a torus orbit closure, and hence a (co)homology class:: @@ -852,6 +852,7 @@ def _homset(self, *args, **kwds): Defn: Defined on coordinates by sending [s : t : x : y] to [s : s : x : y] + sage: # needs sage.libs.singular sage: hom_set = P1.Hom(P1) sage: sbar, tbar, xbar, ybar = P1.coordinate_ring().gens() sage: hom_set([sbar,sbar,xbar,ybar]) @@ -1082,7 +1083,7 @@ def coordinate_ring(self): sage: R = toric_varieties.A1().coordinate_ring(); R Multivariate Polynomial Ring in z over Rational Field - sage: type(R) + sage: type(R) # needs sage.libs.singular <... 'sage.rings.polynomial.multi_polynomial_libsingular.MPolynomialRing_libsingular'> """ if "_coordinate_ring" not in self.__dict__: @@ -1921,7 +1922,7 @@ def cohomology_ring(self): Multivariate Polynomial Ring in x, u, y, v, z, w over Rational Field sage: X.variable_names() ('x', 'u', 'y', 'v', 'z', 'w') - sage: X.cohomology_ring().gens() + sage: X.cohomology_ring().gens() # needs sage.libs.singular ([y + v - w], [-y + z + w], [y], [v], [z], [w]) TESTS: @@ -1930,6 +1931,7 @@ def cohomology_ring(self): potentially troublesome on unpickling, see :trac:`15050` and :trac:`15149` :: + sage: # needs sage.libs.singular sage: variety = toric_varieties.P(1) sage: a = [variety.cohomology_ring(), variety.cohomology_basis(), variety.volume_class()] sage: b = [variety.Todd_class(), variety.Chern_class(), variety.Chern_character(), variety.Kaehler_cone(), variety.Mori_cone()] @@ -1960,6 +1962,7 @@ def cohomology_basis(self, d=None): EXAMPLES:: + sage: # needs sage.libs.singular sage: X = toric_varieties.dP8() sage: X.cohomology_basis() (([1],), ([z], [y]), ([y*z],)) @@ -2004,11 +2007,11 @@ def volume_class(self): EXAMPLES:: sage: P2 = toric_varieties.P2() - sage: P2.volume_class() + sage: P2.volume_class() # needs sage.libs.singular [z^2] sage: A2_Z2 = toric_varieties.A2_Z2() - sage: A2_Z2.volume_class() + sage: A2_Z2.volume_class() # needs sage.libs.singular Traceback (most recent call last): ... ValueError: volume class does not exist @@ -2032,11 +2035,11 @@ def volume_class(self): V(t) sage: Dy = P1xP1_Z2.divisor(3); Dy V(y) - sage: P1xP1_Z2.volume_class() + sage: P1xP1_Z2.volume_class() # needs sage.libs.singular [2*t*y] sage: HH = P1xP1_Z2.cohomology_ring() - sage: HH(Dt) * HH(Dy) == 1/2 * P1xP1_Z2.volume_class() + sage: HH(Dt) * HH(Dy) == 1/2 * P1xP1_Z2.volume_class() # needs sage.libs.singular True The fractional coefficients are also necessary to match the @@ -2075,6 +2078,7 @@ def integrate(self, cohomology_class): EXAMPLES:: + sage: # needs sage.libs.singular sage: dP6 = toric_varieties.dP6() sage: HH = dP6.cohomology_ring() sage: D = [ HH(c) for c in dP6.fan(dim=1) ] @@ -2096,6 +2100,7 @@ def integrate(self, cohomology_class): If the toric variety is an orbifold, the intersection numbers are usually fractional:: + sage: # needs sage.libs.singular sage: P2_123 = toric_varieties.P2_123() sage: HH = P2_123.cohomology_ring() sage: D = [ HH(c) for c in P2_123.fan(dim=1) ] @@ -2157,6 +2162,7 @@ def Chern_class(self, deg=None): EXAMPLES:: + sage: # needs sage.libs.singular sage: X = toric_varieties.dP6() sage: X.Chern_class() [-6*w^2 + y + 2*v + 2*z + w + 1] @@ -2202,6 +2208,7 @@ def Chern_character(self, deg=None): EXAMPLES:: + sage: # needs sage.libs.singular sage: dP6 = toric_varieties.dP6() sage: dP6.Chern_character() [3*w^2 + y + 2*v + 2*z + w + 2] @@ -2241,6 +2248,7 @@ def Todd_class(self, deg=None): EXAMPLES:: + sage: # needs sage.libs.singular sage: dP6 = toric_varieties.dP6() sage: dP6.Todd_class() [-w^2 + 1/2*y + v + z + 1/2*w + 1] @@ -2250,20 +2258,21 @@ def Todd_class(self, deg=None): 1 """ Td = QQ.one() - if self.dimension() >= 1: + dim = self.dimension() + if dim >= 1: c1 = self.Chern_class(1) Td += QQ.one() / 2 * c1 - if self.dimension() >= 2: - c2 = self.Chern_class(2) - Td += QQ.one() / 12 * (c1**2 + c2) - if self.dimension() >= 3: - Td += QQ.one() / 24 * c1*c2 - if self.dimension() >= 4: - c3 = self.Chern_class(3) - c4 = self.Chern_class(4) - Td += -QQ.one() / 720 * (c1**4 - 4*c1**2*c2 - 3*c2**2 - c1*c3 + c4) - if self.dimension() >= 5: - raise NotImplementedError('Todd class is currently only implemented up to degree 4') + if dim >= 2: + c2 = self.Chern_class(2) + Td += QQ.one() / 12 * (c1**2 + c2) + if dim >= 3: + Td += QQ.one() / 24 * c1*c2 + if dim >= 4: + c3 = self.Chern_class(3) + c4 = self.Chern_class(4) + Td += -QQ.one() / 720 * (c1**4 - 4*c1**2*c2 - 3*c2**2 - c1*c3 + c4) + if dim >= 5: + raise NotImplementedError('Todd class is currently only implemented up to degree 4') if deg is None: return Td else: @@ -2287,6 +2296,7 @@ def Euler_number(self): EXAMPLES:: + sage: # needs sage.libs.singular sage: P1xP1 = toric_varieties.P1xP1() sage: P1xP1.Euler_number() 4 @@ -2318,7 +2328,7 @@ def K(self): sage: HH = dP6.cohomology_ring() sage: dP6.K() -V(x) - V(u) - V(y) - V(v) - V(z) - V(w) - sage: dP6.integrate( HH(dP6.K())^2 ) + sage: dP6.integrate( HH(dP6.K())^2 ) # needs sage.libs.singular 6 """ from sage.schemes.toric.divisor import ToricDivisor @@ -2477,18 +2487,18 @@ def _semigroup_ring(self, cone=None, names=None): EXAMPLES:: sage: A2Z2 = Cone([(0,1), (2,1)]) - sage: AffineToricVariety(A2Z2)._semigroup_ring() + sage: AffineToricVariety(A2Z2)._semigroup_ring() # needs fpylll sage.libs.singular (Multivariate Polynomial Ring in z0, z1, z2 over Rational Field, Ideal (-z0*z1 + z2^2) of Multivariate Polynomial Ring in z0, z1, z2 over Rational Field, 2-d cone in 2-d lattice M) sage: P2 = toric_varieties.P2() sage: cone = P2.fan().generating_cone(0) - sage: P2._semigroup_ring(cone) + sage: P2._semigroup_ring(cone) # needs fpylll sage.libs.singular (Multivariate Polynomial Ring in z0, z1 over Rational Field, Ideal (0) of Multivariate Polynomial Ring in z0, z1 over Rational Field, 2-d cone in 2-d lattice M) - sage: P2.change_ring(GF(101))._semigroup_ring(cone) + sage: P2.change_ring(GF(101))._semigroup_ring(cone) # needs fpylll sage.libs.singular (Multivariate Polynomial Ring in z0, z1 over Finite Field of size 101, Ideal (0) of Multivariate Polynomial Ring in z0, z1 over Finite Field of size 101, 2-d cone in 2-d lattice M) @@ -2558,7 +2568,7 @@ def Spec(self, cone=None, names=None): A more interesting example:: sage: A2Z2 = Cone([(0,1), (2,1)]) - sage: AffineToricVariety(A2Z2).Spec(names='u,v,t') + sage: AffineToricVariety(A2Z2).Spec(names='u,v,t') # needs fpylll sage.libs.singular Spectrum of Quotient of Multivariate Polynomial Ring in u, v, t over Rational Field by the ideal (-u*v + t^2) """ @@ -2592,10 +2602,10 @@ def affine_algebraic_patch(self, cone=None, names=None): sage: cone = Cone([(0,1), (2,1)]) sage: A2Z2 = AffineToricVariety(cone) - sage: A2Z2.affine_algebraic_patch() + sage: A2Z2.affine_algebraic_patch() # needs fpylll sage.libs.singular Closed subscheme of Affine Space of dimension 3 over Rational Field defined by: -z0*z1 + z2^2 - sage: A2Z2.affine_algebraic_patch(Cone([(0,1)]), names='x, y, t') + sage: A2Z2.affine_algebraic_patch(Cone([(0,1)]), names='x, y, t') # needs fpylll sage.libs.singular Closed subscheme of Affine Space of dimension 3 over Rational Field defined by: 1 """ @@ -3083,7 +3093,7 @@ def __init__(self, variety): True sage: TDiv.scheme().cohomology_ring() is X2.cohomology_ring() # this is where it gets tricky True - sage: TDiv.gen(0).Chern_character() * X2.cohomology_ring().one() + sage: TDiv.gen(0).Chern_character() * X2.cohomology_ring().one() # needs sage.libs.singular [1] """ self._variety = variety @@ -3145,6 +3155,7 @@ def _element_constructor_(self,x): EXAMPLES:: + sage: # needs sage.libs.singular sage: dP6 = toric_varieties.dP6() sage: H = dP6.cohomology_ring() sage: cone = dP6.fan().cone_containing(2,3); cone @@ -3162,6 +3173,7 @@ def _element_constructor_(self,x): coefficient is a multiple depending on the orbifold singularity. See also [CLS2011]_, Lemma 12.5.2:: + sage: # needs sage.libs.singular sage: P2_123 = toric_varieties.P2_123() sage: HH = P2_123.cohomology_ring() sage: HH(Cone([(1,0)])) * HH(Cone([(-2,-3)])) @@ -3177,6 +3189,7 @@ def _element_constructor_(self,x): Numbers will be converted into the ring:: + sage: # needs sage.libs.singular sage: P2 = toric_varieties.P2() sage: H = P2.cohomology_ring() sage: H._element_constructor_(1) @@ -3220,6 +3233,7 @@ def __call__(self, x, coerce=True): EXAMPLES:: + sage: # needs sage.libs.singular sage: P2 = toric_varieties.P2() sage: H = P2.cohomology_ring() sage: H(1) @@ -3243,7 +3257,7 @@ def gens(self): EXAMPLES:: sage: P2 = toric_varieties.P2() - sage: P2.cohomology_ring().gens() + sage: P2.cohomology_ring().gens() # needs sage.libs.singular ([z], [z], [z]) """ if "_gens" not in self.__dict__: @@ -3268,7 +3282,7 @@ def gen(self, i): EXAMPLES:: sage: P2 = toric_varieties.P2() - sage: P2.cohomology_ring().gen(2) + sage: P2.cohomology_ring().gen(2) # needs sage.libs.singular [z] """ return CohomologyClass(self, self._polynomial_ring.gen(i)) @@ -3293,9 +3307,9 @@ def is_CohomologyClass(x): sage: P2 = toric_varieties.P2() sage: HH = P2.cohomology_ring() sage: from sage.schemes.toric.variety import is_CohomologyClass - sage: is_CohomologyClass( HH.one() ) + sage: is_CohomologyClass( HH.one() ) # needs sage.libs.singular True - sage: is_CohomologyClass( HH(P2.fan(1)[0]) ) + sage: is_CohomologyClass( HH(P2.fan(1)[0]) ) # needs sage.libs.singular True sage: is_CohomologyClass('z') False @@ -3317,6 +3331,7 @@ class CohomologyClass(QuotientRingElement): EXAMPLES:: + sage: # needs sage.libs.singular sage: P2 = toric_varieties.P2() sage: P2.cohomology_ring().gen(0) [z] @@ -3346,7 +3361,7 @@ def __init__(self, cohomology_ring, representative): sage: P2 = toric_varieties.P2() sage: H = P2.cohomology_ring() sage: from sage.schemes.toric.variety import CohomologyClass - sage: CohomologyClass(H, H.defining_ideal().ring().zero() ) + sage: CohomologyClass(H, H.defining_ideal().ring().zero() ) # needs sage.libs.singular [0] """ assert representative in cohomology_ring.defining_ideal().ring(), \ @@ -3363,7 +3378,7 @@ def _repr_(self): EXAMPLES:: - sage: toric_varieties.P2().cohomology_ring().gen(0)._repr_() + sage: toric_varieties.P2().cohomology_ring().gen(0)._repr_() # needs sage.libs.singular '[z]' """ return '[' + super()._repr_() + ']' @@ -3378,8 +3393,8 @@ def _latex_(self): EXAMPLES:: - sage: cohomology_class = toric_varieties.P2().cohomology_ring().gen(0)^2/2 - sage: cohomology_class._latex_() + sage: cohomology_class = toric_varieties.P2().cohomology_ring().gen(0)^2/2 # needs sage.libs.singular + sage: cohomology_class._latex_() # needs sage.libs.singular '\\left[ \\frac{1}{2} z^{2} \\right]' """ return r'\left[ %s \right]' % latex(self.lift()) @@ -3397,9 +3412,9 @@ def deg(self): EXAMPLES:: sage: P2 = toric_varieties.P2() - sage: P2.cohomology_ring().gen(0).deg() + sage: P2.cohomology_ring().gen(0).deg() # needs sage.libs.singular 1 - sage: P2.cohomology_ring().zero().deg() + sage: P2.cohomology_ring().zero().deg() # needs sage.libs.singular -1 """ return self.lift().degree() @@ -3422,6 +3437,7 @@ def part_of_degree(self, d): EXAMPLES:: + sage: # needs sage.libs.singular sage: P1xP1 = toric_varieties.P1xP1() sage: t = P1xP1.cohomology_ring().gen(0) sage: y = P1xP1.cohomology_ring().gen(2) @@ -3458,6 +3474,7 @@ def exp(self): EXAMPLES:: + sage: # needs sage.libs.singular sage: P2 = toric_varieties.P2() sage: H_class = P2.cohomology_ring().gen(0) sage: H_class diff --git a/src/sage/schemes/toric/weierstrass_covering.py b/src/sage/schemes/toric/weierstrass_covering.py index 13e3c24b2c1..cc9caeeae4d 100644 --- a/src/sage/schemes/toric/weierstrass_covering.py +++ b/src/sage/schemes/toric/weierstrass_covering.py @@ -351,7 +351,7 @@ def WeierstrassMap_P1xP1(polynomial, variables=None): sage: f, g = WeierstrassForm_P1xP1(biquadric, [x0, x1, y0, y1]); (f,g) (-625/48*a^4 + 25/3*a^2 - 16/3, 15625/864*a^6 - 625/36*a^4 - 100/9*a^2 + 128/27) sage: X, Y, Z = WeierstrassMap_P1xP1(biquadric, [x0, x1, y0, y1]) - sage: (-Y^2 + X^3 + f*X*Z^4 + g*Z^6).reduce(R.ideal(biquadric)) + sage: (-Y^2 + X^3 + f*X*Z^4 + g*Z^6).reduce(R.ideal(biquadric)) # needs sage.libs.singular 0 sage: R = PolynomialRing(QQ, 'x,y,s,t', order='lex') @@ -361,7 +361,7 @@ def WeierstrassMap_P1xP1(polynomial, variables=None): ....: + t^2*(7*x^2+8*x*y+9*y^2)) sage: X, Y, Z = WeierstrassMap_P1xP1(equation, [x,y,s,t]) sage: f, g = WeierstrassForm_P1xP1(equation, variables=[x,y,s,t]) - sage: (-Y^2 + X^3 + f*X*Z^4 + g*Z^6).reduce(R.ideal(equation)) + sage: (-Y^2 + X^3 + f*X*Z^4 + g*Z^6).reduce(R.ideal(equation)) # needs sage.libs.singular 0 sage: R = PolynomialRing(QQ, 'x,s', order='lex') @@ -370,7 +370,7 @@ def WeierstrassMap_P1xP1(polynomial, variables=None): sage: equation = s^2*(x^2+2*x+3) + s*(4*x^2+5*x+6) + (7*x^2+8*x+9) sage: X, Y, Z = WeierstrassMap_P1xP1(equation) sage: f, g = WeierstrassForm_P1xP1(equation) - sage: (-Y^2 + X^3 + f*X*Z^4 + g*Z^6).reduce(R.ideal(equation)) + sage: (-Y^2 + X^3 + f*X*Z^4 + g*Z^6).reduce(R.ideal(equation)) # needs sage.libs.singular 0 """ x, y, s, t = _check_polynomial_P1xP1(polynomial, variables) @@ -425,7 +425,7 @@ def WeierstrassMap_P2_112(polynomial, variables=None): sage: equation = y^2 + a0*x^4 + 4*a1*x^3 + 6*a2*x^2 + 4*a3*x + a4 sage: X, Y, Z = WeierstrassMap_P2_112(equation, [x,y]) sage: f, g = WeierstrassForm_P2_112(equation, variables=[x,y]) - sage: (-Y^2 + X^3 + f*X*Z^4 + g*Z^6).reduce(R.ideal(equation)) + sage: (-Y^2 + X^3 + f*X*Z^4 + g*Z^6).reduce(R.ideal(equation)) # needs sage.libs.singular 0 Another example, this time in homogeneous coordinates:: @@ -441,7 +441,7 @@ def WeierstrassMap_P2_112(polynomial, variables=None): sage: WeierstrassForm_P2_112(C_eqn, [x,y,z,t]) (-97/48, 17/864) sage: X, Y, Z = WeierstrassMap_P2_112(C_eqn, [x,y,z,t]) - sage: (-Y^2 + X^3 - 97/48*X*Z^4 + 17/864*Z^6).reduce(C.defining_ideal()) + sage: (-Y^2 + X^3 - 97/48*X*Z^4 + 17/864*Z^6).reduce(C.defining_ideal()) # needs sage.libs.singular 0 """ x, y, z, t = _check_polynomial_P2_112(polynomial, variables) diff --git a/src/sage/schemes/toric/weierstrass_higher.py b/src/sage/schemes/toric/weierstrass_higher.py index 2a83234e6ca..6e2cc57e59d 100644 --- a/src/sage/schemes/toric/weierstrass_higher.py +++ b/src/sage/schemes/toric/weierstrass_higher.py @@ -258,7 +258,7 @@ def WeierstrassMap_P3(quadratic1, quadratic2, variables=None): (-1/4, 0) sage: ideal = R.ideal(quadratic1, quadratic2) - sage: (-Y^2 + X^3 + a*X*Z^4 + b*Z^6).reduce(ideal) + sage: (-Y^2 + X^3 + a*X*Z^4 + b*Z^6).reduce(ideal) # needs sage.libs.singular 0 TESTS:: diff --git a/src/sage/sets/family.py b/src/sage/sets/family.py index 6c007a96835..f3c3d0a7556 100644 --- a/src/sage/sets/family.py +++ b/src/sage/sets/family.py @@ -1508,8 +1508,7 @@ def __iter__(self): sage: [i for i in f] [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] """ - for i in self.enumset: - yield i + yield from self.enumset def __getitem__(self, i): """ diff --git a/src/sage/sets/finite_set_map_cy.pxd b/src/sage/sets/finite_set_map_cy.pxd index daa46c099e0..998e4f58729 100644 --- a/src/sage/sets/finite_set_map_cy.pxd +++ b/src/sage/sets/finite_set_map_cy.pxd @@ -5,29 +5,29 @@ # http://www.gnu.org/licenses/ #***************************************************************************** -cpdef fibers(f, domain) +cpdef fibers(f, domain) noexcept from sage.structure.parent cimport Parent from sage.structure.list_clone cimport ClonableIntArray cdef class FiniteSetMap_MN(ClonableIntArray): - cpdef _setimage(self, int i, int j) - cpdef _getimage(self, int i) - cpdef setimage(self, i, j) - cpdef getimage(self, i) - cpdef domain(self) - cpdef codomain(self) - cpdef image_set(self) - cpdef fibers(self) - cpdef items(self) + cpdef _setimage(self, int i, int j) noexcept + cpdef _getimage(self, int i) noexcept + cpdef setimage(self, i, j) noexcept + cpdef getimage(self, i) noexcept + cpdef domain(self) noexcept + cpdef codomain(self) noexcept + cpdef image_set(self) noexcept + cpdef fibers(self) noexcept + cpdef items(self) noexcept cpdef FiniteSetMap_MN _compose_internal_(self, FiniteSetMap_MN other, - Parent resParent) - cpdef check(self) + Parent resParent) noexcept + cpdef check(self) noexcept cdef class FiniteSetMap_Set(FiniteSetMap_MN): pass -cpdef FiniteSetMap_Set FiniteSetMap_Set_from_list(cls, parent, lst) -cpdef FiniteSetMap_Set FiniteSetMap_Set_from_dict(cls, parent, d) +cpdef FiniteSetMap_Set FiniteSetMap_Set_from_list(cls, parent, lst) noexcept +cpdef FiniteSetMap_Set FiniteSetMap_Set_from_dict(cls, parent, d) noexcept cdef class FiniteSetEndoMap_N(FiniteSetMap_MN): pass cdef class FiniteSetEndoMap_Set(FiniteSetMap_Set): pass diff --git a/src/sage/sets/finite_set_map_cy.pyx b/src/sage/sets/finite_set_map_cy.pyx index a06dc0a2bd9..1fad423fb81 100644 --- a/src/sage/sets/finite_set_map_cy.pyx +++ b/src/sage/sets/finite_set_map_cy.pyx @@ -58,7 +58,7 @@ from sage.arith.power cimport generic_power from sage.sets.set import Set_object_enumerated -cpdef fibers(f, domain): +cpdef fibers(f, domain) noexcept: r""" Returns the fibers of the function ``f`` on the finite set ``domain`` @@ -157,7 +157,7 @@ cdef class FiniteSetMap_MN(ClonableIntArray): """ return True - cpdef domain(self): + cpdef domain(self) noexcept: """ Returns the domain of ``self`` @@ -168,7 +168,7 @@ cdef class FiniteSetMap_MN(ClonableIntArray): """ return self._parent.domain() - cpdef codomain(self): + cpdef codomain(self) noexcept: """ Returns the codomain of ``self`` @@ -179,7 +179,7 @@ cdef class FiniteSetMap_MN(ClonableIntArray): """ return self._parent.codomain() - cpdef _setimage(self, int i, int j): + cpdef _setimage(self, int i, int j) noexcept: """ Set the image of ``i`` as ``j`` in ``self`` @@ -221,7 +221,7 @@ cdef class FiniteSetMap_MN(ClonableIntArray): """ self._setitem(i, j) - cpdef _getimage(self, int i): + cpdef _getimage(self, int i) noexcept: """ Returns the image of ``i`` by ``self`` @@ -239,7 +239,7 @@ cdef class FiniteSetMap_MN(ClonableIntArray): """ return self._getitem(i) - cpdef setimage(self, i, j): + cpdef setimage(self, i, j) noexcept: """ Set the image of ``i`` as ``j`` in ``self`` @@ -268,7 +268,7 @@ cdef class FiniteSetMap_MN(ClonableIntArray): """ self._setitem(int(i), int(j)) - cpdef getimage(self, i): + cpdef getimage(self, i) noexcept: """ Returns the image of ``i`` by ``self`` @@ -286,7 +286,7 @@ cdef class FiniteSetMap_MN(ClonableIntArray): """ return self._getitem(int(i)) - cpdef image_set(self): + cpdef image_set(self) noexcept: """ Returns the image set of ``self`` @@ -299,7 +299,7 @@ cdef class FiniteSetMap_MN(ClonableIntArray): """ return Set_object_enumerated(self) - cpdef fibers(self): + cpdef fibers(self) noexcept: """ Returns the fibers of ``self`` @@ -318,7 +318,7 @@ cdef class FiniteSetMap_MN(ClonableIntArray): """ return fibers(self, self.domain()) - cpdef items(self): + cpdef items(self) noexcept: """ The items of ``self`` @@ -331,7 +331,7 @@ cdef class FiniteSetMap_MN(ClonableIntArray): """ return [(i, self._getimage(i)) for i in self.domain()] - cpdef check(self): + cpdef check(self) noexcept: """ Performs checks on ``self`` @@ -362,7 +362,7 @@ cdef class FiniteSetMap_MN(ClonableIntArray): self._parent.check_element(self) cpdef FiniteSetMap_MN _compose_internal_(self, FiniteSetMap_MN other, - Parent resParent): + Parent resParent) noexcept: """ TESTS:: @@ -383,7 +383,7 @@ cdef class FiniteSetMap_MN(ClonableIntArray): return res -cpdef FiniteSetMap_Set FiniteSetMap_Set_from_list(t, parent, lst): +cpdef FiniteSetMap_Set FiniteSetMap_Set_from_list(t, parent, lst) noexcept: """ Creates a ``FiniteSetMap`` from a list @@ -406,7 +406,7 @@ cpdef FiniteSetMap_Set FiniteSetMap_Set_from_list(t, parent, lst): super(FiniteSetMap_MN, res).__init__(parent, lst) return res -cpdef FiniteSetMap_Set FiniteSetMap_Set_from_dict(t, parent, d): +cpdef FiniteSetMap_Set FiniteSetMap_Set_from_dict(t, parent, d) noexcept: """ Creates a ``FiniteSetMap`` from a dictionary @@ -491,7 +491,7 @@ cdef class FiniteSetMap_Set(FiniteSetMap_MN): parent = self._parent return parent._unrank_codomain(self._getitem(parent._rank_domain(i))) - cpdef image_set(self): + cpdef image_set(self) noexcept: """ Returns the image set of ``self`` @@ -507,7 +507,7 @@ cdef class FiniteSetMap_Set(FiniteSetMap_MN): image_i = self._parent._unrank_codomain return Set_object_enumerated([image_i(i) for i in self]) - cpdef setimage(self, i, j): + cpdef setimage(self, i, j) noexcept: """ Set the image of ``i`` as ``j`` in ``self`` @@ -550,7 +550,7 @@ cdef class FiniteSetMap_Set(FiniteSetMap_MN): parent = self._parent return self._setitem(parent._rank_domain(i), parent._rank_codomain(j)) - cpdef getimage(self, i): + cpdef getimage(self, i) noexcept: """ Returns the image of ``i`` by ``self`` @@ -568,7 +568,7 @@ cdef class FiniteSetMap_Set(FiniteSetMap_MN): parent = self._parent return parent._unrank_codomain(self._getitem(parent._rank_domain(i))) - cpdef items(self): + cpdef items(self) noexcept: """ The items of ``self`` diff --git a/src/sage/sets/pythonclass.pxd b/src/sage/sets/pythonclass.pxd index 4346d918386..70c24f64d9c 100644 --- a/src/sage/sets/pythonclass.pxd +++ b/src/sage/sets/pythonclass.pxd @@ -5,4 +5,4 @@ cdef class Set_PythonType_class(Set_generic): cdef type _type -cpdef Set_PythonType(typ) +cpdef Set_PythonType(typ) noexcept diff --git a/src/sage/sets/pythonclass.pyx b/src/sage/sets/pythonclass.pyx index bfa7f3bc617..ed8c6d940c2 100644 --- a/src/sage/sets/pythonclass.pyx +++ b/src/sage/sets/pythonclass.pyx @@ -19,7 +19,7 @@ from sage.categories.sets_cat import Sets cdef dict _type_set_cache = {} -cpdef Set_PythonType(typ): +cpdef Set_PythonType(typ) noexcept: """ Return the (unique) Parent that represents the set of Python objects of a specified type. diff --git a/src/sage/sets/recursively_enumerated_set.pxd b/src/sage/sets/recursively_enumerated_set.pxd index 48c8312456c..7df7e28ec28 100644 --- a/src/sage/sets/recursively_enumerated_set.pxd +++ b/src/sage/sets/recursively_enumerated_set.pxd @@ -16,15 +16,15 @@ cdef class RecursivelyEnumeratedSet_generic(sage.structure.parent.Parent): cdef readonly _max_depth cdef readonly _graded_component - cpdef seeds(self) - cpdef graded_component(self, depth) + cpdef seeds(self) noexcept + cpdef graded_component(self, depth) noexcept cdef class RecursivelyEnumeratedSet_symmetric(RecursivelyEnumeratedSet_generic): - cdef set _get_next_graded_component(self, set A, set B) + cdef set _get_next_graded_component(self, set A, set B) noexcept - cpdef graded_component(self, depth) + cpdef graded_component(self, depth) noexcept cdef class RecursivelyEnumeratedSet_graded(RecursivelyEnumeratedSet_generic): - cdef set _get_next_graded_component(self, set B) + cdef set _get_next_graded_component(self, set B) noexcept - cpdef graded_component(self, depth) + cpdef graded_component(self, depth) noexcept diff --git a/src/sage/sets/recursively_enumerated_set.pyx b/src/sage/sets/recursively_enumerated_set.pyx index 26bcd769b44..d79e104704f 100644 --- a/src/sage/sets/recursively_enumerated_set.pyx +++ b/src/sage/sets/recursively_enumerated_set.pyx @@ -696,7 +696,7 @@ cdef class RecursivelyEnumeratedSet_generic(Parent): L.append("with max_depth={}".format(self._max_depth)) return " ".join(L) - cpdef seeds(self): + cpdef seeds(self) noexcept: r""" Return an iterable over the seeds of ``self``. @@ -746,7 +746,7 @@ cdef class RecursivelyEnumeratedSet_generic(Parent): raise NotImplementedError("graded_component_iterator method currently" " implemented only for graded or symmetric structure") - cpdef graded_component(self, depth): + cpdef graded_component(self, depth) noexcept: r""" Return the graded component of given depth. @@ -1175,7 +1175,7 @@ cdef class RecursivelyEnumeratedSet_symmetric(RecursivelyEnumeratedSet_generic): yield B A, B = B, self._get_next_graded_component(A, B) - cpdef graded_component(self, depth): + cpdef graded_component(self, depth) noexcept: r""" Return the graded component of given depth. @@ -1242,7 +1242,7 @@ cdef class RecursivelyEnumeratedSet_symmetric(RecursivelyEnumeratedSet_generic): self._graded_component.append(C) return self._graded_component[depth] - cdef set _get_next_graded_component(self, set A, set B): + cdef set _get_next_graded_component(self, set A, set B) noexcept: r""" Return the set of elements of depth `n+1`. @@ -1397,7 +1397,7 @@ cdef class RecursivelyEnumeratedSet_graded(RecursivelyEnumeratedSet_generic): yield B B = self._get_next_graded_component(B) - cpdef graded_component(self, depth): + cpdef graded_component(self, depth) noexcept: r""" Return the graded component of given depth. @@ -1460,7 +1460,7 @@ cdef class RecursivelyEnumeratedSet_graded(RecursivelyEnumeratedSet_generic): self._graded_component.append(C) return self._graded_component[depth] - cdef set _get_next_graded_component(self, set B): + cdef set _get_next_graded_component(self, set B) noexcept: r""" Return the set of elements of depth `n+1`. diff --git a/src/sage/sets/set.py b/src/sage/sets/set.py index a6a746e9aca..2ac71e73dbf 100644 --- a/src/sage/sets/set.py +++ b/src/sage/sets/set.py @@ -1467,10 +1467,8 @@ def __iter__(self): sage: [x for x in Set(GF(3)).union(Set(GF(2)))] [0, 1, 2, 0, 1] """ - for x in self._X: - yield x - for y in self._Y: - yield y + yield from self._X + yield from self._Y def __contains__(self, x): """ diff --git a/src/sage/stats/hmm/chmm.pyx b/src/sage/stats/hmm/chmm.pyx index fe84e176a8a..aa35b8cefdc 100644 --- a/src/sage/stats/hmm/chmm.pyx +++ b/src/sage/stats/hmm/chmm.pyx @@ -38,7 +38,7 @@ from sage.misc.randstate cimport current_randstate, randstate # TODO: DELETE THIS FUNCTION WHEN MOVE Gaussian stuff to distributions.pyx!!! (next version) -cdef double random_normal(double mean, double std, randstate rstate): +cdef double random_normal(double mean, double std, randstate rstate) noexcept: r""" Return a number chosen randomly with given mean and standard deviation. @@ -446,7 +446,7 @@ cdef class GaussianHiddenMarkovModel(HiddenMarkovModel): return obs, states - cdef probability_init(self): + cdef probability_init(self) noexcept: r""" Used internally to compute caching information that makes certain computations in the Baum-Welch algorithm faster. This @@ -458,7 +458,7 @@ cdef class GaussianHiddenMarkovModel(HiddenMarkovModel): self.prob[2*i] = 1.0/(sqrt2pi*self.B[2*i+1]) self.prob[2*i+1] = -1.0/(2*self.B[2*i+1]*self.B[2*i+1]) - cdef double random_sample(self, int state, randstate rstate): + cdef double random_sample(self, int state, randstate rstate) noexcept: r""" Return a random sample from the normal distribution associated to the given state. @@ -478,7 +478,7 @@ cdef class GaussianHiddenMarkovModel(HiddenMarkovModel): """ return random_normal(self.B._values[state*2], self.B._values[state*2+1], rstate) - cdef double probability_of(self, int state, double observation): + cdef double probability_of(self, int state, double observation) noexcept: r""" Return a useful continuous analogue of "the probability b_j(o)" of seeing the given observation given that we're in the given @@ -716,7 +716,7 @@ cdef class GaussianHiddenMarkovModel(HiddenMarkovModel): return state_sequence, mx - cdef TimeSeries _backward_scale_all(self, TimeSeries obs, TimeSeries scale): + cdef TimeSeries _backward_scale_all(self, TimeSeries obs, TimeSeries scale) noexcept: r""" This function returns the matrix beta_t(i), and is used internally as part of the Baum-Welch algorithm. @@ -756,7 +756,7 @@ cdef class GaussianHiddenMarkovModel(HiddenMarkovModel): t -= 1 return beta - cdef _forward_scale_all(self, TimeSeries obs): + cdef _forward_scale_all(self, TimeSeries obs) noexcept: r""" Return scaled values alpha_t(i), the sequence of scalings, and the log probability. @@ -821,7 +821,7 @@ cdef class GaussianHiddenMarkovModel(HiddenMarkovModel): # Termination return alpha, scale, log_probability - cdef TimeSeries _baum_welch_xi(self, TimeSeries alpha, TimeSeries beta, TimeSeries obs): + cdef TimeSeries _baum_welch_xi(self, TimeSeries alpha, TimeSeries beta, TimeSeries obs) noexcept: r""" Used internally to compute the scaled quantity xi_t(i,j) appearing in the Baum-Welch reestimation algorithm. @@ -1249,7 +1249,7 @@ cdef class GaussianMixtureHiddenMarkovModel(GaussianHiddenMarkovModel): """ return list(self.mixture) - cdef double random_sample(self, int state, randstate rstate): + cdef double random_sample(self, int state, randstate rstate) noexcept: r""" Return a random sample from the normal distribution associated to the given state. @@ -1270,7 +1270,7 @@ cdef class GaussianMixtureHiddenMarkovModel(GaussianHiddenMarkovModel): cdef GaussianMixtureDistribution G = self.mixture[state] return G._sample(rstate) - cdef double probability_of(self, int state, double observation): + cdef double probability_of(self, int state, double observation) noexcept: r""" Return the probability b_j(o) of see the given observation o (=observation) given that we're in the given state j (=state). @@ -1292,7 +1292,7 @@ cdef class GaussianMixtureHiddenMarkovModel(GaussianHiddenMarkovModel): return G.prob(observation) cdef TimeSeries _baum_welch_mixed_gamma(self, TimeSeries alpha, TimeSeries beta, - TimeSeries obs, int j): + TimeSeries obs, int j) noexcept: r""" Let gamma_t(j,m) be the m-component (in the mixture) of the probability of being in state j at time t, given the diff --git a/src/sage/stats/hmm/distributions.pxd b/src/sage/stats/hmm/distributions.pxd index b07435d3abb..7d613b22a64 100644 --- a/src/sage/stats/hmm/distributions.pxd +++ b/src/sage/stats/hmm/distributions.pxd @@ -22,10 +22,10 @@ cdef class GaussianMixtureDistribution(Distribution): cdef TimeSeries c0, c1, param cdef IntList fixed - cdef double _sample(self, randstate rstate) - cpdef double prob(self, double x) - cpdef double prob_m(self, double x, int m) - cpdef is_fixed(self, i=?) + cdef double _sample(self, randstate rstate) noexcept + cpdef double prob(self, double x) noexcept + cpdef double prob_m(self, double x, int m) noexcept + cpdef is_fixed(self, i=?) noexcept diff --git a/src/sage/stats/hmm/distributions.pyx b/src/sage/stats/hmm/distributions.pyx index 65a743e26f1..ebb85739b2e 100644 --- a/src/sage/stats/hmm/distributions.pyx +++ b/src/sage/stats/hmm/distributions.pyx @@ -34,7 +34,7 @@ from sage.stats.time_series cimport TimeSeries -cdef double random_normal(double mean, double std, randstate rstate): +cdef double random_normal(double mean, double std, randstate rstate) noexcept: r""" Return a floating point number chosen from the normal distribution with given mean and standard deviation, using the given randstate. @@ -282,7 +282,7 @@ cdef class GaussianMixtureDistribution(Distribution): """ return self.c0._length - cpdef is_fixed(self, i=None): + cpdef is_fixed(self, i=None) noexcept: r""" Return whether or not this :class:`GaussianMixtureDistribution` is fixed when using Baum-Welch to update the corresponding HMM. @@ -434,7 +434,7 @@ cdef class GaussianMixtureDistribution(Distribution): T._values[i] = self._sample(rstate) return T - cdef double _sample(self, randstate rstate): + cdef double _sample(self, randstate rstate) noexcept: r""" Used internally to compute a sample from this distribution quickly. @@ -459,7 +459,7 @@ cdef class GaussianMixtureDistribution(Distribution): return random_normal(self.param._values[3*n+1], self.param._values[3*n+2], rstate) raise RuntimeError("invalid probability distribution") - cpdef double prob(self, double x): + cpdef double prob(self, double x) noexcept: r""" Return the probability of `x`. @@ -495,7 +495,7 @@ cdef class GaussianMixtureDistribution(Distribution): s += self.c0._values[n]*exp((x-mu)*(x-mu)*self.c1._values[n]) return s - cpdef double prob_m(self, double x, int m): + cpdef double prob_m(self, double x, int m) noexcept: r""" Return the probability of `x` using just the `m`-th summand. diff --git a/src/sage/stats/hmm/hmm.pxd b/src/sage/stats/hmm/hmm.pxd index 1abcb95392b..f67de100a92 100644 --- a/src/sage/stats/hmm/hmm.pxd +++ b/src/sage/stats/hmm/hmm.pxd @@ -13,5 +13,5 @@ cdef class HiddenMarkovModel: cdef int N cdef TimeSeries A, pi - cdef TimeSeries _baum_welch_gamma(self, TimeSeries alpha, TimeSeries beta) + cdef TimeSeries _baum_welch_gamma(self, TimeSeries alpha, TimeSeries beta) noexcept diff --git a/src/sage/stats/hmm/hmm.pyx b/src/sage/stats/hmm/hmm.pyx index f48d0c9e4db..86de50cc1a3 100644 --- a/src/sage/stats/hmm/hmm.pyx +++ b/src/sage/stats/hmm/hmm.pyx @@ -224,7 +224,7 @@ cdef class HiddenMarkovModel: # Some internal functions used for various general # HMM algorithms. ######################################################### - cdef TimeSeries _baum_welch_gamma(self, TimeSeries alpha, TimeSeries beta): + cdef TimeSeries _baum_welch_gamma(self, TimeSeries alpha, TimeSeries beta) noexcept: r""" Used internally to compute the scaled quantity gamma_t(j) appearing in the Baum-Welch reestimation algorithm. @@ -810,7 +810,7 @@ cdef class DiscreteHiddenMarkovModel(HiddenMarkovModel): # Emission symbol mapping, so change our intlist into a list of symbols return self._IntList_to_emission_symbols(obs), states - cdef int _gen_symbol(self, int q, double r): + cdef int _gen_symbol(self, int q, double r) noexcept: r""" Generate a symbol in state q using the randomly chosen floating point number r, which should be between 0 and 1. @@ -897,7 +897,7 @@ cdef class DiscreteHiddenMarkovModel(HiddenMarkovModel): else: return self._viterbi(obs) - cpdef _viterbi(self, IntList obs): + cpdef _viterbi(self, IntList obs) noexcept: r""" Used internally to compute the viterbi path, without rescaling. This can be useful for short sequences. @@ -977,7 +977,7 @@ cdef class DiscreteHiddenMarkovModel(HiddenMarkovModel): return state_sequence, log(mx) - cpdef _viterbi_scale(self, IntList obs): + cpdef _viterbi_scale(self, IntList obs) noexcept: r""" Used internally to compute the viterbi path with rescaling. @@ -1061,7 +1061,7 @@ cdef class DiscreteHiddenMarkovModel(HiddenMarkovModel): return state_sequence, mx - cdef TimeSeries _backward_scale_all(self, IntList obs, TimeSeries scale): + cdef TimeSeries _backward_scale_all(self, IntList obs, TimeSeries scale) noexcept: r""" Return the scaled matrix of values `\beta_t(i)` that appear in the backtracking algorithm. This function is used internally @@ -1108,7 +1108,7 @@ cdef class DiscreteHiddenMarkovModel(HiddenMarkovModel): t -= 1 return beta - cdef _forward_scale_all(self, IntList obs): + cdef _forward_scale_all(self, IntList obs) noexcept: r""" Return scaled values alpha_t(i), the sequence of scalings, and the log probability. @@ -1169,7 +1169,7 @@ cdef class DiscreteHiddenMarkovModel(HiddenMarkovModel): # Termination return alpha, scale, log_probability - cdef TimeSeries _baum_welch_xi(self, TimeSeries alpha, TimeSeries beta, IntList obs): + cdef TimeSeries _baum_welch_xi(self, TimeSeries alpha, TimeSeries beta, IntList obs) noexcept: r""" Used internally to compute the scaled quantity xi_t(i,j) appearing in the Baum-Welch reestimation algorithm. diff --git a/src/sage/stats/hmm/util.pxd b/src/sage/stats/hmm/util.pxd index b0d399d9aaf..84a0e201a1b 100644 --- a/src/sage/stats/hmm/util.pxd +++ b/src/sage/stats/hmm/util.pxd @@ -1,7 +1,7 @@ from sage.stats.time_series cimport TimeSeries cdef class HMM_Util: - cpdef normalize_probability_TimeSeries(self, TimeSeries T, Py_ssize_t i, Py_ssize_t j) - cpdef TimeSeries initial_probs_to_TimeSeries(self, pi, bint normalize) - cpdef TimeSeries state_matrix_to_TimeSeries(self, A, int N, bint normalize) + cpdef normalize_probability_TimeSeries(self, TimeSeries T, Py_ssize_t i, Py_ssize_t j) noexcept + cpdef TimeSeries initial_probs_to_TimeSeries(self, pi, bint normalize) noexcept + cpdef TimeSeries state_matrix_to_TimeSeries(self, A, int N, bint normalize) noexcept diff --git a/src/sage/stats/hmm/util.pyx b/src/sage/stats/hmm/util.pyx index 553eb997364..fc849742b80 100644 --- a/src/sage/stats/hmm/util.pyx +++ b/src/sage/stats/hmm/util.pyx @@ -22,7 +22,7 @@ cdef class HMM_Util: """ A class used in order to share cdef's methods between different files. """ - cpdef normalize_probability_TimeSeries(self, TimeSeries T, Py_ssize_t i, Py_ssize_t j): + cpdef normalize_probability_TimeSeries(self, TimeSeries T, Py_ssize_t i, Py_ssize_t j) noexcept: """ This function is used internally by the Hidden Markov Models code. @@ -86,7 +86,7 @@ cdef class HMM_Util: - cpdef TimeSeries initial_probs_to_TimeSeries(self, pi, bint normalize): + cpdef TimeSeries initial_probs_to_TimeSeries(self, pi, bint normalize) noexcept: """ This function is used internally by the __init__ methods of various Hidden Markov Models. @@ -125,7 +125,7 @@ cdef class HMM_Util: return T - cpdef TimeSeries state_matrix_to_TimeSeries(self, A, int N, bint normalize): + cpdef TimeSeries state_matrix_to_TimeSeries(self, A, int N, bint normalize) noexcept: """ This function is used internally by the ``__init__`` methods of Hidden Markov Models to make a transition matrix from ``A``. diff --git a/src/sage/stats/intlist.pxd b/src/sage/stats/intlist.pxd index 9799b5c0a29..d63971aac14 100644 --- a/src/sage/stats/intlist.pxd +++ b/src/sage/stats/intlist.pxd @@ -9,5 +9,5 @@ cdef class IntList: cdef int* _values cdef Py_ssize_t _length - cpdef int prod(self) - cpdef int sum(self) + cpdef int prod(self) noexcept + cpdef int sum(self) noexcept diff --git a/src/sage/stats/intlist.pyx b/src/sage/stats/intlist.pyx index 1bfc74aed96..ce5abfc8b7b 100644 --- a/src/sage/stats/intlist.pyx +++ b/src/sage/stats/intlist.pyx @@ -323,7 +323,7 @@ cdef class IntList: cdef Py_ssize_t i return [self._values[i] for i in range(self._length)] - cpdef int sum(self): + cpdef int sum(self) noexcept: """ Return the sum of the entries of ``self``. @@ -347,7 +347,7 @@ cdef class IntList: sig_off() return s - cpdef int prod(self): + cpdef int prod(self) noexcept: """ Return the product of the entries of ``self``. @@ -544,7 +544,7 @@ cdef class IntList: return self.time_series().plot_histogram(*args, **kwds) -cdef IntList new_int_list(Py_ssize_t length): +cdef IntList new_int_list(Py_ssize_t length) noexcept: """ Function that is used internally to quickly create a new intlist without initializing any of the allocated memory. diff --git a/src/sage/stats/time_series.pxd b/src/sage/stats/time_series.pxd index 635b7faeaa9..7a044b52da9 100644 --- a/src/sage/stats/time_series.pxd +++ b/src/sage/stats/time_series.pxd @@ -1,5 +1,5 @@ cdef class TimeSeries: cdef double* _values cdef Py_ssize_t _length - cpdef rescale(self, double s) - cpdef double sum(self) + cpdef rescale(self, double s) noexcept + cpdef double sum(self) noexcept diff --git a/src/sage/stats/time_series.pyx b/src/sage/stats/time_series.pyx index 1ef69068015..ce51e65baab 100644 --- a/src/sage/stats/time_series.pyx +++ b/src/sage/stats/time_series.pyx @@ -892,7 +892,7 @@ cdef class TimeSeries: t._values[i] = self._values[i*k] return t - cpdef rescale(self, double s): + cpdef rescale(self, double s) noexcept: r""" Change ``self`` by multiplying every value in the series by ``s``. @@ -1223,7 +1223,7 @@ cdef class TimeSeries: t._values[i] = s return t - cpdef double sum(self): + cpdef double sum(self) noexcept: r""" Return the sum of all the entries of ``self``. @@ -2514,7 +2514,7 @@ cdef class TimeSeries: return y -cdef new_time_series(Py_ssize_t length): +cdef new_time_series(Py_ssize_t length) noexcept: r""" Return a new uninitialized time series of the given length. The entries of the time series are garbage. diff --git a/src/sage/structure/category_object.pxd b/src/sage/structure/category_object.pxd index 83d3d4967d4..6bd450c4f68 100644 --- a/src/sage/structure/category_object.pxd +++ b/src/sage/structure/category_object.pxd @@ -10,7 +10,7 @@ from sage.structure.sage_object cimport SageObject -cpdef check_default_category(default_category, category) +cpdef check_default_category(default_category, category) noexcept cdef class CategoryObject(SageObject): cdef public dict _cached_methods @@ -21,7 +21,7 @@ cdef class CategoryObject(SageObject): cdef object __weakref__ cdef long _hash_value - cdef getattr_from_category(self, name) + cdef getattr_from_category(self, name) noexcept -cpdef normalize_names(Py_ssize_t ngens, names) +cpdef normalize_names(Py_ssize_t ngens, names) noexcept cpdef bint certify_names(names) except -1 diff --git a/src/sage/structure/category_object.pyx b/src/sage/structure/category_object.pyx index c06933494dc..3d187a13dba 100644 --- a/src/sage/structure/category_object.pyx +++ b/src/sage/structure/category_object.pyx @@ -63,7 +63,7 @@ from sage.misc.cachefunc import cached_method from sage.structure.dynamic_class import DynamicMetaclass -cpdef inline check_default_category(default_category, category): +cpdef inline check_default_category(default_category, category) noexcept: ## The resulting category is guaranteed to be ## a sub-category of the default. if category is None: @@ -840,7 +840,7 @@ cdef class CategoryObject(SageObject): """ return self.getattr_from_category(name) - cdef getattr_from_category(self, name): + cdef getattr_from_category(self, name) noexcept: # Lookup a method or attribute from the category abstract classes. # See __getattr__ above for documentation. try: @@ -905,7 +905,7 @@ cdef class CategoryObject(SageObject): """ return dir_with_other_class(self, self.category().parent_class) -cpdef normalize_names(Py_ssize_t ngens, names): +cpdef normalize_names(Py_ssize_t ngens, names) noexcept: r""" Return a tuple of strings of variable names of length ngens given the input names. diff --git a/src/sage/structure/coerce.pxd b/src/sage/structure/coerce.pxd index e070d1c32e4..8856950d685 100644 --- a/src/sage/structure/coerce.pxd +++ b/src/sage/structure/coerce.pxd @@ -1,11 +1,11 @@ from .parent cimport Parent from .coerce_dict cimport TripleDict -cpdef py_scalar_parent(py_type) -cpdef py_scalar_to_element(py) +cpdef py_scalar_parent(py_type) noexcept +cpdef py_scalar_to_element(py) noexcept cpdef bint parent_is_integers(P) except -1 -cpdef bint is_numpy_type(t) -cpdef bint is_mpmath_type(t) +cpdef bint is_numpy_type(t) noexcept +cpdef bint is_mpmath_type(t) noexcept cdef class CoercionModel: @@ -17,26 +17,26 @@ cdef class CoercionModel: # This MUST be a mapping to actions. cdef readonly TripleDict _action_maps - cpdef canonical_coercion(self, x, y) - cpdef bin_op(self, x, y, op) - cpdef richcmp(self, x, y, int op) + cpdef canonical_coercion(self, x, y) noexcept + cpdef bin_op(self, x, y, op) noexcept + cpdef richcmp(self, x, y, int op) noexcept - cpdef coercion_maps(self, R, S) - cpdef discover_coercion(self, R, S) - cpdef verify_coercion_maps(self, R, S, homs, bint fix=*) - cpdef verify_action(self, action, R, S, op, bint fix=*) + cpdef coercion_maps(self, R, S) noexcept + cpdef discover_coercion(self, R, S) noexcept + cpdef verify_coercion_maps(self, R, S, homs, bint fix=*) noexcept + cpdef verify_action(self, action, R, S, op, bint fix=*) noexcept - cpdef get_action(self, R, S, op=*, r=*, s=*) - cpdef discover_action(self, R, S, op, r=*, s=*) + cpdef get_action(self, R, S, op=*, r=*, s=*) noexcept + cpdef discover_action(self, R, S, op, r=*, s=*) noexcept cdef bint _record_exceptions - cpdef _record_exception(self) + cpdef _record_exception(self) noexcept cdef readonly list _exception_stack cdef bint _exceptions_cleared cdef TripleDict _division_parents - cpdef analyse(self, xp, yp, op=*) - cpdef division_parent(self, Parent P) + cpdef analyse(self, xp, yp, op=*) noexcept + cpdef division_parent(self, Parent P) noexcept # Unique global coercion_model instance diff --git a/src/sage/structure/coerce.pyx b/src/sage/structure/coerce.pyx index d8c3f684217..6dc194c5cf9 100644 --- a/src/sage/structure/coerce.pyx +++ b/src/sage/structure/coerce.pyx @@ -100,7 +100,7 @@ import traceback from fractions import Fraction cdef type FractionType = Fraction -cpdef py_scalar_parent(py_type): +cpdef py_scalar_parent(py_type) noexcept: """ Returns the Sage equivalent of the given python type, if one exists. If there is no equivalent, return None. @@ -184,7 +184,7 @@ cpdef py_scalar_parent(py_type): else: return None -cpdef py_scalar_to_element(x): +cpdef py_scalar_to_element(x) noexcept: """ Convert ``x`` to a Sage :class:`~sage.structure.element.Element` if possible. @@ -415,7 +415,7 @@ def parent_is_real_numerical(P): return P._is_real_numerical() -cpdef bint is_numpy_type(t): +cpdef bint is_numpy_type(t) noexcept: """ Return ``True`` if and only if `t` is a type whose name starts with ``numpy.`` @@ -466,7 +466,7 @@ cpdef bint is_numpy_type(t): return True return False -cpdef bint is_mpmath_type(t): +cpdef bint is_mpmath_type(t) noexcept: r""" Check whether the type ``t`` is a type whose name starts with either ``mpmath.`` or ``sage.libs.mpmath.``. @@ -688,7 +688,7 @@ cdef class CoercionModel: self._exceptions_cleared = True self._exception_stack = [] - cpdef _record_exception(self): + cpdef _record_exception(self) noexcept: r""" Pushes the last exception that occurred onto the stack for later reference, for internal use. @@ -923,7 +923,7 @@ cdef class CoercionModel: print("Result lives in {}".format(res)) return res - cpdef analyse(self, xp, yp, op=mul): + cpdef analyse(self, xp, yp, op=mul) noexcept: """ Emulate the process of doing arithmetic between xp and yp, returning a list of steps and the parent that the result will live in. @@ -1088,7 +1088,7 @@ cdef class CoercionModel: base = parent(self.canonical_coercion(a, b)[0]) return base - cpdef division_parent(self, Parent P): + cpdef division_parent(self, Parent P) noexcept: r""" Deduces where the result of division in ``P`` lies by calculating the inverse of ``P.one()`` or ``P.an_element()``. @@ -1127,7 +1127,7 @@ cdef class CoercionModel: self._division_parents.set(P, None, None, ret) return ret - cpdef bin_op(self, x, y, op): + cpdef bin_op(self, x, y, op) noexcept: """ Execute the operation ``op`` on `x` and `y`. @@ -1275,7 +1275,7 @@ cdef class CoercionModel: # This causes so much headache. raise bin_op_exception(op, x, y) - cpdef canonical_coercion(self, x, y): + cpdef canonical_coercion(self, x, y) noexcept: r""" Given two elements `x` and `y`, with parents `S` and `R` respectively, find a common parent `Z` such that there are coercions @@ -1421,7 +1421,7 @@ cdef class CoercionModel: raise TypeError("no common canonical parent for objects with parents: '%s' and '%s'"%(xp, yp)) - cpdef coercion_maps(self, R, S): + cpdef coercion_maps(self, R, S) noexcept: r""" Give two parents `R` and `S`, return a pair of coercion maps `f: R \rightarrow Z` and `g: S \rightarrow Z` , if such a `Z` @@ -1570,7 +1570,7 @@ cdef class CoercionModel: self._coercion_maps.set(S, R, None, swap) return homs - cpdef verify_coercion_maps(self, R, S, homs, bint fix=False): + cpdef verify_coercion_maps(self, R, S, homs, bint fix=False) noexcept: """ Make sure this is a valid pair of homomorphisms from `R` and `S` to a common parent. This function is used to protect the user against buggy parents. @@ -1639,7 +1639,7 @@ cdef class CoercionModel: return R_map, S_map - cpdef discover_coercion(self, R, S): + cpdef discover_coercion(self, R, S) noexcept: """ This actually implements the finding of coercion maps as described in the :meth:`coercion_maps` method. @@ -1718,7 +1718,7 @@ cdef class CoercionModel: return None - cpdef get_action(self, R, S, op=mul, r=None, s=None): + cpdef get_action(self, R, S, op=mul, r=None, s=None) noexcept: """ Get the action of R on S or S on R associated to the operation op. @@ -1759,7 +1759,7 @@ cdef class CoercionModel: self._action_maps.set(R, S, op, action) return action - cpdef verify_action(self, action, R, S, op, bint fix=True): + cpdef verify_action(self, action, R, S, op, bint fix=True) noexcept: r""" Verify that ``action`` takes an element of R on the left and S on the right, raising an error if not. @@ -1818,7 +1818,7 @@ cdef class CoercionModel: return action - cpdef discover_action(self, R, S, op, r=None, s=None): + cpdef discover_action(self, R, S, op, r=None, s=None) noexcept: """ INPUT: @@ -1956,7 +1956,7 @@ cdef class CoercionModel: return None - cpdef richcmp(self, x, y, int op): + cpdef richcmp(self, x, y, int op) noexcept: """ Given two arbitrary objects ``x`` and ``y``, coerce them to a common parent and compare them using rich comparison operator diff --git a/src/sage/structure/coerce_actions.pyx b/src/sage/structure/coerce_actions.pyx index 6df2aec6695..7b1d9491f56 100644 --- a/src/sage/structure/coerce_actions.pyx +++ b/src/sage/structure/coerce_actions.pyx @@ -26,10 +26,10 @@ from sage.categories.action cimport InverseAction, PrecomposedAction from sage.arith.long cimport integer_check_long -cdef _record_exception(): +cdef _record_exception() noexcept: coercion_model._record_exception() -cdef inline an_element(R): +cdef inline an_element(R) noexcept: if isinstance(R, Parent): return R.an_element() else: @@ -118,7 +118,7 @@ cdef class ActOnAction(GenericAction): """ Class for actions defined via the _act_on_ method. """ - cpdef _act_(self, g, x): + cpdef _act_(self, g, x) noexcept: """ TESTS:: @@ -140,7 +140,7 @@ cdef class ActedUponAction(GenericAction): """ Class for actions defined via the _acted_upon_ method. """ - cpdef _act_(self, g, x): + cpdef _act_(self, g, x) noexcept: """ TESTS:: @@ -586,7 +586,7 @@ cdef class ModuleAction(Action): cdef class LeftModuleAction(ModuleAction): - cpdef _act_(self, g, a): + cpdef _act_(self, g, a) noexcept: """ A left module action is an action that takes the ring element as the first argument (the left side) and the module element as the second @@ -623,7 +623,7 @@ cdef class LeftModuleAction(ModuleAction): cdef class RightModuleAction(ModuleAction): - cpdef _act_(self, g, a): + cpdef _act_(self, g, a) noexcept: """ A right module action is an action that takes the module element as the first argument (the left side) and the ring element as the second @@ -743,7 +743,7 @@ cdef class IntegerMulAction(IntegerAction): test = m + (-m) # make sure addition and negation is allowed super().__init__(Z, M, is_left, operator.mul) - cpdef _act_(self, nn, a): + cpdef _act_(self, nn, a) noexcept: """ EXAMPLES: @@ -879,7 +879,7 @@ cdef class IntegerPowAction(IntegerAction): raise TypeError(f"no integer powering action defined on {M}") super().__init__(Z, M, False, operator.pow) - cpdef _act_(self, n, a): + cpdef _act_(self, n, a) noexcept: """ EXAMPLES: @@ -916,7 +916,7 @@ cdef class IntegerPowAction(IntegerAction): return "Integer Powering" -cdef inline fast_mul(a, n): +cdef inline fast_mul(a, n) noexcept: if n < 0: n = -n a = -a @@ -935,7 +935,7 @@ cdef inline fast_mul(a, n): n = n >> 1 return sum -cdef inline fast_mul_long(a, long s): +cdef inline fast_mul_long(a, long s) noexcept: # It's important to change the signed s to an unsigned n, # since -LONG_MIN = LONG_MIN. See Issue #17844. cdef unsigned long n diff --git a/src/sage/structure/coerce_dict.pxd b/src/sage/structure/coerce_dict.pxd index be14effa0f8..8542545a2f8 100644 --- a/src/sage/structure/coerce_dict.pxd +++ b/src/sage/structure/coerce_dict.pxd @@ -18,8 +18,8 @@ cdef class MonoDict: cdef bint weak_values cdef eraser - cdef mono_cell* lookup(self, PyObject* key) - cdef get(self, k) + cdef mono_cell* lookup(self, PyObject* key) noexcept + cdef get(self, k) noexcept cdef int set(self, k, value) except -1 cdef int resize(self) except -1 @@ -44,7 +44,7 @@ cdef class TripleDict: cdef bint weak_values cdef eraser - cdef triple_cell* lookup(self, PyObject* key1, PyObject* key2, PyObject* key3) - cdef get(self, k1, k2, k3) + cdef triple_cell* lookup(self, PyObject* key1, PyObject* key2, PyObject* key3) noexcept + cdef get(self, k1, k2, k3) noexcept cdef int set(self, k1, k2, k3, value) except -1 cdef int resize(self) except -1 diff --git a/src/sage/structure/coerce_dict.pyx b/src/sage/structure/coerce_dict.pyx index ef86c6af35c..269f1be5fd5 100644 --- a/src/sage/structure/coerce_dict.pyx +++ b/src/sage/structure/coerce_dict.pyx @@ -79,7 +79,7 @@ cdef extern from "sage/cpython/pyx_visit.h": cdef type KeyedRef, ref from weakref import KeyedRef, ref -cdef inline bint is_dead_keyedref(x): +cdef inline bint is_dead_keyedref(x) noexcept: """ Check whether ``x`` is a ``KeyedRef`` which is dead. """ @@ -93,7 +93,7 @@ cdef object dummy = object() cdef PyObject* deleted_key = dummy -cdef inline bint valid(PyObject* obj): +cdef inline bint valid(PyObject* obj) noexcept: """ Check whether ``obj`` points to a valid object """ @@ -110,7 +110,7 @@ cdef class ObjectWrapper: cdef PyObject* obj -cdef inline ObjectWrapper wrap(obj): +cdef inline ObjectWrapper wrap(obj) noexcept: """ Wrap a given Python object in an :class:`ObjectWrapper`. """ @@ -126,7 +126,7 @@ cdef inline PyObject* unwrap(w) except? NULL: return (w).obj -cdef extract_mono_cell(mono_cell* cell): +cdef extract_mono_cell(mono_cell* cell) noexcept: """ Take the refcounted components from a mono_cell, put them in a tuple and return it. The mono_cell itself is marked as "freed". @@ -151,7 +151,7 @@ cdef extract_mono_cell(mono_cell* cell): return t -cdef extract_triple_cell(triple_cell* cell): +cdef extract_triple_cell(triple_cell* cell) noexcept: # See extract_mono_cell for documentation assert valid(cell.key_id1) t = PyTuple_New(4) @@ -425,7 +425,7 @@ cdef class MonoDict: - Simon King (2013-02) - Nils Bruin (2013-11) """ - cdef mono_cell* lookup(self, PyObject* key): + cdef mono_cell* lookup(self, PyObject* key) noexcept: """ Return a pointer to where ``key`` should be stored in this :class:`MonoDict`. @@ -644,7 +644,7 @@ cdef class MonoDict: """ return self.get(k) - cdef get(self, k): + cdef get(self, k) noexcept: cdef mono_cell* cursor = self.lookup(k) if not valid(cursor.key_id): raise KeyError(k) @@ -844,7 +844,7 @@ cdef class MonoDict: # and we have to replicate here) is the "eraser" which in its closure # stores a reference back to the dictionary itself (meaning that # MonoDicts only disappear on cyclic GC). -cdef int MonoDict_traverse(MonoDict self, visitproc visit, void* arg): +cdef int MonoDict_traverse(MonoDict self, visitproc visit, void* arg) noexcept: if not self.mask: return 0 Py_VISIT3(self.eraser, visit, arg) @@ -856,7 +856,7 @@ cdef int MonoDict_traverse(MonoDict self, visitproc visit, void* arg): Py_VISIT3(cursor.value, visit, arg) -cdef int MonoDict_clear(MonoDict self): +cdef int MonoDict_clear(MonoDict self) noexcept: """ We clear a monodict by taking first taking away the table before dereffing its contents. That shortcuts callbacks, so we deref the @@ -1123,7 +1123,7 @@ cdef class TripleDict: - Nils Bruin, 2013-11 """ - cdef triple_cell* lookup(self, PyObject* key1, PyObject* key2, PyObject* key3): + cdef triple_cell* lookup(self, PyObject* key1, PyObject* key2, PyObject* key3) noexcept: """ Return a pointer to where ``(key1, key2, key3)`` should be stored in this :class:`MonoDict`. @@ -1320,7 +1320,7 @@ cdef class TripleDict: raise KeyError(k) return self.get(k1, k2, k3) - cdef get(self, k1, k2, k3): + cdef get(self, k1, k2, k3) noexcept: cdef triple_cell* cursor = self.lookup(k1, k2, k3) if not valid(cursor.key_id1): raise KeyError((k1, k2, k3)) @@ -1524,7 +1524,7 @@ cdef class TripleDict: # and we have to replicate here) is the "eraser" which in its closure # stores a reference back to the dictionary itself (meaning that # TripleDicts only disappear on cyclic GC). -cdef int TripleDict_traverse(TripleDict self, visitproc visit, void* arg): +cdef int TripleDict_traverse(TripleDict self, visitproc visit, void* arg) noexcept: if not self.mask: return 0 Py_VISIT3(self.eraser, visit, arg) @@ -1538,7 +1538,7 @@ cdef int TripleDict_traverse(TripleDict self, visitproc visit, void* arg): Py_VISIT3(cursor.value, visit, arg) -cdef int TripleDict_clear(TripleDict self): +cdef int TripleDict_clear(TripleDict self) noexcept: if not self.mask: return 0 cdef size_t mask = self.mask diff --git a/src/sage/structure/coerce_maps.pxd b/src/sage/structure/coerce_maps.pxd index 0afc1a96adb..e3e969d0266 100644 --- a/src/sage/structure/coerce_maps.pxd +++ b/src/sage/structure/coerce_maps.pxd @@ -24,4 +24,4 @@ cdef class CallableConvertMap(Map): cdef _func -cdef Map CCallableConvertMap(domain, codomain, void* func, name) +cdef Map CCallableConvertMap(domain, codomain, void* func, name) noexcept diff --git a/src/sage/structure/coerce_maps.pyx b/src/sage/structure/coerce_maps.pyx index 1c1464a7899..be6d4807297 100644 --- a/src/sage/structure/coerce_maps.pyx +++ b/src/sage/structure/coerce_maps.pyx @@ -91,7 +91,7 @@ cdef class DefaultConvertMap(Map): """ return self._repr_type_str or ("Coercion" if self._is_coercion else "Conversion") - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Create an element of the codomain from a single element of the domain. @@ -110,7 +110,7 @@ cdef class DefaultConvertMap(Map): print(type(C._element_constructor), C._element_constructor) raise - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ Create an element of the codomain from an element of the domain, with extra arguments. @@ -152,7 +152,7 @@ cdef class DefaultConvertMap_unique(DefaultConvertMap): used when the element_constructor is a bound method (whose self argument is assumed to be bound to the codomain). """ - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: cdef Parent C = self._codomain try: return C._element_constructor(x) @@ -162,7 +162,7 @@ cdef class DefaultConvertMap_unique(DefaultConvertMap): print(type(C._element_constructor), C._element_constructor) raise - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: cdef Parent C = self._codomain try: if len(args) == 0: @@ -212,7 +212,7 @@ cdef class NamedConvertMap(Map): self.method_name = method_name self._repr_type_str = "Conversion via %s method" % self.method_name - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -239,7 +239,7 @@ cdef class NamedConvertMap(Map): slots['method_name'] = self.method_name return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -265,7 +265,7 @@ cdef class NamedConvertMap(Map): self.method_name = _slots['method_name'] Map._update_slots(self, _slots) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ EXAMPLES:: @@ -299,7 +299,7 @@ cdef class NamedConvertMap(Map): e = m._call_(e) return e - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ EXAMPLES:: @@ -366,7 +366,7 @@ cdef class CallableConvertMap(Map): except AttributeError: self._repr_type_str = "Conversion via %s" % self._func - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -386,7 +386,7 @@ cdef class CallableConvertMap(Map): slots['_parent_as_first_arg'] = self._parent_as_first_arg return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -405,7 +405,7 @@ cdef class CallableConvertMap(Map): self._parent_as_first_arg = _slots['_parent_as_first_arg'] Map._update_slots(self, _slots) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ Because self._func may be anything we do a little bit of sanity checking (the return value must be an element with the correct parent). @@ -447,7 +447,7 @@ cdef class CallableConvertMap(Map): raise RuntimeError("BUG in coercion model: {} returned element with wrong parent (expected {} got {})".format(self._func, C, y._parent)) return y - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ TESTS:: @@ -485,7 +485,7 @@ cdef class CallableConvertMap(Map): cdef class CCallableConvertMap_class(Map): - cdef Element (*_func)(Parent, object) + cdef Element (*_func)(Parent, object) noexcept cdef public _name def __init__(self, domain, codomain, name): @@ -495,7 +495,7 @@ cdef class CCallableConvertMap_class(Map): self._coerce_cost = 10 self._name = name - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ TESTS:: @@ -526,7 +526,7 @@ cdef class CCallableConvertMap_class(Map): return "Conversion via c call '%s'" % self._name -cdef Map CCallableConvertMap(domain, codomain, void* func, name): +cdef Map CCallableConvertMap(domain, codomain, void* func, name) noexcept: """ Use this to create a map from domain to codomain by calling func (which must be a function pointer taking a Parent and object, and @@ -540,7 +540,7 @@ cdef Map CCallableConvertMap(domain, codomain, void* func, name): map._func = func return map -cpdef Element _ccall_test_function(codomain, x): +cpdef Element _ccall_test_function(codomain, x) noexcept: """ For testing CCallableConvertMap_class. Returns x*x*x-x in the codomain. @@ -587,23 +587,23 @@ cdef class ListMorphism(Map): self._real_morphism = real_morphism self._repr_type_str = "List" - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: slots = Map._extra_slots(self) slots['_real_morphism'] = self._real_morphism return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: self._real_morphism = _slots['_real_morphism'] Map._update_slots(self, _slots) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: try: x = x._data except AttributeError: x = list(x) return self._real_morphism._call_(x) - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: try: x = x._data except AttributeError: @@ -632,7 +632,7 @@ cdef class TryMap(Map): else: self._error_types = error_types - cdef dict _extra_slots(self): + cdef dict _extra_slots(self) noexcept: """ Helper for copying and pickling. @@ -655,7 +655,7 @@ cdef class TryMap(Map): slots['_error_types'] = self._error_types return slots - cdef _update_slots(self, dict _slots): + cdef _update_slots(self, dict _slots) noexcept: """ Helper for copying and pickling. @@ -677,7 +677,7 @@ cdef class TryMap(Map): self._error_types = _slots['_error_types'] Map._update_slots(self, _slots) - cpdef Element _call_(self, x): + cpdef Element _call_(self, x) noexcept: """ EXAMPLES:: @@ -696,7 +696,7 @@ cdef class TryMap(Map): except self._error_types: return self._map_b._call_(x) - cpdef Element _call_with_args(self, x, args=(), kwds={}): + cpdef Element _call_with_args(self, x, args=(), kwds={}) noexcept: """ EXAMPLES:: diff --git a/src/sage/structure/element.pxd b/src/sage/structure/element.pxd index 20c556b985e..1cef67617ff 100644 --- a/src/sage/structure/element.pxd +++ b/src/sage/structure/element.pxd @@ -3,7 +3,7 @@ from .parent cimport Parent from sage.misc.inherit_comparison cimport InheritComparisonMetaclass -cpdef inline parent(x): +cpdef inline parent(x) noexcept: """ Return the parent of the element ``x``. @@ -61,7 +61,7 @@ cpdef inline parent(x): return type(x) -cdef inline int classify_elements(left, right): +cdef inline int classify_elements(left, right) noexcept: """ Given two objects, at least one which is an :class:`Element`, classify their type and parent. This is a finer version of @@ -102,13 +102,13 @@ cdef inline int classify_elements(left, right): return 0o07 # Functions to help understand the result of classify_elements() -cdef inline bint BOTH_ARE_ELEMENT(int cl): +cdef inline bint BOTH_ARE_ELEMENT(int cl) noexcept: return cl & 0o04 -cdef inline bint HAVE_SAME_PARENT(int cl): +cdef inline bint HAVE_SAME_PARENT(int cl) noexcept: return cl & 0o20 -cpdef inline bint have_same_parent(left, right): +cpdef inline bint have_same_parent(left, right) noexcept: """ Return ``True`` if and only if ``left`` and ``right`` have the same parent. @@ -143,36 +143,36 @@ cpdef inline bint have_same_parent(left, right): return HAVE_SAME_PARENT(classify_elements(left, right)) -cdef unary_op_exception(op, x) -cdef bin_op_exception(op, x, y) +cdef unary_op_exception(op, x) noexcept +cdef bin_op_exception(op, x, y) noexcept cdef class Element(SageObject): cdef Parent _parent - cpdef _richcmp_(left, right, int op) + cpdef _richcmp_(left, right, int op) noexcept cpdef int _cmp_(left, right) except -2 - cpdef base_extend(self, R) + cpdef base_extend(self, R) noexcept - cdef getattr_from_category(self, name) + cdef getattr_from_category(self, name) noexcept - cpdef _act_on_(self, x, bint self_on_left) - cpdef _acted_upon_(self, x, bint self_on_left) + cpdef _act_on_(self, x, bint self_on_left) noexcept + cpdef _acted_upon_(self, x, bint self_on_left) noexcept - cdef _add_(self, other) - cdef _sub_(self, other) - cdef _neg_(self) - cdef _add_long(self, long n) + cdef _add_(self, other) noexcept + cdef _sub_(self, other) noexcept + cdef _neg_(self) noexcept + cdef _add_long(self, long n) noexcept - cdef _mul_(self, other) - cdef _mul_long(self, long n) - cdef _matmul_(self, other) - cdef _div_(self, other) - cdef _floordiv_(self, other) - cdef _mod_(self, other) + cdef _mul_(self, other) noexcept + cdef _mul_long(self, long n) noexcept + cdef _matmul_(self, other) noexcept + cdef _div_(self, other) noexcept + cdef _floordiv_(self, other) noexcept + cdef _mod_(self, other) noexcept - cdef _pow_(self, other) - cdef _pow_int(self, n) - cdef _pow_long(self, long n) + cdef _pow_(self, other) noexcept + cdef _pow_int(self, n) noexcept + cdef _pow_long(self, long n) noexcept cdef class ElementWithCachedMethod(Element): @@ -183,33 +183,33 @@ cdef class ModuleElement(Element) # forward declaration cdef class RingElement(ModuleElement) # forward declaration cdef class ModuleElement(Element): - cpdef _add_(self, other) - cpdef _sub_(self, other) - cpdef _neg_(self) + cpdef _add_(self, other) noexcept + cpdef _sub_(self, other) noexcept + cpdef _neg_(self) noexcept # self._rmul_(x) is x * self - cpdef _lmul_(self, Element right) + cpdef _lmul_(self, Element right) noexcept # self._lmul_(x) is self * x - cpdef _rmul_(self, Element left) + cpdef _rmul_(self, Element left) noexcept cdef class ModuleElementWithMutability(ModuleElement): cdef bint _is_immutable - cpdef bint is_immutable(self) - cpdef bint is_mutable(self) + cpdef bint is_immutable(self) noexcept + cpdef bint is_mutable(self) noexcept cdef class MonoidElement(Element): - cpdef _pow_int(self, n) + cpdef _pow_int(self, n) noexcept cdef class MultiplicativeGroupElement(MonoidElement): - cpdef _div_(self, other) + cpdef _div_(self, other) noexcept cdef class AdditiveGroupElement(ModuleElement): pass cdef class RingElement(ModuleElement): - cpdef _mul_(self, other) - cpdef _div_(self, other) - cpdef _pow_int(self, n) + cpdef _mul_(self, other) noexcept + cpdef _div_(self, other) noexcept + cpdef _pow_int(self, n) noexcept cdef class CommutativeRingElement(RingElement): pass @@ -224,11 +224,11 @@ cdef class PrincipalIdealDomainElement(DedekindDomainElement): pass cdef class EuclideanDomainElement(PrincipalIdealDomainElement): - cpdef _floordiv_(self, other) - cpdef _mod_(self, other) + cpdef _floordiv_(self, other) noexcept + cpdef _mod_(self, other) noexcept cdef class FieldElement(CommutativeRingElement): - cpdef _floordiv_(self, other) + cpdef _floordiv_(self, other) noexcept cdef class AlgebraElement(RingElement): pass @@ -248,13 +248,13 @@ cdef class Vector(ModuleElementWithMutability): # Return the dot product using the simple metric # $e_i \cdot e_j = \delta_{ij}$. The first assumes that the parents # are equal, both assume that the degrees are equal. - cpdef _dot_product_(Vector left, Vector right) - cpdef _dot_product_coerce_(Vector left, Vector right) + cpdef _dot_product_(Vector left, Vector right) noexcept + cpdef _dot_product_coerce_(Vector left, Vector right) noexcept - cpdef _pairwise_product_(Vector left, Vector right) # override, call if parents the same + cpdef _pairwise_product_(Vector left, Vector right) noexcept # override, call if parents the same - cdef bint is_sparse_c(self) - cdef bint is_dense_c(self) + cdef bint is_sparse_c(self) noexcept + cdef bint is_dense_c(self) noexcept cdef class Matrix(ModuleElement): @@ -262,9 +262,9 @@ cdef class Matrix(ModuleElement): cdef Py_ssize_t _nrows cdef Py_ssize_t _ncols - cdef _vector_times_matrix_(matrix_right, Vector vector_left) # OK to override, AND call directly - cdef _matrix_times_vector_(matrix_left, Vector vector_right) # OK to override, AND call directly - cdef _matrix_times_matrix_(left, Matrix right) # OK to override, AND call directly + cdef _vector_times_matrix_(matrix_right, Vector vector_left) noexcept # OK to override, AND call directly + cdef _matrix_times_vector_(matrix_left, Vector vector_right) noexcept # OK to override, AND call directly + cdef _matrix_times_matrix_(left, Matrix right) noexcept # OK to override, AND call directly - cdef bint is_sparse_c(self) - cdef bint is_dense_c(self) + cdef bint is_sparse_c(self) noexcept + cdef bint is_dense_c(self) noexcept diff --git a/src/sage/structure/element.pyx b/src/sage/structure/element.pyx index 543506e9a74..f1cf9d26ac7 100644 --- a/src/sage/structure/element.pyx +++ b/src/sage/structure/element.pyx @@ -324,7 +324,7 @@ def make_element(_class, _dict, parent): return make_element_old(_class, _dict, parent) -cdef unary_op_exception(op, x): +cdef unary_op_exception(op, x) noexcept: try: op = op.__name__ op = _coerce_op_symbols[op] @@ -334,7 +334,7 @@ cdef unary_op_exception(op, x): return TypeError(f"unsupported operand parent for {op}: '{px}'") -cdef bin_op_exception(op, x, y): +cdef bin_op_exception(op, x, y) noexcept: try: op = op.__name__ op = _coerce_op_symbols[op] @@ -488,7 +488,7 @@ cdef class Element(SageObject): """ return self.getattr_from_category(name) - cdef getattr_from_category(self, name): + cdef getattr_from_category(self, name) noexcept: # Lookup a method or attribute from the category abstract classes. # See __getattr__ above for documentation. cdef Parent P = self._parent @@ -636,7 +636,7 @@ cdef class Element(SageObject): """ raise NotImplementedError - cpdef base_extend(self, R): + cpdef base_extend(self, R) noexcept: cdef Parent V V = self._parent.base_extend(R) return V.coerce(self) @@ -937,7 +937,7 @@ cdef class Element(SageObject): """ return self.subs(in_dict,**kwds) - cpdef _act_on_(self, x, bint self_on_left): + cpdef _act_on_(self, x, bint self_on_left) noexcept: """ Use this method to implement ``self`` acting on ``x``. @@ -946,7 +946,7 @@ cdef class Element(SageObject): """ return None - cpdef _acted_upon_(self, x, bint self_on_left): + cpdef _acted_upon_(self, x, bint self_on_left) noexcept: """ Use this method to implement ``self`` acted on by x. @@ -1106,7 +1106,7 @@ cdef class Element(SageObject): else: return coercion_model.richcmp(self, other, op) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: r""" Basic default implementation of rich comparisons for elements with equal parents. @@ -1248,7 +1248,7 @@ cdef class Element(SageObject): # reversed addition (__radd__). return NotImplemented - cdef _add_(self, other): + cdef _add_(self, other) noexcept: """ Virtual addition method for elements with identical parents. @@ -1278,7 +1278,7 @@ cdef class Element(SageObject): else: return python_op(other) - cdef _add_long(self, long n): + cdef _add_long(self, long n) noexcept: """ Generic path for adding a C long, assumed to commute. @@ -1360,7 +1360,7 @@ cdef class Element(SageObject): except TypeError: return NotImplemented - cdef _sub_(self, other): + cdef _sub_(self, other) noexcept: """ Virtual subtraction method for elements with identical parents. @@ -1414,7 +1414,7 @@ cdef class Element(SageObject): """ return self._neg_() - cdef _neg_(self): + cdef _neg_(self) noexcept: """ Virtual unary negation method for elements. @@ -1528,7 +1528,7 @@ cdef class Element(SageObject): except TypeError: return NotImplemented - cdef _mul_(self, other): + cdef _mul_(self, other) noexcept: """ Virtual multiplication method for elements with identical parents. @@ -1558,7 +1558,7 @@ cdef class Element(SageObject): else: return python_op(other) - cdef _mul_long(self, long n): + cdef _mul_long(self, long n) noexcept: """ Generic path for multiplying by a C long, assumed to commute. @@ -1640,7 +1640,7 @@ cdef class Element(SageObject): except TypeError: return NotImplemented - cdef _matmul_(self, other): + cdef _matmul_(self, other) noexcept: """ Virtual matrix multiplication method for elements with identical parents. @@ -1743,7 +1743,7 @@ cdef class Element(SageObject): except TypeError: return NotImplemented - cdef _div_(self, other): + cdef _div_(self, other) noexcept: """ Virtual division method for elements with identical parents. This is called for Python 2 division as well as true division. @@ -1844,7 +1844,7 @@ cdef class Element(SageObject): except TypeError: return NotImplemented - cdef _floordiv_(self, other): + cdef _floordiv_(self, other) noexcept: """ Virtual floor division method for elements with identical parents. @@ -1944,7 +1944,7 @@ cdef class Element(SageObject): except TypeError: return NotImplemented - cdef _mod_(self, other): + cdef _mod_(self, other) noexcept: """ Virtual modulo method for elements with identical parents. @@ -2071,7 +2071,7 @@ cdef class Element(SageObject): except TypeError: return NotImplemented - cdef _pow_(self, other): + cdef _pow_(self, other) noexcept: """ Virtual powering method for elements with identical parents. @@ -2101,7 +2101,7 @@ cdef class Element(SageObject): else: return python_op(other) - cdef _pow_int(self, other): + cdef _pow_int(self, other) noexcept: """ Virtual powering method for powering to an integer exponent. @@ -2131,7 +2131,7 @@ cdef class Element(SageObject): else: return python_op(other) - cdef _pow_long(self, long n): + cdef _pow_long(self, long n) noexcept: """ Generic path for powering with a C long. """ @@ -2308,7 +2308,7 @@ cdef class ElementWithCachedMethod(Element): True """ - cdef getattr_from_category(self, name): + cdef getattr_from_category(self, name) noexcept: """ This getattr method ensures that cached methods and lazy attributes can be inherited from the element class of a category. @@ -2376,7 +2376,7 @@ cdef class ModuleElement(Element): """ Generic element of a module. """ - cpdef _add_(self, other): + cpdef _add_(self, other) noexcept: """ Abstract addition method @@ -2391,7 +2391,7 @@ cdef class ModuleElement(Element): """ raise NotImplementedError(f"addition not implemented for {self._parent}") - cdef _add_long(self, long n): + cdef _add_long(self, long n) noexcept: """ Generic path for adding a C long, assumed to commute. """ @@ -2399,21 +2399,21 @@ cdef class ModuleElement(Element): return self return coercion_model.bin_op(self, n, add) - cpdef _sub_(self, other): + cpdef _sub_(self, other) noexcept: """ Default implementation of subtraction using addition and negation. """ return self + (-other) - cpdef _neg_(self): + cpdef _neg_(self) noexcept: """ Default implementation of negation using multiplication with -1. """ return self._mul_long(-1) - cdef _mul_long(self, long n): + cdef _mul_long(self, long n) noexcept: """ Generic path for multiplying by a C long, assumed to commute. """ @@ -2422,7 +2422,7 @@ cdef class ModuleElement(Element): return coercion_model.bin_op(self, n, mul) # rmul -- left * self - cpdef _rmul_(self, Element left): + cpdef _rmul_(self, Element left) noexcept: """ Reversed scalar multiplication for module elements with the module element on the right and the scalar on the left. @@ -2432,7 +2432,7 @@ cdef class ModuleElement(Element): return self._lmul_(left) # lmul -- self * right - cpdef _lmul_(self, Element right): + cpdef _lmul_(self, Element right) noexcept: """ Scalar multiplication for module elements with the module element on the left and the scalar on the right. @@ -2490,7 +2490,7 @@ cdef class ModuleElementWithMutability(ModuleElement): """ self._is_immutable = 1 - cpdef bint is_mutable(self): + cpdef bint is_mutable(self) noexcept: """ Return True if this vector is mutable, i.e., the entries can be changed. @@ -2505,7 +2505,7 @@ cdef class ModuleElementWithMutability(ModuleElement): """ return not self._is_immutable - cpdef bint is_immutable(self): + cpdef bint is_immutable(self) noexcept: """ Return True if this vector is immutable, i.e., the entries cannot be changed. @@ -2551,7 +2551,7 @@ cdef class MonoidElement(Element): """ raise NotImplementedError - cpdef _pow_int(self, n): + cpdef _pow_int(self, n) noexcept: """ Return the (integral) power of self. """ @@ -2619,7 +2619,7 @@ cdef class MultiplicativeGroupElement(MonoidElement): """ return self.multiplicative_order() - cpdef _div_(self, right): + cpdef _div_(self, right) noexcept: """ Default implementation of division using multiplication by the inverse. @@ -2644,7 +2644,7 @@ def is_RingElement(x): cdef class RingElement(ModuleElement): - cpdef _mul_(self, other): + cpdef _mul_(self, other) noexcept: """ Abstract multiplication method @@ -2662,7 +2662,7 @@ cdef class RingElement(ModuleElement): def is_one(self): return self == self._parent.one() - cpdef _pow_int(self, n): + cpdef _pow_int(self, n) noexcept: """ Return the (integral) power of self. @@ -2745,7 +2745,7 @@ cdef class RingElement(ModuleElement): l.append(x) return l - cpdef _div_(self, other): + cpdef _div_(self, other) noexcept: """ Default implementation of division using the fraction field. """ @@ -3403,10 +3403,10 @@ cdef class Expression(CommutativeRingElement): ############################################## cdef class Vector(ModuleElementWithMutability): - cdef bint is_sparse_c(self): + cdef bint is_sparse_c(self) noexcept: raise NotImplementedError - cdef bint is_dense_c(self): + cdef bint is_dense_c(self) noexcept: raise NotImplementedError def __mul__(left, right): @@ -3684,13 +3684,13 @@ cdef class Vector(ModuleElementWithMutability): return (left)._dot_product_(right) return coercion_model.bin_op(left, right, mul) - cpdef _dot_product_(Vector left, Vector right): + cpdef _dot_product_(Vector left, Vector right) noexcept: return left._dot_product_coerce_(right) - cpdef _dot_product_coerce_(Vector left, Vector right): + cpdef _dot_product_coerce_(Vector left, Vector right) noexcept: raise bin_op_exception('*', left, right) - cpdef _pairwise_product_(Vector left, Vector right): + cpdef _pairwise_product_(Vector left, Vector right) noexcept: raise TypeError("unsupported operation for '%s' and '%s'"%(parent(left), parent(right))) def __truediv__(self, right): @@ -3774,10 +3774,10 @@ def is_Vector(x): cdef class Matrix(ModuleElement): - cdef bint is_sparse_c(self): + cdef bint is_sparse_c(self) noexcept: raise NotImplementedError - cdef bint is_dense_c(self): + cdef bint is_dense_c(self) noexcept: raise NotImplementedError def __mul__(left, right): @@ -4153,13 +4153,13 @@ cdef class Matrix(ModuleElement): return right.solve_left(left) return coercion_model.bin_op(left, right, truediv) - cdef _vector_times_matrix_(matrix_right, Vector vector_left): + cdef _vector_times_matrix_(matrix_right, Vector vector_left) noexcept: raise TypeError - cdef _matrix_times_vector_(matrix_left, Vector vector_right): + cdef _matrix_times_vector_(matrix_left, Vector vector_right) noexcept: raise TypeError - cdef _matrix_times_matrix_(left, Matrix right): + cdef _matrix_times_matrix_(left, Matrix right) noexcept: raise TypeError @@ -4289,7 +4289,7 @@ cdef class EuclideanDomainElement(PrincipalIdealDomainElement): def quo_rem(self, other): raise NotImplementedError - cpdef _floordiv_(self, right): + cpdef _floordiv_(self, right) noexcept: """ Quotient of division of ``self`` by other. This is denoted //. @@ -4312,7 +4312,7 @@ cdef class EuclideanDomainElement(PrincipalIdealDomainElement): Q, _ = self.quo_rem(right) return Q - cpdef _mod_(self, other): + cpdef _mod_(self, other) noexcept: """ Remainder of division of ``self`` by other. @@ -4351,7 +4351,7 @@ def is_FieldElement(x): return isinstance(x, FieldElement) cdef class FieldElement(CommutativeRingElement): - cpdef _floordiv_(self, right): + cpdef _floordiv_(self, right) noexcept: """ Return the quotient of self and other. Since these are field elements, the floor division is exactly the same as usual division. @@ -4508,7 +4508,7 @@ cdef class InfinityElement(RingElement): # ################################################################################# -cpdef canonical_coercion(x, y): +cpdef canonical_coercion(x, y) noexcept: """ ``canonical_coercion(x,y)`` is what is called before doing an arithmetic operation between ``x`` and ``y``. It returns a pair ``(z,w)`` @@ -4527,7 +4527,7 @@ cpdef canonical_coercion(x, y): return coercion_model.canonical_coercion(x,y) -cpdef bin_op(x, y, op): +cpdef bin_op(x, y, op) noexcept: return coercion_model.bin_op(x, y, op) diff --git a/src/sage/structure/element_wrapper.pxd b/src/sage/structure/element_wrapper.pxd index 4ae146b3dd5..308f4a749ce 100644 --- a/src/sage/structure/element_wrapper.pxd +++ b/src/sage/structure/element_wrapper.pxd @@ -4,8 +4,8 @@ from sage.structure.element cimport Element cdef class ElementWrapper(Element): cdef public object value - cpdef _richcmp_(left, right, int op) - cpdef bint _lt_by_value(self, other) + cpdef _richcmp_(left, right, int op) noexcept + cpdef bint _lt_by_value(self, other) noexcept cdef class ElementWrapperCheckWrappedClass(ElementWrapper): pass diff --git a/src/sage/structure/element_wrapper.pyx b/src/sage/structure/element_wrapper.pyx index 3aa87527d92..42dedbf03c3 100644 --- a/src/sage/structure/element_wrapper.pyx +++ b/src/sage/structure/element_wrapper.pyx @@ -293,7 +293,7 @@ cdef class ElementWrapper(Element): return left._richcmp_(right, op) return coercion_model.richcmp(left, right, op) - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Return ``True`` if ``left`` compares with ``right`` based on ``op``. @@ -357,7 +357,7 @@ cdef class ElementWrapper(Element): return self.value != (right).value return False - cpdef bint _lt_by_value(self, other): + cpdef bint _lt_by_value(self, other) noexcept: """ Return whether ``self`` is strictly smaller than ``other``. diff --git a/src/sage/structure/factory.pyx b/src/sage/structure/factory.pyx index ddb55501d94..1b83ea0c2a9 100644 --- a/src/sage/structure/factory.pyx +++ b/src/sage/structure/factory.pyx @@ -372,7 +372,7 @@ cdef class UniqueFactory(SageObject): version = self.get_version(sage_version) return self.get_object(version, key, kwds) - cpdef get_object(self, version, key, extra_args): + cpdef get_object(self, version, key, extra_args) noexcept: """ Returns the object corresponding to ``key``, creating it with ``extra_args`` if necessary (for example, it isn't in the cache @@ -436,7 +436,7 @@ cdef class UniqueFactory(SageObject): pass return obj - cpdef get_version(self, sage_version): + cpdef get_version(self, sage_version) noexcept: """ This is provided to allow more or less granular control over pickle versioning. Objects pickled in the same version of Sage @@ -507,7 +507,7 @@ cdef class UniqueFactory(SageObject): """ raise NotImplementedError - cpdef other_keys(self, key, obj): + cpdef other_keys(self, key, obj) noexcept: """ Sometimes during object creation, certain defaults are chosen which may result in a new (more specific) key. This allows the more specific @@ -534,7 +534,7 @@ cdef class UniqueFactory(SageObject): """ return [] - cpdef reduce_data(self, obj): + cpdef reduce_data(self, obj) noexcept: """ The results of this function can be returned from :meth:`__reduce__`. This is here so the factory internals can diff --git a/src/sage/structure/list_clone.pxd b/src/sage/structure/list_clone.pxd index f57c7148974..e182ebf8be1 100644 --- a/src/sage/structure/list_clone.pxd +++ b/src/sage/structure/list_clone.pxd @@ -19,46 +19,46 @@ cdef class ClonableElement(Element): cdef long int _hash cpdef bint _require_mutable(self) except -2 - cpdef bint is_mutable(self) - cpdef bint is_immutable(self) - cpdef set_immutable(self) + cpdef bint is_mutable(self) noexcept + cpdef bint is_immutable(self) noexcept + cpdef set_immutable(self) noexcept - cpdef _set_mutable(self) + cpdef _set_mutable(self) noexcept - cpdef ClonableElement clone(self, bint check=?) + cpdef ClonableElement clone(self, bint check=?) noexcept cdef class ClonableArray(ClonableElement): cdef list _list - cpdef list _get_list(self) - cpdef _set_list(self, list lst) - cpdef ClonableArray __copy__(self) - cpdef check(self) - cpdef object _getitem(self, int key) - cpdef _setitem(self, int key, value) + cpdef list _get_list(self) noexcept + cpdef _set_list(self, list lst) noexcept + cpdef ClonableArray __copy__(self) noexcept + cpdef check(self) noexcept + cpdef object _getitem(self, int key) noexcept + cpdef _setitem(self, int key, value) noexcept cpdef int index(self, key, start=*, stop=*) except -1 cpdef int count(self, key) except -1 cpdef long int _hash_(self) except? -1 cdef class ClonableList(ClonableArray): - cpdef append(self, el) - cpdef extend(self, it) - cpdef insert(self, int index, el) - cpdef pop(self, int index=*) - cpdef remove(self, el) + cpdef append(self, el) noexcept + cpdef extend(self, it) noexcept + cpdef insert(self, int index, el) noexcept + cpdef pop(self, int index=*) noexcept + cpdef remove(self, el) noexcept cdef class NormalizedClonableList(ClonableList): - cpdef normalize(self) + cpdef normalize(self) noexcept cdef class ClonableIntArray(ClonableElement): cdef int _len cdef int* _list - cpdef _alloc_(self, int size) - cpdef ClonableIntArray __copy__(self) - cpdef check(self) - cpdef object _getitem(self, int key) - cpdef _setitem(self, int item, value) + cpdef _alloc_(self, int size) noexcept + cpdef ClonableIntArray __copy__(self) noexcept + cpdef check(self) noexcept + cpdef object _getitem(self, int key) noexcept + cpdef _setitem(self, int item, value) noexcept cpdef int index(self, int item) except -1 cpdef long int _hash_(self) except? -1 - cpdef list list(self) + cpdef list list(self) noexcept diff --git a/src/sage/structure/list_clone.pyx b/src/sage/structure/list_clone.pyx index ae50771c7b8..9ca7be464e6 100644 --- a/src/sage/structure/list_clone.pyx +++ b/src/sage/structure/list_clone.pyx @@ -308,7 +308,7 @@ cdef class ClonableElement(Element): if self._is_immutable: raise ValueError("object is immutable; please change a copy instead.") - cpdef bint is_mutable(self): + cpdef bint is_mutable(self) noexcept: """ Return ``True`` if ``self`` is mutable (can be changed) and ``False`` if it is not. @@ -329,7 +329,7 @@ cdef class ClonableElement(Element): """ return not self._is_immutable - cpdef bint is_immutable(self): + cpdef bint is_immutable(self) noexcept: """ Return ``True`` if ``self`` is immutable (cannot be changed) and ``False`` if it is not. @@ -350,7 +350,7 @@ cdef class ClonableElement(Element): """ return self._is_immutable - cpdef set_immutable(self): + cpdef set_immutable(self) noexcept: """ Makes ``self`` immutable, so it can never again be changed. @@ -369,7 +369,7 @@ cdef class ClonableElement(Element): """ self._is_immutable = True - cpdef _set_mutable(self): + cpdef _set_mutable(self) noexcept: """ Makes ``self`` mutable, so it can be changed. @@ -415,7 +415,7 @@ cdef class ClonableElement(Element): self._hash = self._hash_() return self._hash - cpdef ClonableElement clone(self, bint check=True): + cpdef ClonableElement clone(self, bint check=True) noexcept: """ Return a clone that is mutable copy of ``self``. @@ -578,7 +578,7 @@ cdef class ClonableArray(ClonableElement): """ return bool(self._list) - cpdef list _get_list(self): + cpdef list _get_list(self) noexcept: """ Return the list embedded in ``self``. @@ -594,7 +594,7 @@ cdef class ClonableArray(ClonableElement): """ return self._list - cpdef _set_list(self, list lst): + cpdef _set_list(self, list lst) noexcept: """ Set the list embedded in ``self``. @@ -676,7 +676,7 @@ cdef class ClonableArray(ClonableElement): self._require_mutable() self._list[key] = value - cpdef object _getitem(self, int key): + cpdef object _getitem(self, int key) noexcept: """ Same as :meth:`__getitem__` @@ -695,7 +695,7 @@ cdef class ClonableArray(ClonableElement): """ return self._list[key] - cpdef _setitem(self, int key, value): + cpdef _setitem(self, int key, value) noexcept: """ Same as :meth:`__setitem__` @@ -822,7 +822,7 @@ cdef class ClonableArray(ClonableElement): return self._hash # See protocol in comment in sage/structure/element.pyx - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ TESTS:: @@ -845,7 +845,7 @@ cdef class ClonableArray(ClonableElement): cdef ClonableArray rgt = right return richcmp(left._list, rgt._list, op) - cpdef ClonableArray __copy__(self): + cpdef ClonableArray __copy__(self) noexcept: """ Return a copy of ``self`` @@ -889,7 +889,7 @@ cdef class ClonableArray(ClonableElement): res.__dict__ = self.__dict__.copy() return res - cpdef check(self): + cpdef check(self) noexcept: """ Check that ``self`` fulfill the invariants @@ -1006,7 +1006,7 @@ cdef class ClonableList(ClonableArray): .. SEEALSO:: :class:`~sage.structure.list_clone_demo.IncreasingList` for an example of usage. """ - cpdef append(self, el): + cpdef append(self, el) noexcept: """ Appends ``el`` to ``self`` @@ -1035,7 +1035,7 @@ cdef class ClonableList(ClonableArray): self._require_mutable() self._list.append(el) - cpdef extend(self, it): + cpdef extend(self, it) noexcept: """ Extends ``self`` by the content of the iterable ``it`` @@ -1070,7 +1070,7 @@ cdef class ClonableList(ClonableArray): self._require_mutable() self._list.extend(it) - cpdef insert(self, int index, el): + cpdef insert(self, int index, el) noexcept: """ Inserts ``el`` in ``self`` at position ``index`` @@ -1100,7 +1100,7 @@ cdef class ClonableList(ClonableArray): self._require_mutable() self._list.insert(index, el) - cpdef pop(self, int index=-1): + cpdef pop(self, int index=-1) noexcept: """ Remove ``self[index]`` from ``self`` and returns it @@ -1128,7 +1128,7 @@ cdef class ClonableList(ClonableArray): self._require_mutable() return self._list.pop(index) - cpdef remove(self, el): + cpdef remove(self, el) noexcept: """ Remove the first occurrence of ``el`` from ``self`` @@ -1285,7 +1285,7 @@ cdef class ClonableIntArray(ClonableElement): if check: self.check() - cpdef _alloc_(self, int size): + cpdef _alloc_(self, int size) noexcept: """ Allocate the array part of ``self`` for a given size @@ -1371,7 +1371,7 @@ cdef class ClonableIntArray(ClonableElement): """ return iter(self.list()) - cpdef list list(self): + cpdef list list(self) noexcept: """ Convert self into a Python list. @@ -1469,7 +1469,7 @@ cdef class ClonableIntArray(ClonableElement): else: raise IndexError("list index out of range") - cpdef object _getitem(self, int key): + cpdef object _getitem(self, int key) noexcept: """ Same as :meth:`__getitem__` @@ -1487,7 +1487,7 @@ cdef class ClonableIntArray(ClonableElement): else: raise IndexError("list index out of range") - cpdef _setitem(self, int key, value): + cpdef _setitem(self, int key, value) noexcept: """ Same as :meth:`__setitem__` @@ -1575,7 +1575,7 @@ cdef class ClonableIntArray(ClonableElement): return self._hash # See protocol in comment in sage/structure/element.pyx - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ TESTS:: @@ -1623,7 +1623,7 @@ cdef class ClonableIntArray(ClonableElement): return rich_to_bool(op, 1) return rich_to_bool(op, reslen) - cpdef ClonableIntArray __copy__(self): + cpdef ClonableIntArray __copy__(self) noexcept: """ Return a copy of ``self`` @@ -1670,7 +1670,7 @@ cdef class ClonableIntArray(ClonableElement): res.__dict__ = self.__dict__.copy() return res - cpdef check(self): + cpdef check(self) noexcept: """ Check that ``self`` fulfill the invariants @@ -1832,7 +1832,7 @@ cdef class NormalizedClonableList(ClonableList): self.normalize() return ClonableList.__exit__(self, typ, value, tracback) - cpdef normalize(self): + cpdef normalize(self) noexcept: """ Normalize ``self`` diff --git a/src/sage/structure/list_clone_demo.pyx b/src/sage/structure/list_clone_demo.pyx index 0bd018f57c0..fc68eee947e 100644 --- a/src/sage/structure/list_clone_demo.pyx +++ b/src/sage/structure/list_clone_demo.pyx @@ -30,7 +30,7 @@ cdef class IncreasingArray(ClonableArray): sage: TestSuite(IncreasingArrays()([])).run() """ - cpdef check(self): + cpdef check(self) noexcept: """ Check that ``self`` is increasing. @@ -113,7 +113,7 @@ cdef class IncreasingList(ClonableList): sage: TestSuite(IncreasingLists()([])).run() """ - cpdef check(self): + cpdef check(self) noexcept: """ Check that ``self`` is increasing @@ -146,7 +146,7 @@ cdef class IncreasingIntArray(ClonableIntArray): sage: TestSuite(IncreasingIntArrays()([])).run() """ - cpdef check(self): + cpdef check(self) noexcept: """ Check that ``self`` is increasing. @@ -193,7 +193,7 @@ cdef class SortedList(NormalizedClonableList): sage: TestSuite(IncreasingIntArrays()([1,2,3])).run() sage: TestSuite(IncreasingIntArrays()([])).run() """ - cpdef normalize(self): + cpdef normalize(self) noexcept: """ Normalize ``self`` @@ -213,7 +213,7 @@ cdef class SortedList(NormalizedClonableList): self._require_mutable() self._get_list().sort() - cpdef check(self): + cpdef check(self) noexcept: """ Check that ``self`` is strictly increasing diff --git a/src/sage/structure/list_clone_timings_cy.pyx b/src/sage/structure/list_clone_timings_cy.pyx index 46152f1e68b..6237fbe09a7 100644 --- a/src/sage/structure/list_clone_timings_cy.pyx +++ b/src/sage/structure/list_clone_timings_cy.pyx @@ -14,7 +14,7 @@ from sage.structure.list_clone cimport ClonableArray ##################################################################### ###### Timings functions ###### ##################################################################### -cpdef ClonableArray cy_add1_internal(ClonableArray bla): +cpdef ClonableArray cy_add1_internal(ClonableArray bla) noexcept: """ TESTS:: @@ -34,7 +34,7 @@ cpdef ClonableArray cy_add1_internal(ClonableArray bla): return blo -cpdef ClonableArray cy_add1_immutable(ClonableArray bla): +cpdef ClonableArray cy_add1_immutable(ClonableArray bla) noexcept: """ TESTS:: @@ -49,7 +49,7 @@ cpdef ClonableArray cy_add1_immutable(ClonableArray bla): for i in range(len(lbla)): lbla[i] += 1 return bla.__class__(bla._parent, lbla) -cpdef ClonableArray cy_add1_mutable(ClonableArray bla): +cpdef ClonableArray cy_add1_mutable(ClonableArray bla) noexcept: """ TESTS:: @@ -68,7 +68,7 @@ cpdef ClonableArray cy_add1_mutable(ClonableArray bla): return blo -cpdef ClonableArray cy_add1_with(ClonableArray bla): +cpdef ClonableArray cy_add1_with(ClonableArray bla) noexcept: """ TESTS:: diff --git a/src/sage/structure/mutability.pxd b/src/sage/structure/mutability.pxd index 3df360116ad..16a474e8d2e 100644 --- a/src/sage/structure/mutability.pxd +++ b/src/sage/structure/mutability.pxd @@ -14,7 +14,7 @@ Mutability -- Pyrex Implementation cdef class Mutability: cdef public bint _is_immutable - cpdef _require_mutable(self) - cpdef _require_immutable(self) - cpdef bint is_immutable(self) - cpdef bint is_mutable(self) \ No newline at end of file + cpdef _require_mutable(self) noexcept + cpdef _require_immutable(self) noexcept + cpdef bint is_immutable(self) noexcept + cpdef bint is_mutable(self) noexcept \ No newline at end of file diff --git a/src/sage/structure/mutability.pyx b/src/sage/structure/mutability.pyx index 4aa466513c8..46a04784e0c 100644 --- a/src/sage/structure/mutability.pyx +++ b/src/sage/structure/mutability.pyx @@ -66,7 +66,7 @@ cdef class Mutability: """ self._is_immutable = is_immutable - cpdef _require_mutable(self): + cpdef _require_mutable(self) noexcept: r""" Whenever mutability is required, this method can be called. @@ -92,7 +92,7 @@ cdef class Mutability: if self._is_immutable: raise ValueError("object is immutable; please change a copy instead") - cpdef _require_immutable(self): + cpdef _require_immutable(self) noexcept: r""" Whenever immutability is required, this method can be called. @@ -135,7 +135,7 @@ cdef class Mutability: """ self._is_immutable = 1 - cpdef bint is_immutable(self): + cpdef bint is_immutable(self) noexcept: """ Return ``True`` if this object is immutable (cannot be changed) and ``False`` if it is not. @@ -156,7 +156,7 @@ cdef class Mutability: """ return self._is_immutable - cpdef bint is_mutable(self): + cpdef bint is_mutable(self) noexcept: """ Return ``True`` if this object is mutable (can be changed) and ``False`` if it is not. diff --git a/src/sage/structure/parent.pxd b/src/sage/structure/parent.pxd index a9e98c2bd5c..2a9c637af6c 100644 --- a/src/sage/structure/parent.pxd +++ b/src/sage/structure/parent.pxd @@ -20,13 +20,13 @@ cdef class Parent(sage.structure.category_object.CategoryObject): # Flags, see below cdef int flags - cdef inline bint get_flag(self, int flag): + cdef inline bint get_flag(self, int flag) noexcept: return self.flags & flag - cpdef register_coercion(self, mor) - cpdef register_action(self, action) - cpdef register_conversion(self, mor) - cpdef register_embedding(self, embedding) + cpdef register_coercion(self, mor) noexcept + cpdef register_action(self, action) noexcept + cpdef register_conversion(self, mor) noexcept + cpdef register_embedding(self, embedding) noexcept cpdef bint is_exact(self) except -2 @@ -37,33 +37,33 @@ cdef class Parent(sage.structure.category_object.CategoryObject): cpdef bint has_coerce_map_from(self, S) except -2 # returns a Morphism from S to self, or None - cpdef coerce_map_from(self, S) - cpdef _internal_coerce_map_from(self, S) - cpdef _coerce_map_from_(self, S) + cpdef coerce_map_from(self, S) noexcept + cpdef _internal_coerce_map_from(self, S) noexcept + cpdef _coerce_map_from_(self, S) noexcept # returns a Map from S to self, or None - cpdef convert_map_from(self, S) - cpdef _internal_convert_map_from(self, S) - cpdef _convert_map_from_(self, S) - cdef convert_method_map(self, S, method_name) + cpdef convert_map_from(self, S) noexcept + cpdef _internal_convert_map_from(self, S) noexcept + cpdef _convert_map_from_(self, S) noexcept + cdef convert_method_map(self, S, method_name) noexcept # returns the Action by/on self on/by S # corresponding to op and self_on_left - cpdef get_action(self, S, op=*, bint self_on_left=*, self_el=*, S_el=*) - cpdef _get_action_(self, S, op, bint self_on_left) + cpdef get_action(self, S, op=*, bint self_on_left=*, self_el=*, S_el=*) noexcept + cpdef _get_action_(self, S, op, bint self_on_left) noexcept # coerce x into self - cpdef coerce(self, x) + cpdef coerce(self, x) noexcept - cpdef an_element(self) + cpdef an_element(self) noexcept cdef public object _cache_an_element # For internal use - cpdef _generic_convert_map(self, S, category=*) - cpdef _generic_coerce_map(self, S) - cdef discover_coerce_map_from(self, S) - cdef discover_convert_map_from(self, S) - cdef discover_action(self, S, op, bint self_on_left, self_el=*, S_el=*) + cpdef _generic_convert_map(self, S, category=*) noexcept + cpdef _generic_coerce_map(self, S) noexcept + cdef discover_coerce_map_from(self, S) noexcept + cdef discover_convert_map_from(self, S) noexcept + cdef discover_action(self, S, op, bint self_on_left, self_el=*, S_el=*) noexcept # List consisting of Morphisms (from anything to self) # and Parents for which the __call__ method of self diff --git a/src/sage/structure/parent.pyx b/src/sage/structure/parent.pyx index 6548d8a3656..6c073e8cd98 100644 --- a/src/sage/structure/parent.pyx +++ b/src/sage/structure/parent.pyx @@ -128,11 +128,11 @@ from .coerce_maps cimport (NamedConvertMap, DefaultConvertMap, from .element cimport parent -cdef _record_exception(): +cdef _record_exception() noexcept: coercion_model._record_exception() cdef object _Integer -cdef bint is_Integer(x): +cdef bint is_Integer(x) noexcept: global _Integer if _Integer is None: from sage.rings.integer import Integer as _Integer @@ -157,7 +157,7 @@ def is_Parent(x): return isinstance(x, Parent) -cdef bint guess_pass_parent(parent, element_constructor): +cdef bint guess_pass_parent(parent, element_constructor) noexcept: # Returning True here is deprecated, see #26879 if isinstance(element_constructor, MethodType): return False @@ -171,7 +171,7 @@ from sage.structure.dynamic_class import dynamic_class Sets_parent_class = Sets().parent_class -cdef inline bint good_as_coerce_domain(S): +cdef inline bint good_as_coerce_domain(S) noexcept: """ Determine whether the input can be the domain of a map. @@ -197,7 +197,7 @@ cdef inline bint good_as_coerce_domain(S): return isinstance(S, (CategoryObject, type)) -cdef inline bint good_as_convert_domain(S): +cdef inline bint good_as_convert_domain(S) noexcept: return isinstance(S, (SageObject, type)) @@ -1188,7 +1188,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): except (TypeError, ValueError, ArithmeticError): return False - cpdef coerce(self, x): + cpdef coerce(self, x) noexcept: """ Return x as an element of self, if and only if there is a canonical coercion from the parent of x to self. @@ -1604,7 +1604,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): except KeyError: pass - cpdef register_coercion(self, mor): + cpdef register_coercion(self, mor) noexcept: r""" Update the coercion model to use `mor : P \to \text{self}` to coerce from a parent ``P`` into ``self``. @@ -1664,7 +1664,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): self._registered_domains.append(D) self._coerce_from_hash.set(D, mor) - cpdef register_action(self, action): + cpdef register_action(self, action) noexcept: r""" Update the coercion model to use ``action`` to act on self. @@ -1728,7 +1728,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): raise ValueError("action must involve self") self._action_list.append(action) - cpdef register_conversion(self, mor): + cpdef register_conversion(self, mor) noexcept: r""" Update the coercion model to use `\text{mor} : P \to \text{self}` to convert from ``P`` into ``self``. @@ -1763,7 +1763,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): else: raise TypeError("conversions must be parents or maps") - cpdef register_embedding(self, embedding): + cpdef register_embedding(self, embedding) noexcept: r""" Add embedding to coercion model. @@ -1900,7 +1900,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): """ return copy(self._embedding) # It might be overkill to make a copy here - cpdef _generic_coerce_map(self, S): + cpdef _generic_coerce_map(self, S) noexcept: r""" Returns a default coercion map based on the data provided to :meth:`_populate_coercion_lists_`. @@ -1931,7 +1931,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): category = self.category()._meet_(S.category()) return self._generic_convert_map(S, category=category) - cpdef _generic_convert_map(self, S, category=None): + cpdef _generic_convert_map(self, S, category=None) noexcept: r""" Returns the default conversion map based on the data provided to :meth:`_populate_coercion_lists_`. @@ -1989,7 +1989,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): method_name = self._convert_method_name return self.convert_method_map(S, method_name) - cdef convert_method_map(self, S, method_name): + cdef convert_method_map(self, S, method_name) noexcept: # Cython implementation of _convert_method_map() cdef Parent P if isinstance(S, Parent): @@ -2090,7 +2090,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): return True return self._internal_coerce_map_from(S) is not None - cpdef _coerce_map_from_(self, S): + cpdef _coerce_map_from_(self, S) noexcept: """ Override this method to specify coercions beyond those specified in coerce_list. @@ -2107,7 +2107,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): except AttributeError: return None - cpdef coerce_map_from(self, S): + cpdef coerce_map_from(self, S) noexcept: """ Return a :class:`Map` object to coerce from ``S`` to ``self`` if one exists, or ``None`` if no such coercion exists. @@ -2145,7 +2145,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): """ return copy(self._internal_coerce_map_from(S)) - cpdef _internal_coerce_map_from(self, S): + cpdef _internal_coerce_map_from(self, S) noexcept: """ Return the :class:`Map` object to coerce from ``S`` to ``self`` that is used internally by the coercion system if one exists, or ``None`` @@ -2267,7 +2267,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): finally: _unregister_pair(self, S, "coerce") - cdef discover_coerce_map_from(self, S): + cdef discover_coerce_map_from(self, S) noexcept: """ Precedence for discovering a coercion S -> self goes as follows: @@ -2444,7 +2444,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): if connecting is not None: return (S)._embedding.post_compose(connecting) - cpdef convert_map_from(self, S): + cpdef convert_map_from(self, S) noexcept: """ This function returns a :class:`Map` from `S` to `self`, which may or may not succeed on all inputs. @@ -2470,7 +2470,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): """ return copy(self._internal_convert_map_from(S)) - cpdef _internal_convert_map_from(self, S): + cpdef _internal_convert_map_from(self, S) noexcept: """ This function returns a :class:`Map` from `S` to `self`, which may or may not succeed on all inputs. @@ -2516,7 +2516,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): mor._make_weak_references() return mor - cdef discover_convert_map_from(self, S): + cdef discover_convert_map_from(self, S) noexcept: cdef map.Map mor = self._internal_coerce_map_from(S) if mor is not None: @@ -2544,7 +2544,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): mor = self._generic_convert_map(S) return mor - cpdef _convert_map_from_(self, S): + cpdef _convert_map_from_(self, S) noexcept: """ Override this method to provide additional conversions beyond those given in convert_list. @@ -2558,7 +2558,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): """ return None - cpdef get_action(self, S, op=operator.mul, bint self_on_left=True, self_el=None, S_el=None): + cpdef get_action(self, S, op=operator.mul, bint self_on_left=True, self_el=None, S_el=None) noexcept: """ Returns an action of self on S or S on self. @@ -2594,7 +2594,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): self._action_hash.set(S, op, self_on_left, action) return action - cdef discover_action(self, S, op, bint self_on_left, self_el=None, S_el=None): + cdef discover_action(self, S, op, bint self_on_left, self_el=None, S_el=None) noexcept: """ TESTS:: @@ -2704,7 +2704,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): except TypeError: _record_exception() - cpdef _get_action_(self, S, op, bint self_on_left): + cpdef _get_action_(self, S, op, bint self_on_left) noexcept: """ Override this method to provide an action of self on S or S on self beyond what was specified in action_list. @@ -2716,7 +2716,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): # TODO: remove once all parents in Sage will inherit properly from # Sets().ParentMethods.an_element - cpdef an_element(self): + cpdef an_element(self) noexcept: r""" Returns a (preferably typical) element of this parent. diff --git a/src/sage/structure/parent_base.pyx b/src/sage/structure/parent_base.pyx index dd697f90135..64277588819 100644 --- a/src/sage/structure/parent_base.pyx +++ b/src/sage/structure/parent_base.pyx @@ -14,7 +14,7 @@ Base class for old-style parent objects with a base ring cimport sage.structure.parent as parent from .coerce_exceptions import CoercionException -cdef inline check_old_coerce(parent.Parent p): +cdef inline check_old_coerce(parent.Parent p) noexcept: if p._element_constructor is not None: raise RuntimeError("%s still using old coercion framework" % p) @@ -27,7 +27,7 @@ cdef class ParentWithBase(Parent_old): Parent_old.__init__(self, *args, **kwds) self._base = base - cdef _coerce_c_impl(self,x): + cdef _coerce_c_impl(self,x) noexcept: check_old_coerce(self) from sage.misc.superseded import deprecation deprecation(33497, "_coerce_c_impl is deprecated, use coerce instead") diff --git a/src/sage/structure/parent_gens.pyx b/src/sage/structure/parent_gens.pyx index 3f69b9daee4..6d493e56781 100644 --- a/src/sage/structure/parent_gens.pyx +++ b/src/sage/structure/parent_gens.pyx @@ -73,7 +73,7 @@ cimport sage.structure.parent as parent cimport sage.structure.category_object as category_object -cdef inline check_old_coerce(parent.Parent p): +cdef inline check_old_coerce(parent.Parent p) noexcept: if p._element_constructor is not None: raise RuntimeError("%s still using old coercion framework" % p) diff --git a/src/sage/structure/parent_old.pxd b/src/sage/structure/parent_old.pxd index 54bb4753970..688ae96469a 100644 --- a/src/sage/structure/parent_old.pxd +++ b/src/sage/structure/parent_old.pxd @@ -16,9 +16,9 @@ cdef class Parent(parent.Parent): # Cache for __has_coerce_map_from_c() cdef MonoDict _has_coerce_map_from - cpdef _coerce_c(self, x) - cdef _coerce_c_impl(self, x) + cpdef _coerce_c(self, x) noexcept + cdef _coerce_c_impl(self, x) noexcept - cdef __coerce_map_from_c(self, S) - cdef __coerce_map_from_c_impl(self, S) - cdef __has_coerce_map_from_c(self, S) + cdef __coerce_map_from_c(self, S) noexcept + cdef __coerce_map_from_c_impl(self, S) noexcept + cdef __has_coerce_map_from_c(self, S) noexcept diff --git a/src/sage/structure/parent_old.pyx b/src/sage/structure/parent_old.pyx index 77a7888d3b8..b92a826020f 100644 --- a/src/sage/structure/parent_old.pyx +++ b/src/sage/structure/parent_old.pyx @@ -34,7 +34,7 @@ from sage.sets.pythonclass cimport Set_PythonType, Set_PythonType_class from cpython.object cimport * from cpython.bool cimport * -cdef inline check_old_coerce(Parent p): +cdef inline check_old_coerce(Parent p) noexcept: if p._element_constructor is not None: raise RuntimeError("%s still using old coercion framework" % p) @@ -79,7 +79,7 @@ cdef class Parent(parent.Parent): # New Coercion support functionality ########################################################## - cdef __coerce_map_from_c(self, S): + cdef __coerce_map_from_c(self, S) noexcept: """ EXAMPLES: @@ -143,7 +143,7 @@ cdef class Parent(parent.Parent): return mor - cdef __coerce_map_from_c_impl(self, S): + cdef __coerce_map_from_c_impl(self, S) noexcept: check_old_coerce(self) import sage.categories.morphism from sage.categories.map import Map @@ -183,7 +183,7 @@ cdef class Parent(parent.Parent): check_old_coerce(self) return self._coerce_c(x) - cpdef _coerce_c(self, x): # DO NOT OVERRIDE THIS (call it) + cpdef _coerce_c(self, x) noexcept: # DO NOT OVERRIDE THIS (call it) if self._element_constructor is not None: from sage.misc.superseded import deprecation deprecation(33497, "_coerce_c is deprecated, use coerce instead") @@ -200,7 +200,7 @@ cdef class Parent(parent.Parent): else: return self._coerce_c_impl(x) - cdef _coerce_c_impl(self, x): # OVERRIDE THIS FOR CYTHON CLASSES + cdef _coerce_c_impl(self, x) noexcept: # OVERRIDE THIS FOR CYTHON CLASSES """ Canonically coerce x in assuming that the parent of x is not equal to self. @@ -241,7 +241,7 @@ cdef class Parent(parent.Parent): pass raise TypeError("no canonical coercion of element into self") - cdef __has_coerce_map_from_c(self, S): + cdef __has_coerce_map_from_c(self, S) noexcept: check_old_coerce(self) if self == S: return True @@ -289,7 +289,7 @@ cdef class Parent(parent.Parent): ############################################################### # Coercion Compatibility Layer ############################################################### - cpdef _coerce_map_from_(self, S): + cpdef _coerce_map_from_(self, S) noexcept: if self._element_constructor is None: return self.__coerce_map_from_c(S) else: @@ -303,7 +303,7 @@ cdef class Parent(parent.Parent): self._cache_an_element = self._an_element_impl() return self._cache_an_element - cpdef _generic_convert_map(self, S, category=None): + cpdef _generic_convert_map(self, S, category=None) noexcept: r""" Return a default conversion from ``S``. diff --git a/src/sage/structure/richcmp.pxd b/src/sage/structure/richcmp.pxd index 493af157a79..7db6340ec48 100644 --- a/src/sage/structure/richcmp.pxd +++ b/src/sage/structure/richcmp.pxd @@ -3,7 +3,7 @@ from cpython.object cimport (Py_LT, Py_LE, Py_EQ, Py_NE, Py_GT, Py_GE, PyObject_RichCompare) -cpdef inline richcmp(x, y, int op): +cpdef inline richcmp(x, y, int op) noexcept: """ Return the result of the rich comparison of ``x`` and ``y`` with operator ``op``. @@ -50,10 +50,10 @@ cpdef inline richcmp(x, y, int op): return PyObject_RichCompare(x, y, op) -cpdef richcmp_item(x, y, int op) +cpdef richcmp_item(x, y, int op) noexcept -cpdef inline richcmp_not_equal(x, y, int op): +cpdef inline richcmp_not_equal(x, y, int op) noexcept: """ Like ``richcmp(x, y, op)`` but assuming that `x` is not equal to `y`. @@ -117,7 +117,7 @@ cpdef inline richcmp_not_equal(x, y, int op): return richcmp(x, y, op) -cpdef inline bint rich_to_bool(int op, int c): +cpdef inline bint rich_to_bool(int op, int c) noexcept: """ Return the corresponding ``True`` or ``False`` value for a rich comparison, given the result of an old-style comparison. @@ -184,7 +184,7 @@ cpdef inline bint rich_to_bool(int op, int c): return (bits >> (shift & 31)) & 1 -cpdef inline bint rich_to_bool_sgn(int op, Py_ssize_t c): +cpdef inline bint rich_to_bool_sgn(int op, Py_ssize_t c) noexcept: """ Same as ``rich_to_bool``, but allow any `c < 0` and `c > 0` instead of only `-1` and `1`. @@ -196,7 +196,7 @@ cpdef inline bint rich_to_bool_sgn(int op, Py_ssize_t c): return rich_to_bool(op, (c > 0) - (c < 0)) -cpdef inline int revop(int op): +cpdef inline int revop(int op) noexcept: """ Return the reverse operation of ``op``. diff --git a/src/sage/structure/richcmp.pyx b/src/sage/structure/richcmp.pyx index 465f16e8274..7e1720c0e07 100644 --- a/src/sage/structure/richcmp.pyx +++ b/src/sage/structure/richcmp.pyx @@ -68,7 +68,7 @@ richcmp_slotdef[Py_LE] = get_slotdef(bytes.__le__) richcmp_slotdef[Py_GE] = get_slotdef(bytes.__ge__) -cpdef richcmp_item(x, y, int op): +cpdef richcmp_item(x, y, int op) noexcept: """ This function is meant to implement lexicographic rich comparison of sequences (lists, vectors, polynomials, ...). @@ -266,7 +266,7 @@ cpdef richcmp_item(x, y, int op): return NotImplemented -cdef slot_tp_richcompare(self, other, int op): +cdef slot_tp_richcompare(self, other, int op) noexcept: """ Function to put in the ``tp_richcompare`` slot. """ diff --git a/src/sage/symbolic/comparison_impl.pxi b/src/sage/symbolic/comparison_impl.pxi index c07ed620de1..e4b80ad6fad 100644 --- a/src/sage/symbolic/comparison_impl.pxi +++ b/src/sage/symbolic/comparison_impl.pxi @@ -36,7 +36,7 @@ There is also a mixed version: from cpython cimport * -cdef int print_order_c(Expression lhs, Expression rhs): +cdef int print_order_c(Expression lhs, Expression rhs) noexcept: """ Print comparison. @@ -135,7 +135,7 @@ class _print_key(): return print_order_c(self.ex, other.ex) < 0 -cpdef print_sorted(expressions): +cpdef print_sorted(expressions) noexcept: """ Sort a list in print order @@ -219,7 +219,7 @@ class _math_key(): raise ValueError('cannot compare {0} and {1}'.format(self.ex, other.ex)) -cpdef math_sorted(expressions): +cpdef math_sorted(expressions) noexcept: """ Sort a list of symbolic numbers in the "Mathematics" order @@ -409,7 +409,7 @@ class _mixed_key(): return num < 0 -cpdef mixed_sorted(expressions): +cpdef mixed_sorted(expressions) noexcept: """ Sort a list of symbolic numbers in the "Mixed" order diff --git a/src/sage/symbolic/expression.pxd b/src/sage/symbolic/expression.pxd index 33e352b7f3d..a212eb414c0 100644 --- a/src/sage/symbolic/expression.pxd +++ b/src/sage/symbolic/expression.pxd @@ -1,6 +1,6 @@ -cpdef _repr_Expression(x) -cpdef _latex_Expression(x) -cpdef new_Expression(parent, x) -cpdef new_Expression_from_pyobject(parent, x, bint force=?, bint recursive=?) -cpdef new_Expression_wild(parent, unsigned int n=?) -cpdef new_Expression_symbol(parent, name=?, latex_name=?, domain=?) +cpdef _repr_Expression(x) noexcept +cpdef _latex_Expression(x) noexcept +cpdef new_Expression(parent, x) noexcept +cpdef new_Expression_from_pyobject(parent, x, bint force=?, bint recursive=?) noexcept +cpdef new_Expression_wild(parent, unsigned int n=?) noexcept +cpdef new_Expression_symbol(parent, name=?, latex_name=?, domain=?) noexcept diff --git a/src/sage/symbolic/expression.pyx b/src/sage/symbolic/expression.pyx index 20d7647d2e5..0b80c017a0b 100644 --- a/src/sage/symbolic/expression.pyx +++ b/src/sage/symbolic/expression.pyx @@ -409,7 +409,7 @@ include "pynac_impl.pxi" from sage.symbolic.symbols import symbol_table, register_symbol # used to be defined in pynac_impl -cpdef bint is_SymbolicEquation(x): +cpdef bint is_SymbolicEquation(x) noexcept: """ Return True if *x* is a symbolic equation. @@ -452,7 +452,7 @@ cpdef bint is_SymbolicEquation(x): # Defined here but exported by sage.symbolic.ring -cpdef bint _is_SymbolicVariable(x): +cpdef bint _is_SymbolicVariable(x) noexcept: """ Return ``True`` if ``x`` is a variable. @@ -704,7 +704,7 @@ cdef class Expression(Expression_abc): cdef GEx _gobj - cpdef object pyobject(self): + cpdef object pyobject(self) noexcept: """ Get the underlying Python object. @@ -1577,7 +1577,7 @@ cdef class Expression(Expression_abc): return n return sage.rings.rational.Rational(n) - cpdef _eval_self(self, R): + cpdef _eval_self(self, R) noexcept: """ Evaluate this expression numerically. @@ -1638,7 +1638,7 @@ cdef class Expression(Expression_abc): else: raise TypeError("cannot evaluate symbolic expression to a numeric value") - cpdef _convert(self, kwds): + cpdef _convert(self, kwds) noexcept: """ Convert all the numeric coefficients and constants in this expression to the given ring ``R``. This results in an expression which contains @@ -2178,7 +2178,7 @@ cdef class Expression(Expression_abc): finally: sig_off() - cpdef _richcmp_(left, right, int op): + cpdef _richcmp_(left, right, int op) noexcept: """ Create a formal symbolic inequality or equality. @@ -2945,7 +2945,7 @@ cdef class Expression(Expression_abc): """ return False - cpdef bint is_polynomial(self, var): + cpdef bint is_polynomial(self, var) noexcept: """ Return ``True`` if ``self`` is a polynomial in the given variable. @@ -2998,7 +2998,7 @@ cdef class Expression(Expression_abc): finally: sig_off() - cpdef bint is_relational(self): + cpdef bint is_relational(self) noexcept: r""" Return ``True`` if ``self`` is a relational expression. @@ -3065,7 +3065,7 @@ cdef class Expression(Expression_abc): return all(nelem.pyobject().base_ring().is_exact() for nelem in numelems_gen(self)) - cpdef bint is_infinity(self): + cpdef bint is_infinity(self) noexcept: """ Return ``True`` if ``self`` is an infinite expression. @@ -3078,7 +3078,7 @@ cdef class Expression(Expression_abc): """ return is_a_infinity(self._gobj) - cpdef bint is_positive_infinity(self): + cpdef bint is_positive_infinity(self) noexcept: """ Return ``True`` if ``self`` is a positive infinite expression. @@ -3093,7 +3093,7 @@ cdef class Expression(Expression_abc): """ return is_a_infinity(self._gobj) and self._gobj.info(info_positive) - cpdef bint is_negative_infinity(self): + cpdef bint is_negative_infinity(self) noexcept: """ Return ``True`` if ``self`` is a negative infinite expression. @@ -3798,7 +3798,7 @@ cdef class Expression(Expression_abc): return False raise NotImplementedError - cdef Expression coerce_in(self, z): + cdef Expression coerce_in(self, z) noexcept: """ Quickly coerce z to be an Expression. """ @@ -3807,7 +3807,7 @@ cdef class Expression(Expression_abc): except TypeError: return self._parent.coerce(z) - cpdef _add_(left, right): + cpdef _add_(left, right) noexcept: """ Add left and right. @@ -3902,7 +3902,7 @@ cdef class Expression(Expression_abc): x = left._gobj + _right._gobj return new_Expression_from_GEx(left._parent, x) - cpdef _sub_(left, right): + cpdef _sub_(left, right) noexcept: """ EXAMPLES:: @@ -3954,7 +3954,7 @@ cdef class Expression(Expression_abc): x = left._gobj - _right._gobj return new_Expression_from_GEx(left._parent, x) - cpdef _mul_(left, right): + cpdef _mul_(left, right) noexcept: """ Multiply left and right. @@ -4120,7 +4120,7 @@ cdef class Expression(Expression_abc): x = left._gobj * _right._gobj return new_Expression_from_GEx(left._parent, x) - cpdef _div_(left, right): + cpdef _div_(left, right) noexcept: """ Divide left and right. @@ -4301,7 +4301,7 @@ cdef class Expression(Expression_abc): """ return print_order_compare_mul(left._gobj, right._gobj) - cpdef _pow_(self, other): + cpdef _pow_(self, other) noexcept: r""" Return ``self`` raised to the power ``other``. @@ -4515,7 +4515,7 @@ cdef class Expression(Expression_abc): x = g_pow(self._gobj, nexp._gobj) return new_Expression_from_GEx(self._parent, x) - cpdef _pow_int(self, other): + cpdef _pow_int(self, other) noexcept: """ TESTS:: @@ -5901,7 +5901,7 @@ cdef class Expression(Expression_abc): subs = substitute - cpdef Expression _subs_expr(self, expr): + cpdef Expression _subs_expr(self, expr) noexcept: """ EXAMPLES:: @@ -13532,7 +13532,7 @@ cdef class Expression(Expression_abc): return S -cpdef _repr_Expression(x): +cpdef _repr_Expression(x) noexcept: r""" Return the string representation of the expression ``x``. @@ -13544,7 +13544,7 @@ cpdef _repr_Expression(x): return ccrepr((x)._gobj) -cpdef _latex_Expression(x): +cpdef _latex_Expression(x) noexcept: r""" Return the standard LaTeX version of the expression `x`. @@ -13620,7 +13620,7 @@ def _eval_on_operands(f): cdef dict dynamic_class_cache = {} -cdef get_dynamic_class_for_function(unsigned serial): +cdef get_dynamic_class_for_function(unsigned serial) noexcept: r""" Create a dynamic class corresponding to the function with given ``serial`` that includes dynamic methods defined by the function. @@ -13715,7 +13715,7 @@ cdef get_dynamic_class_for_function(unsigned serial): return cls -cdef Expression new_Expression_from_GEx(parent, GEx juice): +cdef Expression new_Expression_from_GEx(parent, GEx juice) noexcept: cdef type cls cdef Expression nex if is_exactly_a_function(juice): @@ -13731,7 +13731,7 @@ cdef Expression new_Expression_from_GEx(parent, GEx juice): return nex -cpdef new_Expression(parent, x): +cpdef new_Expression(parent, x) noexcept: r""" Convert ``x`` into the symbolic expression ring ``parent``. @@ -13821,7 +13821,7 @@ cpdef new_Expression(parent, x): return new_Expression_from_GEx(parent, exp) -cpdef new_Expression_from_pyobject(parent, x, bint force=True, bint recursive=True): +cpdef new_Expression_from_pyobject(parent, x, bint force=True, bint recursive=True) noexcept: r""" Wrap the given Python object in a symbolic expression even if it cannot be coerced to the Symbolic Ring. @@ -13892,7 +13892,7 @@ cpdef new_Expression_from_pyobject(parent, x, bint force=True, bint recursive=Tr return new_Expression_from_GEx(parent, exp) -cpdef new_Expression_wild(parent, unsigned int n=0): +cpdef new_Expression_wild(parent, unsigned int n=0) noexcept: r""" Return the n-th wild-card for pattern matching and substitution. @@ -13922,7 +13922,7 @@ cpdef new_Expression_wild(parent, unsigned int n=0): return new_Expression_from_GEx(parent, g_wild(n)) -cpdef new_Expression_symbol(parent, name=None, latex_name=None, domain=None): +cpdef new_Expression_symbol(parent, name=None, latex_name=None, domain=None) noexcept: r""" Look up or create a symbol. @@ -14074,7 +14074,7 @@ cdef class ExpressionIterator: self._ind+=1 return new_Expression_from_GEx(self._ex._parent, ex) -cdef inline ExpressionIterator new_ExpIter_from_Expression(Expression ex): +cdef inline ExpressionIterator new_ExpIter_from_Expression(Expression ex) noexcept: """ Construct a new iterator over a symbolic expression. diff --git a/src/sage/symbolic/function.pxd b/src/sage/symbolic/function.pxd index db1ba6c5d54..1987a393f86 100644 --- a/src/sage/symbolic/function.pxd +++ b/src/sage/symbolic/function.pxd @@ -8,21 +8,21 @@ cdef class Function(SageObject): cdef object _latex_name cdef object _conversions cdef object _evalf_params_first - cdef _is_registered(self) - cdef _register_function(self) + cdef _is_registered(self) noexcept + cdef _register_function(self) noexcept cdef class BuiltinFunction(Function): cdef object _preserved_arg - cdef _is_registered(self) + cdef _is_registered(self) noexcept cdef class GinacFunction(BuiltinFunction): cdef object _ginac_name - cdef _is_registered(self) - cdef _register_function(self) + cdef _is_registered(self) noexcept + cdef _register_function(self) noexcept cdef class SymbolicFunction(Function): # cache hash value cdef long _hash_(self) except -1 cdef bint __hinit cdef long __hcache - cdef _is_registered(self) + cdef _is_registered(self) noexcept diff --git a/src/sage/symbolic/function.pyx b/src/sage/symbolic/function.pyx index f4bd22df0a6..589c500d00d 100644 --- a/src/sage/symbolic/function.pyx +++ b/src/sage/symbolic/function.pyx @@ -245,14 +245,14 @@ cdef class Function(SageObject): self._register_function() register_symbol(self, self._conversions) - cdef _is_registered(self): + cdef _is_registered(self) noexcept: """ Check if this function is already registered. If it is, set `self._serial` to the right value. """ raise NotImplementedError("this is an abstract base class, it shouldn't be initialized directly") - cdef _register_function(self): + cdef _register_function(self) noexcept: """ TESTS: @@ -849,14 +849,14 @@ cdef class GinacFunction(BuiltinFunction): evalf_params_first=evalf_params_first, preserved_arg=preserved_arg, alt_name=alt_name) - cdef _is_registered(self): + cdef _is_registered(self) noexcept: # Since this is function is defined in C++, it is already in # ginac's function registry fname = self._ginac_name if self._ginac_name is not None else self._name self._serial = find_registered_function(fname, self._nargs) return bool(get_sfunction_from_serial(self._serial)) - cdef _register_function(self): + cdef _register_function(self) noexcept: # We don't need to add anything to GiNaC's function registry # However, if any custom methods were provided in the python class, # we should set the properties of the function_options object @@ -1085,7 +1085,7 @@ cdef class BuiltinFunction(Function): else: return res - cdef _is_registered(self): + cdef _is_registered(self) noexcept: """ TESTS: @@ -1203,7 +1203,7 @@ cdef class SymbolicFunction(Function): Function.__init__(self, name, nargs, latex_name, conversions, evalf_params_first) - cdef _is_registered(SymbolicFunction self): + cdef _is_registered(SymbolicFunction self) noexcept: # see if there is already a SymbolicFunction with the same state cdef long myhash = self._hash_() cdef SymbolicFunction sfunc = get_sfunction_from_hash(myhash) diff --git a/src/sage/symbolic/pynac_function_impl.pxi b/src/sage/symbolic/pynac_function_impl.pxi index f20c8faf91a..cca1bb5d196 100644 --- a/src/sage/symbolic/pynac_function_impl.pxi +++ b/src/sage/symbolic/pynac_function_impl.pxi @@ -3,7 +3,7 @@ cpdef call_registered_function(unsigned serial, list args, bint hold, bint allow_numeric_result, - result_parent): + result_parent) noexcept: r""" Call a function registered with Pynac (GiNaC). @@ -173,7 +173,7 @@ cpdef unsigned register_or_update_function(self, name, latex_name, int nargs, cdef dict sfunction_serial_dict = {} -cpdef get_sfunction_from_serial(unsigned int serial): +cpdef get_sfunction_from_serial(unsigned int serial) noexcept: """ Return an already created :class:`SymbolicFunction` given the serial. @@ -189,7 +189,7 @@ cpdef get_sfunction_from_serial(unsigned int serial): return sfunction_serial_dict.get(serial) -cpdef get_sfunction_from_hash(long myhash): +cpdef get_sfunction_from_hash(long myhash) noexcept: """ Return an already created :class:`SymbolicFunction` given the hash. diff --git a/src/sage/symbolic/pynac_impl.pxi b/src/sage/symbolic/pynac_impl.pxi index 7fd7c3b314b..88436ee2705 100644 --- a/src/sage/symbolic/pynac_impl.pxi +++ b/src/sage/symbolic/pynac_impl.pxi @@ -61,7 +61,7 @@ from sage.symbolic.function cimport Function # Symbolic function helpers ################################################################# -cdef ex_to_pyExpression(GEx juice): +cdef ex_to_pyExpression(GEx juice) noexcept: """ Convert given GiNaC::ex object to a python Expression instance. @@ -74,7 +74,7 @@ cdef ex_to_pyExpression(GEx juice): nex._parent = SR return nex -cdef exprseq_to_PyTuple(GEx seq): +cdef exprseq_to_PyTuple(GEx seq) noexcept: """ Convert an exprseq to a Python tuple. @@ -134,7 +134,7 @@ def unpack_operands(Expression ex): return exprseq_to_PyTuple(ex._gobj) -cdef exvector_to_PyTuple(GExVector seq): +cdef exvector_to_PyTuple(GExVector seq) noexcept: """ Converts arguments list given to a function to a PyTuple. @@ -196,7 +196,7 @@ cdef GEx pyExpression_to_ex(res) except *: raise TypeError("function did not return a symbolic expression or an element that can be coerced into a symbolic expression") return (t)._gobj -cdef paramset_to_PyTuple(const_paramset_ref s): +cdef paramset_to_PyTuple(const_paramset_ref s) noexcept: """ Converts a std::multiset to a PyTuple. @@ -226,7 +226,7 @@ def paramset_from_Expression(Expression e): cdef int GINAC_FN_SERIAL = 0 -cdef set_ginac_fn_serial(): +cdef set_ginac_fn_serial() noexcept: """ Initialize the GINAC_FN_SERIAL variable to the number of functions defined by GiNaC. This allows us to prevent collisions with C++ level @@ -236,7 +236,7 @@ cdef set_ginac_fn_serial(): global GINAC_FN_SERIAL GINAC_FN_SERIAL = g_registered_functions().size() -cdef int py_get_ginac_serial(): +cdef int py_get_ginac_serial() noexcept: """ Returns the number of C++ level functions defined by GiNaC. @@ -262,7 +262,7 @@ def get_ginac_serial(): return py_get_ginac_serial() -cdef get_fn_serial_c(): +cdef get_fn_serial_c() noexcept: """ Return overall size of Pynac function registry. """ @@ -288,7 +288,7 @@ def get_fn_serial(): return get_fn_serial_c() -cdef subs_args_to_PyTuple(const GExMap& map, unsigned options, const GExVector& seq): +cdef subs_args_to_PyTuple(const GExMap& map, unsigned options, const GExVector& seq) noexcept: """ Convert arguments from ``GiNaC::subs()`` to a PyTuple. @@ -339,7 +339,7 @@ cdef subs_args_to_PyTuple(const GExMap& map, unsigned options, const GExVector& # Structure: 70 ########################################################################## -cdef stdstring* py_repr(o, int level): +cdef stdstring* py_repr(o, int level) noexcept: """ Return string representation of o. If level > 0, possibly put parentheses around the string. @@ -363,7 +363,7 @@ cdef stdstring* py_repr(o, int level): return string_from_pystr(s) -cdef stdstring* py_latex(o, int level): +cdef stdstring* py_latex(o, int level) noexcept: """ Return latex string representation of o. If level > 0, possibly put parentheses around the string. @@ -395,7 +395,7 @@ cdef stdstring* string_from_pystr(py_str) except NULL: s = b"(INVALID)" # Avoid segfaults for invalid input return new stdstring(s) -cdef stdstring* py_latex_variable(var_name): +cdef stdstring* py_latex_variable(var_name) noexcept: r""" Return a c++ string containing the latex representation of the given variable name. @@ -506,7 +506,7 @@ def py_print_function_pystring(id, args, fname_paren=False): return ''.join(olist) -cdef stdstring* py_print_function(unsigned id, args): +cdef stdstring* py_print_function(unsigned id, args) noexcept: return string_from_pystr(py_print_function_pystring(id, args)) @@ -598,7 +598,7 @@ def py_latex_function_pystring(id, args, fname_paren=False): return ''.join(olist) -cdef stdstring* py_latex_function(unsigned id, args): +cdef stdstring* py_latex_function(unsigned id, args) noexcept: return string_from_pystr(py_latex_function_pystring(id, args)) @@ -628,7 +628,7 @@ def tolerant_is_symbol(a): cdef stdstring* py_print_fderivative(unsigned id, params, - args): + args) noexcept: """ Return a string with the representation of the derivative of the symbolic function specified by the given id, lists of params and args. @@ -689,7 +689,7 @@ def py_print_fderivative_for_doctests(id, params, args): cdef stdstring* py_latex_fderivative(unsigned id, params, - args): + args) noexcept: """ Return a string with the latex representation of the derivative of the symbolic function specified by the given id, lists of params and args. @@ -780,7 +780,7 @@ def py_latex_fderivative_for_doctests(id, params, args): # Archive helpers ################################################################# -cdef stdstring* py_dumps(o): +cdef stdstring* py_dumps(o) noexcept: s = dumps(o, compress=False) # pynac archive format terminates atoms with zeroes. # since pickle output can break the archive format @@ -789,18 +789,18 @@ cdef stdstring* py_dumps(o): s = base64.b64encode(s) return string_from_pystr(s) -cdef py_loads(s): +cdef py_loads(s) noexcept: import base64 s = base64.b64decode(s) return loads(s) -cdef py_get_sfunction_from_serial(unsigned s): +cdef py_get_sfunction_from_serial(unsigned s) noexcept: """ Return the Python object associated with a serial. """ return get_sfunction_from_serial(s) -cdef unsigned py_get_serial_from_sfunction(f): +cdef unsigned py_get_serial_from_sfunction(f) noexcept: """ Given a Function object return its serial. @@ -814,7 +814,7 @@ cdef unsigned py_get_serial_from_sfunction(f): return (f)._serial cdef unsigned py_get_serial_for_new_sfunction(stdstring &s, - unsigned nargs): + unsigned nargs) noexcept: """ Return a symbolic function with the given name and number of arguments. @@ -869,7 +869,7 @@ cdef int py_get_parent_char(o) except -1: # power helpers ################################################################# -cdef py_rational_power_parts(base, exp): +cdef py_rational_power_parts(base, exp) noexcept: if type(base) is not Rational: base = Rational(base) if type(exp) is not Rational: @@ -882,7 +882,7 @@ cdef py_rational_power_parts(base, exp): ################################################################# -cdef py_binomial_int(int n, unsigned int k): +cdef py_binomial_int(int n, unsigned int k) noexcept: cdef bint sign if n < 0: n = -n + (k-1) @@ -898,7 +898,7 @@ cdef py_binomial_int(int n, unsigned int k): else: return ans -cdef py_binomial(n, k): +cdef py_binomial(n, k) noexcept: # Keep track of the sign we should use. cdef bint sign if n < 0: @@ -949,7 +949,7 @@ def test_binomial(n, k): ################################################################# # GCD ################################################################# -cdef py_gcd(n, k): +cdef py_gcd(n, k) noexcept: if isinstance(n, Integer) and isinstance(k, Integer): if mpz_cmp_si((n).value, 1) == 0: return n @@ -969,7 +969,7 @@ cdef py_gcd(n, k): ################################################################# # LCM ################################################################# -cdef py_lcm(n, k): +cdef py_lcm(n, k) noexcept: if isinstance(n, Integer) and isinstance(k, Integer): if mpz_cmp_si((n).value, 1) == 0: return k @@ -987,7 +987,7 @@ cdef py_lcm(n, k): ################################################################# # Real Part ################################################################# -cdef py_real(x): +cdef py_real(x) noexcept: """ Returns the real part of x. @@ -1046,7 +1046,7 @@ def py_real_for_doctests(x): ################################################################# # Imaginary Part ################################################################# -cdef py_imag(x): +cdef py_imag(x) noexcept: """ Return the imaginary part of x. @@ -1103,27 +1103,27 @@ def py_imag_for_doctests(x): ################################################################# # Conjugate ################################################################# -cdef py_conjugate(x): +cdef py_conjugate(x) noexcept: try: return x.conjugate() except AttributeError: return x # assume is real since it doesn't have an imag attribute. -cdef bint py_is_rational(x): +cdef bint py_is_rational(x) noexcept: return (type(x) is Rational or type(x) is Integer or isinstance(x, int)) -cdef bint py_is_equal(x, y): +cdef bint py_is_equal(x, y) noexcept: """ Return True precisely if x and y are equal. """ return bool(x == y) -cdef bint py_is_integer(x): +cdef bint py_is_integer(x) noexcept: r""" Returns True if pynac should treat this object as an integer. @@ -1176,7 +1176,7 @@ def py_is_integer_for_doctests(x): return py_is_integer(x) -cdef bint py_is_even(x): +cdef bint py_is_even(x) noexcept: try: return not(x % 2) except Exception: @@ -1187,7 +1187,7 @@ cdef bint py_is_even(x): return 0 -cdef bint py_is_crational(x): +cdef bint py_is_crational(x) noexcept: if py_is_rational(x): return True return isinstance(x, Element) and (x)._parent is pynac_I._parent @@ -1214,7 +1214,7 @@ def py_is_crational_for_doctest(x): return py_is_crational(x) -cdef bint py_is_real(a): +cdef bint py_is_real(a) noexcept: if isinstance(a, (int, Integer, float)): return True try: @@ -1228,7 +1228,7 @@ cdef bint py_is_real(a): return py_imag(a) == 0 -cdef bint py_is_prime(n): +cdef bint py_is_prime(n) noexcept: try: return n.is_prime() except Exception: # yes, I'm doing this on purpose. @@ -1240,7 +1240,7 @@ cdef bint py_is_prime(n): return False -cdef bint py_is_exact(x): +cdef bint py_is_exact(x) noexcept: if isinstance(x, (int, Integer)): return True if not isinstance(x, Element): @@ -1250,7 +1250,7 @@ cdef bint py_is_exact(x): return isinstance(P, SymbolicRing) or P.is_exact() -cdef py_numer(n): +cdef py_numer(n) noexcept: """ Return the numerator of the given object. This is called for typesetting coefficients. @@ -1298,7 +1298,7 @@ def py_numer_for_doctests(n): """ return py_numer(n) -cdef py_denom(n): +cdef py_denom(n) noexcept: """ Return the denominator of the given object. This is called for typesetting coefficients. @@ -1335,7 +1335,7 @@ def py_denom_for_doctests(n): return py_denom(n) -cdef bint py_is_cinteger(x): +cdef bint py_is_cinteger(x) noexcept: return py_is_integer(x) or (py_is_crational(x) and py_denom(x) == 1) @@ -1357,7 +1357,7 @@ def py_is_cinteger_for_doctest(x): """ return py_is_cinteger(x) -cdef py_float(n, PyObject* kwds): +cdef py_float(n, PyObject* kwds) noexcept: """ Evaluate pynac numeric objects numerically. @@ -1416,7 +1416,7 @@ def py_float_for_doctests(n, kwds): return py_float(n, kwds) -cdef py_RDF_from_double(double x): +cdef py_RDF_from_double(double x) noexcept: cdef RealDoubleElement r = RealDoubleElement.__new__(RealDoubleElement) r._value = x return r @@ -1424,7 +1424,7 @@ cdef py_RDF_from_double(double x): ################################################################# # SPECIAL FUNCTIONS ################################################################# -cdef py_tgamma(x): +cdef py_tgamma(x) noexcept: """ The gamma function exported to pynac. @@ -1469,7 +1469,7 @@ def py_tgamma_for_doctests(x): """ return py_tgamma(x) -cdef py_factorial(x): +cdef py_factorial(x) noexcept: """ The factorial function exported to pynac. @@ -1510,7 +1510,7 @@ def py_factorial_py(x): """ return py_factorial(x) -cdef py_doublefactorial(x): +cdef py_doublefactorial(x) noexcept: n = Integer(x) if n < -1: raise ValueError("argument must be >= -1") @@ -1546,10 +1546,10 @@ def doublefactorial(n): return py_doublefactorial(n) -cdef py_fibonacci(n): +cdef py_fibonacci(n) noexcept: return Integer(pari(n).fibonacci()) -cdef py_step(n): +cdef py_step(n) noexcept: """ Return step function of n. """ @@ -1560,10 +1560,10 @@ cdef py_step(n): return SR(1) return SR(Rational((1,2))) -cdef py_bernoulli(x): +cdef py_bernoulli(x) noexcept: return bernoulli(x) -cdef py_sin(x): +cdef py_sin(x) noexcept: """ TESTS:: @@ -1585,7 +1585,7 @@ cdef py_sin(x): except (TypeError, ValueError): return CC(x).sin() -cdef py_cos(x): +cdef py_cos(x) noexcept: """ TESTS:: @@ -1607,7 +1607,7 @@ cdef py_cos(x): except (TypeError, ValueError): return CC(x).cos() -cdef py_stieltjes(x): +cdef py_stieltjes(x) noexcept: """ Return the Stieltjes constant of the given index. @@ -1649,7 +1649,7 @@ def py_stieltjes_for_doctests(x): """ return py_stieltjes(x) -cdef py_zeta(x): +cdef py_zeta(x) noexcept: """ Return the value of the zeta function at the given value. @@ -1683,7 +1683,7 @@ def py_zeta_for_doctests(x): """ return py_zeta(x) -cdef py_exp(x): +cdef py_exp(x) noexcept: """ Return the value of the exp function at the given value. @@ -1724,7 +1724,7 @@ def py_exp_for_doctests(x): """ return py_exp(x) -cdef py_log(x): +cdef py_log(x) noexcept: """ Return the value of the log function at the given value. @@ -1793,7 +1793,7 @@ def py_log_for_doctests(x): """ return py_log(x) -cdef py_tan(x): +cdef py_tan(x) noexcept: try: return x.tan() except AttributeError: @@ -1803,28 +1803,28 @@ cdef py_tan(x): except TypeError: return CC(x).tan() -cdef py_asin(x): +cdef py_asin(x) noexcept: try: return x.arcsin() except AttributeError: return RR(x).arcsin() -cdef py_acos(x): +cdef py_acos(x) noexcept: try: return x.arccos() except AttributeError: return RR(x).arccos() -cdef py_atan(x): +cdef py_atan(x) noexcept: try: return x.arctan() except AttributeError: return RR(x).arctan() -cdef py_atan2(x, y): +cdef py_atan2(x, y) noexcept: """ Return the value of the two argument arctan function at the given values. @@ -1909,14 +1909,14 @@ def py_atan2_for_doctests(x, y): return py_atan2(x, y) -cdef py_sinh(x): +cdef py_sinh(x) noexcept: try: return x.sinh() except AttributeError: return RR(x).sinh() -cdef py_cosh(x): +cdef py_cosh(x) noexcept: if type(x) is float: return math.cosh(PyFloat_AS_DOUBLE(x)) try: @@ -1925,14 +1925,14 @@ cdef py_cosh(x): return RR(x).cosh() -cdef py_tanh(x): +cdef py_tanh(x) noexcept: try: return x.tanh() except AttributeError: return RR(x).tanh() -cdef py_asinh(x): +cdef py_asinh(x) noexcept: try: return x.arcsinh() except AttributeError: @@ -1943,7 +1943,7 @@ cdef py_asinh(x): return CC(x).arcsinh() -cdef py_acosh(x): +cdef py_acosh(x) noexcept: try: return x.arccosh() except AttributeError: @@ -1954,7 +1954,7 @@ cdef py_acosh(x): return CC(x).arccosh() -cdef py_atanh(x): +cdef py_atanh(x) noexcept: try: return x.arctanh() except AttributeError: @@ -1965,7 +1965,7 @@ cdef py_atanh(x): return CC(x).arctanh() -cdef py_lgamma(x): +cdef py_lgamma(x) noexcept: """ Return the value of the principal branch of the log gamma function at the given value. @@ -2012,11 +2012,11 @@ def py_lgamma_for_doctests(x): return py_lgamma(x) -cdef py_isqrt(x): +cdef py_isqrt(x) noexcept: return Integer(x).isqrt() -cdef py_sqrt(x): +cdef py_sqrt(x) noexcept: try: # WORRY: What if Integer's sqrt calls symbolic one and we go in circle? return x.sqrt() @@ -2024,11 +2024,11 @@ cdef py_sqrt(x): return math.sqrt(float(x)) -cdef py_abs(x): +cdef py_abs(x) noexcept: return abs(x) -cdef py_mod(x, n): +cdef py_mod(x, n) noexcept: """ Return x mod n. Both x and n are assumed to be integers. @@ -2076,7 +2076,7 @@ def py_mod_for_doctests(x, n): return py_mod(x, n) -cdef py_smod(a, b): +cdef py_smod(a, b) noexcept: # Modulus (in symmetric representation). # Equivalent to Maple's mods. # returns a mod b in the range [-iquo(abs(b)-1,2), iquo(abs(b),2)] @@ -2089,15 +2089,15 @@ cdef py_smod(a, b): return c -cdef py_irem(x, n): +cdef py_irem(x, n) noexcept: return Integer(x) % Integer(n) -cdef py_iquo(x, n): +cdef py_iquo(x, n) noexcept: return Integer(x)//Integer(n) -cdef py_iquo2(x, n): +cdef py_iquo2(x, n) noexcept: x = Integer(x) n = Integer(n) try: @@ -2115,7 +2115,7 @@ cdef int py_int_length(x) except -1: return Integer(x).nbits() -cdef py_li(x, n, parent): +cdef py_li(x, n, parent) noexcept: """ Returns a numerical approximation of polylog(n, x) with precision given by the ``parent`` argument. @@ -2152,7 +2152,7 @@ def py_li_for_doctests(x, n, parent): return py_li(x, n, parent) -cdef py_psi(x): +cdef py_psi(x) noexcept: """ EXAMPLES:: @@ -2187,7 +2187,7 @@ def py_psi_for_doctests(x): """ return py_psi(x) -cdef py_psi2(n, x): +cdef py_psi2(n, x) noexcept: """ EXAMPLES:: @@ -2215,7 +2215,7 @@ def py_psi2_for_doctests(n, x): """ return py_psi2(n, x) -cdef py_li2(x): +cdef py_li2(x) noexcept: """ EXAMPLES:: @@ -2249,7 +2249,7 @@ def py_li2_for_doctests(x): # Constants ################################################################## -cdef GConstant py_get_constant(const char* name): +cdef GConstant py_get_constant(const char* name) noexcept: """ Returns a constant given its name. This is called by constant::unarchive in constant.cpp in Pynac and is used for @@ -2264,12 +2264,12 @@ cdef GConstant py_get_constant(const char* name): pc = c._pynac return pc.pointer[0] -cdef py_eval_constant(unsigned serial, kwds): +cdef py_eval_constant(unsigned serial, kwds) noexcept: from sage.symbolic.constants import constants_table constant = constants_table[serial] return kwds['parent'](constant) -cdef py_eval_unsigned_infinity(): +cdef py_eval_unsigned_infinity() noexcept: """ Returns unsigned_infinity. """ @@ -2288,7 +2288,7 @@ def py_eval_unsigned_infinity_for_doctests(): """ return py_eval_unsigned_infinity() -cdef py_eval_infinity(): +cdef py_eval_infinity() noexcept: """ Returns positive infinity, i.e., oo. """ @@ -2307,7 +2307,7 @@ def py_eval_infinity_for_doctests(): """ return py_eval_infinity() -cdef py_eval_neg_infinity(): +cdef py_eval_neg_infinity() noexcept: """ Returns minus_infinity. """ @@ -2330,37 +2330,37 @@ def py_eval_neg_infinity_for_doctests(): # Constructors ################################################################## -cdef py_integer_from_long(long x): +cdef py_integer_from_long(long x) noexcept: return smallInteger(x) -cdef py_integer_from_python_obj(x): +cdef py_integer_from_python_obj(x) noexcept: return Integer(x) -cdef py_integer_from_mpz(mpz_t bigint): +cdef py_integer_from_mpz(mpz_t bigint) noexcept: cdef Integer z = PY_NEW(Integer) mpz_set(z.value, bigint) return z -cdef py_rational_from_mpq(mpq_t bigrat): +cdef py_rational_from_mpq(mpq_t bigrat) noexcept: cdef Rational rat = Rational.__new__(Rational) mpq_set(rat.value, bigrat) mpq_canonicalize(rat.value) return rat -cdef bint py_is_Integer(x): +cdef bint py_is_Integer(x) noexcept: return isinstance(x, Integer) -cdef bint py_is_Rational(x): +cdef bint py_is_Rational(x) noexcept: return isinstance(x, Rational) -cdef mpz_ptr py_mpz_from_integer(x): +cdef mpz_ptr py_mpz_from_integer(x) noexcept: return ((x).value) -cdef mpq_ptr py_mpq_from_rational(x): +cdef mpq_ptr py_mpq_from_rational(x) noexcept: return ((x).value) diff --git a/src/sage/symbolic/ring.pyx b/src/sage/symbolic/ring.pyx index 822eaacd30b..f3f32b9c922 100644 --- a/src/sage/symbolic/ring.pyx +++ b/src/sage/symbolic/ring.pyx @@ -122,7 +122,7 @@ cdef class SymbolicRing(sage.rings.abc.SymbolicRing): """ return r'\text{SR}' - cpdef _coerce_map_from_(self, R): + cpdef _coerce_map_from_(self, R) noexcept: """ EXAMPLES:: @@ -1221,7 +1221,7 @@ cdef class NumpyToSRMorphism(Morphism): else: raise TypeError("{} is not a numpy number type".format(numpy_type)) - cpdef Element _call_(self, a): + cpdef Element _call_(self, a) noexcept: """ EXAMPLES: @@ -1268,7 +1268,7 @@ cdef class UnderscoreSageMorphism(Morphism): from sage.interfaces.sympy import sympy_init sympy_init() - cpdef Element _call_(self, a): + cpdef Element _call_(self, a) noexcept: """ EXAMPLES: diff --git a/src/sage/symbolic/substitution_map_impl.pxi b/src/sage/symbolic/substitution_map_impl.pxi index ea60e899d1a..c1dc3be748b 100644 --- a/src/sage/symbolic/substitution_map_impl.pxi +++ b/src/sage/symbolic/substitution_map_impl.pxi @@ -24,7 +24,7 @@ cdef class SubstitutionMap(SageObject): cdef GExMap _gmapobj - cpdef Expression apply_to(self, Expression expr, unsigned options): + cpdef Expression apply_to(self, Expression expr, unsigned options) noexcept: """ Apply the substitution to a symbolic expression @@ -51,7 +51,7 @@ cdef class SubstitutionMap(SageObject): return 'SubsMap' # GEx_to_str(&x._gobj) -cdef SubstitutionMap new_SubstitutionMap_from_GExMap(const GExMap& smap): +cdef SubstitutionMap new_SubstitutionMap_from_GExMap(const GExMap& smap) noexcept: """ Wrap a Pynac object into a Python object @@ -75,7 +75,7 @@ cdef SubstitutionMap new_SubstitutionMap_from_GExMap(const GExMap& smap): return result -cpdef SubstitutionMap make_map(subs_dict): +cpdef SubstitutionMap make_map(subs_dict) noexcept: """ Construct a new substitution map diff --git a/src/sage/tensor/modules/finite_rank_free_module.py b/src/sage/tensor/modules/finite_rank_free_module.py index d868c50b109..d8d8686eeae 100644 --- a/src/sage/tensor/modules/finite_rank_free_module.py +++ b/src/sage/tensor/modules/finite_rank_free_module.py @@ -1210,7 +1210,7 @@ def __classcall_private__(cls, ring, rank, name=None, latex_name=None, start_ind category = Modules(ring).FiniteDimensional().or_subcategory(category) if latex_name is None: latex_name = name - return super(FiniteRankFreeModule, cls).__classcall__( + return super().__classcall__( cls, ring, rank, name, latex_name, start_index, output_formatter, category, ambient) def __init__( diff --git a/src/sage/tensor/modules/free_module_basis.py b/src/sage/tensor/modules/free_module_basis.py index 7fb776621b9..e44276a4317 100644 --- a/src/sage/tensor/modules/free_module_basis.py +++ b/src/sage/tensor/modules/free_module_basis.py @@ -700,7 +700,7 @@ def __classcall_private__(cls, fmodule, symbol, latex_symbol=None, symbol_dual = tuple(symbol_dual) if isinstance(latex_symbol_dual, list): latex_symbol_dual = tuple(latex_symbol_dual) - return super(FreeModuleBasis, cls).__classcall__(cls, fmodule, symbol, + return super().__classcall__(cls, fmodule, symbol, latex_symbol=latex_symbol, indices=indices, latex_indices=latex_indices, diff --git a/src/sage/tests/stl_vector.pyx b/src/sage/tests/stl_vector.pyx index f3b29b30dfe..2a7c1bf5d05 100644 --- a/src/sage/tests/stl_vector.pyx +++ b/src/sage/tests/stl_vector.pyx @@ -115,7 +115,7 @@ cdef class stl_int_vector(SageObject): s += ' data[' + str(i) + '] = ' + str(self.data.at(i)) + '\n' return s.strip() - cpdef sum(self): + cpdef sum(self) noexcept: """ Add the elements. diff --git a/src/sage/topology/simplicial_complex.py b/src/sage/topology/simplicial_complex.py index e3b8f9a853c..8ca615e3488 100644 --- a/src/sage/topology/simplicial_complex.py +++ b/src/sage/topology/simplicial_complex.py @@ -1394,8 +1394,7 @@ def face_iterator(self, increasing=True): if not increasing: dim_index = reversed(dim_index) for i in dim_index: - for F in Fs[i]: - yield F + yield from Fs[i] cells = faces diff --git a/src/sage/version.py b/src/sage/version.py index ab26727486a..f00a3e839af 100644 --- a/src/sage/version.py +++ b/src/sage/version.py @@ -1,5 +1,5 @@ # Sage version information for Python scripts # This file is auto-generated by the sage-update-version script, do not edit! -version = '10.2.beta8' -date = '2023-10-21' -banner = 'SageMath version 10.2.beta8, Release Date: 2023-10-21' +version = '10.2.beta9' +date = '2023-10-30' +banner = 'SageMath version 10.2.beta9, Release Date: 2023-10-30' diff --git a/src/sage_docbuild/__main__.py b/src/sage_docbuild/__main__.py index 77919ec4000..0d15808a69c 100644 --- a/src/sage_docbuild/__main__.py +++ b/src/sage_docbuild/__main__.py @@ -294,6 +294,9 @@ def setup_parser(): standard.add_argument("--no-pdf-links", dest="no_pdf_links", action="store_true", help="do not include PDF links in DOCUMENT 'website'; FORMATs: html, json, pickle, web") + standard.add_argument("--live-doc", dest="live_doc", + action="store_true", + help="make Sage code blocks live for html FORMAT") standard.add_argument("--warn-links", dest="warn_links", action="store_true", help="issue a warning whenever a link is not properly resolved; equivalent to '--sphinx-opts -n' (sphinx option: nitpicky)") @@ -474,6 +477,8 @@ def excepthook(*exc_info): build_options.ALLSPHINXOPTS += "-n " if args.no_plot: os.environ['SAGE_SKIP_PLOT_DIRECTIVE'] = 'yes' + if args.live_doc: + os.environ['SAGE_LIVE_DOC'] = 'yes' if args.skip_tests: os.environ['SAGE_SKIP_TESTS_BLOCKS'] = 'True' if args.use_cdns: diff --git a/src/sage_docbuild/conf.py b/src/sage_docbuild/conf.py index 5eca4ed29b0..93333c2509d 100644 --- a/src/sage_docbuild/conf.py +++ b/src/sage_docbuild/conf.py @@ -27,12 +27,14 @@ import sage.version from sphinx import highlighting +from sphinx.transforms import SphinxTransform from IPython.lib.lexers import IPythonConsoleLexer, IPyLexer from sage.misc.sagedoc import extlinks -from sage.env import SAGE_DOC_SRC, SAGE_DOC, THEBE_DIR, PPLPY_DOCS, MATHJAX_DIR +from sage.env import SAGE_DOC_SRC, SAGE_DOC, PPLPY_DOCS, MATHJAX_DIR from sage.misc.latex_macros import sage_mathjax_macros from sage.features import PythonModule +from sage.features.all import all_features # General configuration # --------------------- @@ -54,17 +56,56 @@ jupyter_execute_default_kernel = 'sagemath' -jupyter_sphinx_thebelab_config = { - 'requestKernel': True, - 'binderOptions': { - 'repo': "sagemath/sage-binder-env", - }, - 'kernelOptions': { - 'name': "sagemath", - 'kernelName': "sagemath", - 'path': ".", - }, -} +if os.environ.get('SAGE_LIVE_DOC', 'no') == 'yes': + SAGE_JUPYTER_SERVER = os.environ.get('SAGE_JUPYTER_SERVER', 'binder') + if SAGE_JUPYTER_SERVER.startswith('binder'): + # format: "binder" or + # "binder:sagemath/sage-binder-env" or + # "binder:sagemath/sage-binder-env/dev" + if SAGE_JUPYTER_SERVER == 'binder': + binder_repo = "sagemath/sage-binder-env/master" + else: + binder_repo = SAGE_JUPYTER_SERVER[7:] + s = binder_repo.split('/', 2) + if len(s) > 2: + binder_options = { + 'repo': s[0] + '/' + s[1], + 'ref': s[2] + } + else: + binder_options = { + 'repo': binder_repo + } + jupyter_sphinx_thebelab_config = { + 'requestKernel': False, + 'binderOptions': binder_options, + 'kernelOptions': { + 'name': "sagemath", + 'kernelName': "sagemath", + 'path': ".", + }, + 'selector': "div.live-doc" + } + else: # local jupyter server + SAGE_JUPYTER_SERVER_TOKEN = os.environ.get('SAGE_JUPYTER_SERVER_TOKEN', 'secret') + jupyter_sphinx_thebelab_config = { + 'requestKernel': False, + 'kernelOptions': { + 'name': "sagemath", + 'kernelName': "sagemath", + 'path': ".", + 'serverSettings': { + 'baseUrl': SAGE_JUPYTER_SERVER, + 'token': SAGE_JUPYTER_SERVER_TOKEN + }, + }, + 'selector': "div.live-doc" + } + jupyter_sphinx_thebelab_config.update({ + 'codeMirrorConfig': { + 'lineNumbers': True, + } + }) # This code is executed before each ".. PLOT::" directive in the Sphinx # documentation. It defines a 'sphinx_plot' function that displays a Sage object @@ -310,7 +351,14 @@ def set_intersphinx_mappings(app, config): # or fully qualified paths (eg. https://...) html_css_files = [ 'custom-furo.css', + 'custom-jupyter-sphinx.css', + 'custom-codemirror-monokai.css', + ] + + html_js_files = [ + 'jupyter-sphinx-furo.js', ] + # A list of paths that contain extra templates (or templates that overwrite # builtin/theme-specific templates). Relative paths are taken as relative # to the configuration directory. @@ -348,8 +396,7 @@ def set_intersphinx_mappings(app, config): # conf.py read by Sphinx was the cause of subtle bugs in builders (see #30418 for # instance). Hence now html_common_static_path contains the common paths to static # files, and is combined to html_static_path in each conf.py file read by Sphinx. -html_common_static_path = [os.path.join(SAGE_DOC_SRC, 'common', 'static'), - THEBE_DIR, 'static'] +html_common_static_path = [os.path.join(SAGE_DOC_SRC, 'common', 'static'), 'static'] # Configure MathJax # https://docs.mathjax.org/en/latest/options/input/tex.html @@ -913,6 +960,69 @@ class will be properly documented inside its surrounding class. return skip +from jupyter_sphinx.ast import JupyterCellNode, CellInputNode + +class SagecodeTransform(SphinxTransform): + """ + Transform a code block to a live code block enabled by jupyter-sphinx. + + Effectively a code block like:: + + EXAMPLE:: + + sage: 1 + 1 + 2 + + is transformed into:: + + EXAMPLE:: + + sage: 1 + 1 + 2 + + .. ONLY:: html + + .. JUPYTER-EXECUTE:: + :hide-code: + :hide-output: + :raises: + :stderr: + + 1 + 1 + + enabling live execution of the code. + """ + # lower than the priority of jupyer_sphinx.execute.ExecuteJupyterCells + default_priority = 170 + + def apply(self): + if self.app.builder.tags.has('html') or self.app.builder.tags.has('inventory'): + for node in self.document.traverse(nodes.literal_block): + if node.get('language') is None and node.astext().startswith('sage:'): + source = node.rawsource + lines = [] + for line in source.splitlines(): + newline = line.lstrip() + if newline.startswith('sage: ') or newline.startswith('....: '): + lines.append(newline[6:]) + cell_node = JupyterCellNode( + execute=False, + hide_code=True, + hide_output=True, + emphasize_lines=[], + raises=False, + stderr=True, + code_below=False, + classes=["jupyter_cell"]) + cell_input = CellInputNode(classes=['cell_input','live-doc']) + cell_input += nodes.literal_block( + text='\n'.join(lines), + linenos=False, + linenostart=1) + cell_node += cell_input + + node.parent.insert(node.parent.index(node) + 1, cell_node) + # This replaces the setup() in sage.misc.sagedoc_conf def setup(app): app.connect('autodoc-process-docstring', process_docstring_cython) @@ -924,6 +1034,8 @@ def setup(app): app.connect('autodoc-process-docstring', skip_TESTS_block) app.connect('autodoc-skip-member', skip_member) app.add_transform(SagemathTransform) + if os.environ.get('SAGE_LIVE_DOC', 'no') == 'yes': + app.add_transform(SagecodeTransform) # When building the standard docs, app.srcdir is set to SAGE_DOC_SRC + # 'LANGUAGE/DOCNAME'. @@ -940,3 +1052,18 @@ def setup(app): app.connect('missing-reference', find_sage_dangling_links) app.connect('builder-inited', nitpick_patch_config) app.connect('html-page-context', add_page_context) + + +# Conditional content +# https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#tags +# https://www.sphinx-doc.org/en/master/usage/configuration.html#conf-tags +# https://github.com/readthedocs/readthedocs.org/issues/4603#issuecomment-1411594800 +# Workaround to allow importing this file from other confs +if 'tags' not in locals(): + class Tags(set): + has = set.__contains__ + tags = Tags() + + +for feature in all_features(): + tags.add('feature_' + feature.name.replace('.', '_')) diff --git a/src/sage_docbuild/sphinxbuild.py b/src/sage_docbuild/sphinxbuild.py index 94407cad5eb..5ae1d2e6b10 100644 --- a/src/sage_docbuild/sphinxbuild.py +++ b/src/sage_docbuild/sphinxbuild.py @@ -77,14 +77,14 @@ def _init_chatter(self): re.compile(r'^loading cross citations... done \([0-9]* citations\).'), re.compile('^Compiling a sub-document'), re.compile('^updating environment: 0 added, 0 changed, 0 removed'), + re.compile('^executing .*'), re.compile('^looking for now-outdated files... none found'), re.compile(r'^building \[.*\]: targets for 0 source files that are out of date'), re.compile(r'^building \[.*\]: targets for 0 po files that are out of date'), re.compile(r'^building \[.*\]: targets for 0 mo files that are out of date'), re.compile('^pickling environment... done'), re.compile('^dumping object inventory... done'), - # We still have "Build finished." - re.compile('^build succeeded.'), + re.compile('^build succeeded.'), # We still have "Build finished." re.compile('^checking consistency... done'), re.compile('^preparing documents... done'), re.compile('^copying extra files... done'),