hexsha
stringlengths
40
40
size
int64
7
1.04M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
247
max_stars_repo_name
stringlengths
4
125
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
247
max_issues_repo_name
stringlengths
4
125
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
247
max_forks_repo_name
stringlengths
4
125
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.04M
avg_line_length
float64
1.77
618k
max_line_length
int64
1
1.02M
alphanum_fraction
float64
0
1
original_content
stringlengths
7
1.04M
filtered:remove_function_no_docstring
int64
-102
942k
filtered:remove_class_no_docstring
int64
-354
977k
filtered:remove_delete_markers
int64
0
60.1k
2e7d9fb93923633f4e151a78651eefc2d0d36792
841
py
Python
src/bp/domain.py
jggomez/Python-Reference-Microservice
13723c5f5a205bf1f874c44dddbd4cab64839da7
[ "MIT" ]
14
2020-07-09T22:31:09.000Z
2022-01-21T23:03:29.000Z
src/bp/domain.py
jggomez/Python-Reference-Microservice
13723c5f5a205bf1f874c44dddbd4cab64839da7
[ "MIT" ]
1
2021-02-03T23:51:35.000Z
2021-02-03T23:51:35.000Z
src/bp/domain.py
jggomez/Python-Reference-Microservice
13723c5f5a205bf1f874c44dddbd4cab64839da7
[ "MIT" ]
6
2020-07-10T04:07:11.000Z
2020-10-04T00:04:30.000Z
from dataclasses import dataclass from typing_extensions import Final # Constants ID: Final = "id" NAME: Final = "name" URL_BACKGROUND: Final = "urlbackground" CODE: Final = "code" TYPE: Final = "type" HAS_MEDALS: Final = "hasmedals" LEVEL: Final = "level" NAME_LEVEL: Final = "namelevel" PROGRESSION: Final = "progression" @dataclass(frozen=True)
21.564103
48
0.606421
from dataclasses import dataclass from typing_extensions import Final # Constants ID: Final = "id" NAME: Final = "name" URL_BACKGROUND: Final = "urlbackground" CODE: Final = "code" TYPE: Final = "type" HAS_MEDALS: Final = "hasmedals" LEVEL: Final = "level" NAME_LEVEL: Final = "namelevel" PROGRESSION: Final = "progression" @dataclass(frozen=True) class TypeGame: id: int name: str url_background: str code: str type: str level: str = "" namelevel: str = "" progression: int = 0 def to_json(self): return { ID: self.id, NAME: self.name, URL_BACKGROUND: self.url_background, CODE: self.code, TYPE: self.type, LEVEL: self.level, NAME_LEVEL: self.namelevel, PROGRESSION: self.progression, }
299
168
22
180b8061f6ddde6d89c5f92f515db94b94f06374
23,348
py
Python
tests/integration/test_hooks_github.py
aavcc/taiga-openshift
7c33284573ceed38f755b8159ad83f3f68d2f7cb
[ "MIT" ]
null
null
null
tests/integration/test_hooks_github.py
aavcc/taiga-openshift
7c33284573ceed38f755b8159ad83f3f68d2f7cb
[ "MIT" ]
12
2019-11-25T14:08:32.000Z
2021-06-24T10:35:51.000Z
tests/integration/test_hooks_github.py
threefoldtech/Threefold-Circles
cbc433796b25cf7af9a295af65d665a4a279e2d6
[ "Apache-2.0" ]
1
2018-06-07T10:58:15.000Z
2018-06-07T10:58:15.000Z
# -*- coding: utf-8 -*- # Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net> # Copyright (C) 2014-2017 Anler Hernández <hello@anler.me> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import pytest from unittest import mock from django.core.urlresolvers import reverse from django.core import mail from taiga.base.utils import json from taiga.hooks.github import event_hooks from taiga.hooks.github.api import GitHubViewSet from taiga.hooks.exceptions import ActionSyntaxException from taiga.projects import choices as project_choices from taiga.projects.epics.models import Epic from taiga.projects.issues.models import Issue from taiga.projects.tasks.models import Task from taiga.projects.userstories.models import UserStory from taiga.projects.models import Membership from taiga.projects.history.services import get_history_queryset_by_model_instance, take_snapshot from taiga.projects.notifications.choices import NotifyLevel from taiga.projects.notifications.models import NotifyPolicy from taiga.projects import services from .. import factories as f pytestmark = pytest.mark.django_db
37.658065
147
0.684256
# -*- coding: utf-8 -*- # Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net> # Copyright (C) 2014-2017 Anler Hernández <hello@anler.me> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import pytest from unittest import mock from django.core.urlresolvers import reverse from django.core import mail from taiga.base.utils import json from taiga.hooks.github import event_hooks from taiga.hooks.github.api import GitHubViewSet from taiga.hooks.exceptions import ActionSyntaxException from taiga.projects import choices as project_choices from taiga.projects.epics.models import Epic from taiga.projects.issues.models import Issue from taiga.projects.tasks.models import Task from taiga.projects.userstories.models import UserStory from taiga.projects.models import Membership from taiga.projects.history.services import get_history_queryset_by_model_instance, take_snapshot from taiga.projects.notifications.choices import NotifyLevel from taiga.projects.notifications.models import NotifyPolicy from taiga.projects import services from .. import factories as f pytestmark = pytest.mark.django_db def test_bad_project(client): project = f.ProjectFactory() url = reverse("github-hook-list") url = "%s?project=%s-extra-text-added" % (url, project.id) data = {"test:": "data"} response = client.post(url, json.dumps(data), HTTP_X_HUB_SIGNATURE="sha1=3c8e83fdaa266f81c036ea0b71e98eb5e054581a", content_type="application/json") response_content = response.data assert response.status_code == 400 assert "The project doesn't exist" in response_content["_error_message"] def test_bad_signature(client): project = f.ProjectFactory() url = reverse("github-hook-list") url = "%s?project=%s" % (url, project.id) data = {} response = client.post(url, json.dumps(data), HTTP_X_HUB_SIGNATURE="sha1=badbadbad", content_type="application/json") response_content = response.data assert response.status_code == 400 assert "Bad signature" in response_content["_error_message"] def test_ok_signature(client): project = f.ProjectFactory() f.ProjectModulesConfigFactory(project=project, config={ "github": { "secret": "tpnIwJDz4e" } }) url = reverse("github-hook-list") url = "%s?project=%s" % (url, project.id) data = {"test:": "data"} response = client.post(url, json.dumps(data), HTTP_X_HUB_SIGNATURE="sha1=3c8e83fdaa266f81c036ea0b71e98eb5e054581a", content_type="application/json") assert response.status_code == 204 def test_blocked_project(client): project = f.ProjectFactory(blocked_code=project_choices.BLOCKED_BY_STAFF) f.ProjectModulesConfigFactory(project=project, config={ "github": { "secret": "tpnIwJDz4e" } }) url = reverse("github-hook-list") url = "%s?project=%s" % (url, project.id) data = {"test:": "data"} response = client.post(url, json.dumps(data), HTTP_X_HUB_SIGNATURE="sha1=3c8e83fdaa266f81c036ea0b71e98eb5e054581a", content_type="application/json") assert response.status_code == 451 def test_push_event_detected(client): project = f.ProjectFactory() url = reverse("github-hook-list") url = "%s?project=%s" % (url, project.id) data = {"commits": [ {"message": "test message"}, ]} GitHubViewSet._validate_signature = mock.Mock(return_value=True) with mock.patch.object(event_hooks.PushEventHook, "process_event") as process_event_mock: response = client.post(url, json.dumps(data), HTTP_X_GITHUB_EVENT="push", content_type="application/json") assert process_event_mock.call_count == 1 assert response.status_code == 204 def test_push_event_epic_processing(client): creation_status = f.EpicStatusFactory() role = f.RoleFactory(project=creation_status.project, permissions=["view_epics"]) f.MembershipFactory(project=creation_status.project, role=role, user=creation_status.project.owner) new_status = f.EpicStatusFactory(project=creation_status.project) epic = f.EpicFactory.create(status=creation_status, project=creation_status.project, owner=creation_status.project.owner) payload = {"commits": [ {"message": """test message test TG-%s #%s ok bye! """ % (epic.ref, new_status.slug)}, ]} mail.outbox = [] ev_hook = event_hooks.PushEventHook(epic.project, payload) ev_hook.process_event() epic = Epic.objects.get(id=epic.id) assert epic.status.id == new_status.id assert len(mail.outbox) == 1 def test_push_event_issue_processing(client): creation_status = f.IssueStatusFactory() role = f.RoleFactory(project=creation_status.project, permissions=["view_issues"]) f.MembershipFactory(project=creation_status.project, role=role, user=creation_status.project.owner) new_status = f.IssueStatusFactory(project=creation_status.project) issue = f.IssueFactory.create(status=creation_status, project=creation_status.project, owner=creation_status.project.owner) payload = {"commits": [ {"message": """test message test TG-%s #%s ok bye! """ % (issue.ref, new_status.slug)}, ]} mail.outbox = [] ev_hook = event_hooks.PushEventHook(issue.project, payload) ev_hook.process_event() issue = Issue.objects.get(id=issue.id) assert issue.status.id == new_status.id assert len(mail.outbox) == 1 def test_push_event_task_processing(client): creation_status = f.TaskStatusFactory() role = f.RoleFactory(project=creation_status.project, permissions=["view_tasks"]) f.MembershipFactory(project=creation_status.project, role=role, user=creation_status.project.owner) new_status = f.TaskStatusFactory(project=creation_status.project) task = f.TaskFactory.create(status=creation_status, project=creation_status.project, owner=creation_status.project.owner) payload = {"commits": [ {"message": """test message test TG-%s #%s ok bye! """ % (task.ref, new_status.slug)}, ]} mail.outbox = [] ev_hook = event_hooks.PushEventHook(task.project, payload) ev_hook.process_event() task = Task.objects.get(id=task.id) assert task.status.id == new_status.id assert len(mail.outbox) == 1 def test_push_event_user_story_processing(client): creation_status = f.UserStoryStatusFactory() role = f.RoleFactory(project=creation_status.project, permissions=["view_us"]) f.MembershipFactory(project=creation_status.project, role=role, user=creation_status.project.owner) new_status = f.UserStoryStatusFactory(project=creation_status.project) user_story = f.UserStoryFactory.create(status=creation_status, project=creation_status.project, owner=creation_status.project.owner) payload = {"commits": [ {"message": """test message test TG-%s #%s ok bye! """ % (user_story.ref, new_status.slug)}, ]} mail.outbox = [] ev_hook = event_hooks.PushEventHook(user_story.project, payload) ev_hook.process_event() user_story = UserStory.objects.get(id=user_story.id) assert user_story.status.id == new_status.id assert len(mail.outbox) == 1 def test_push_event_issue_mention(client): creation_status = f.IssueStatusFactory() role = f.RoleFactory(project=creation_status.project, permissions=["view_issues"]) f.MembershipFactory(project=creation_status.project, role=role, user=creation_status.project.owner) issue = f.IssueFactory.create(status=creation_status, project=creation_status.project, owner=creation_status.project.owner) take_snapshot(issue, user=creation_status.project.owner) payload = {"commits": [ {"message": """test message test TG-%s ok bye! """ % (issue.ref)}, ]} mail.outbox = [] ev_hook = event_hooks.PushEventHook(issue.project, payload) ev_hook.process_event() issue_history = get_history_queryset_by_model_instance(issue) assert issue_history.count() == 1 assert issue_history[0].comment.startswith("This issue has been mentioned by") assert len(mail.outbox) == 1 def test_push_event_task_mention(client): creation_status = f.TaskStatusFactory() role = f.RoleFactory(project=creation_status.project, permissions=["view_tasks"]) f.MembershipFactory(project=creation_status.project, role=role, user=creation_status.project.owner) task = f.TaskFactory.create(status=creation_status, project=creation_status.project, owner=creation_status.project.owner) take_snapshot(task, user=creation_status.project.owner) payload = {"commits": [ {"message": """test message test TG-%s ok bye! """ % (task.ref)}, ]} mail.outbox = [] ev_hook = event_hooks.PushEventHook(task.project, payload) ev_hook.process_event() task_history = get_history_queryset_by_model_instance(task) assert task_history.count() == 1 assert task_history[0].comment.startswith("This task has been mentioned by") assert len(mail.outbox) == 1 def test_push_event_user_story_mention(client): creation_status = f.UserStoryStatusFactory() role = f.RoleFactory(project=creation_status.project, permissions=["view_us"]) f.MembershipFactory(project=creation_status.project, role=role, user=creation_status.project.owner) user_story = f.UserStoryFactory.create(status=creation_status, project=creation_status.project, owner=creation_status.project.owner) take_snapshot(user_story, user=creation_status.project.owner) payload = {"commits": [ {"message": """test message test TG-%s ok bye! """ % (user_story.ref)}, ]} mail.outbox = [] ev_hook = event_hooks.PushEventHook(user_story.project, payload) ev_hook.process_event() us_history = get_history_queryset_by_model_instance(user_story) assert us_history.count() == 1 assert us_history[0].comment.startswith("This user story has been mentioned by") assert len(mail.outbox) == 1 def test_push_event_multiple_actions(client): creation_status = f.IssueStatusFactory() role = f.RoleFactory(project=creation_status.project, permissions=["view_issues"]) f.MembershipFactory(project=creation_status.project, role=role, user=creation_status.project.owner) new_status = f.IssueStatusFactory(project=creation_status.project) issue1 = f.IssueFactory.create(status=creation_status, project=creation_status.project, owner=creation_status.project.owner) issue2 = f.IssueFactory.create(status=creation_status, project=creation_status.project, owner=creation_status.project.owner) payload = {"commits": [ {"message": """test message test TG-%s #%s ok test TG-%s #%s ok bye! """ % (issue1.ref, new_status.slug, issue2.ref, new_status.slug)}, ]} mail.outbox = [] ev_hook1 = event_hooks.PushEventHook(issue1.project, payload) ev_hook1.process_event() issue1 = Issue.objects.get(id=issue1.id) issue2 = Issue.objects.get(id=issue2.id) assert issue1.status.id == new_status.id assert issue2.status.id == new_status.id assert len(mail.outbox) == 2 def test_push_event_processing_case_insensitive(client): creation_status = f.TaskStatusFactory() role = f.RoleFactory(project=creation_status.project, permissions=["view_tasks"]) f.MembershipFactory(project=creation_status.project, role=role, user=creation_status.project.owner) new_status = f.TaskStatusFactory(project=creation_status.project) task = f.TaskFactory.create(status=creation_status, project=creation_status.project, owner=creation_status.project.owner) payload = {"commits": [ {"message": """test message test tg-%s #%s ok bye! """ % (task.ref, new_status.slug.upper())}, ]} mail.outbox = [] ev_hook = event_hooks.PushEventHook(task.project, payload) ev_hook.process_event() task = Task.objects.get(id=task.id) assert task.status.id == new_status.id assert len(mail.outbox) == 1 def test_push_event_task_bad_processing_non_existing_ref(client): issue_status = f.IssueStatusFactory() payload = {"commits": [ {"message": """test message test TG-6666666 #%s ok bye! """ % (issue_status.slug)}, ]} mail.outbox = [] ev_hook = event_hooks.PushEventHook(issue_status.project, payload) with pytest.raises(ActionSyntaxException) as excinfo: ev_hook.process_event() assert str(excinfo.value) == "The referenced element doesn't exist" assert len(mail.outbox) == 0 def test_push_event_us_bad_processing_non_existing_status(client): user_story = f.UserStoryFactory.create() payload = {"commits": [ {"message": """test message test TG-%s #non-existing-slug ok bye! """ % (user_story.ref)}, ]} mail.outbox = [] ev_hook = event_hooks.PushEventHook(user_story.project, payload) with pytest.raises(ActionSyntaxException) as excinfo: ev_hook.process_event() assert str(excinfo.value) == "The status doesn't exist" assert len(mail.outbox) == 0 def test_push_event_bad_processing_non_existing_status(client): issue = f.IssueFactory.create() payload = {"commits": [ {"message": """test message test TG-%s #non-existing-slug ok bye! """ % (issue.ref)}, ]} mail.outbox = [] ev_hook = event_hooks.PushEventHook(issue.project, payload) with pytest.raises(ActionSyntaxException) as excinfo: ev_hook.process_event() assert str(excinfo.value) == "The status doesn't exist" assert len(mail.outbox) == 0 def test_issues_event_opened_issue(client): issue = f.IssueFactory.create() issue.project.default_issue_status = issue.status issue.project.default_issue_type = issue.type issue.project.default_severity = issue.severity issue.project.default_priority = issue.priority issue.project.save() Membership.objects.create(user=issue.owner, project=issue.project, role=f.RoleFactory.create(project=issue.project), is_admin=True) notify_policy = NotifyPolicy.objects.get(user=issue.owner, project=issue.project) notify_policy.notify_level = NotifyLevel.all notify_policy.save() payload = { "action": "opened", "issue": { "title": "test-title", "body": "test-body", "html_url": "http://github.com/test/project/issues/11", }, "assignee": {}, "label": {}, "repository": { "html_url": "test", }, } mail.outbox = [] ev_hook = event_hooks.IssuesEventHook(issue.project, payload) ev_hook.process_event() assert Issue.objects.count() == 2 assert len(mail.outbox) == 1 def test_issues_event_other_than_opened_issue(client): issue = f.IssueFactory.create() issue.project.default_issue_status = issue.status issue.project.default_issue_type = issue.type issue.project.default_severity = issue.severity issue.project.default_priority = issue.priority issue.project.save() payload = { "action": "closed", "issue": { "title": "test-title", "body": "test-body", "html_url": "http://github.com/test/project/issues/11", }, "assignee": {}, "label": {}, } mail.outbox = [] ev_hook = event_hooks.IssuesEventHook(issue.project, payload) ev_hook.process_event() assert Issue.objects.count() == 1 assert len(mail.outbox) == 0 def test_issues_event_bad_issue(client): issue = f.IssueFactory.create() issue.project.default_issue_status = issue.status issue.project.default_issue_type = issue.type issue.project.default_severity = issue.severity issue.project.default_priority = issue.priority issue.project.save() payload = { "action": "opened", "issue": {}, "assignee": {}, "label": {}, } mail.outbox = [] ev_hook = event_hooks.IssuesEventHook(issue.project, payload) with pytest.raises(ActionSyntaxException) as excinfo: ev_hook.process_event() assert str(excinfo.value) == "Invalid issue information" assert Issue.objects.count() == 1 assert len(mail.outbox) == 0 def test_issue_comment_event_on_existing_issue_task_and_us(client): project = f.ProjectFactory() role = f.RoleFactory(project=project, permissions=["view_tasks", "view_issues", "view_us"]) f.MembershipFactory(project=project, role=role, user=project.owner) user = f.UserFactory() issue = f.IssueFactory.create(external_reference=["github", "http://github.com/test/project/issues/11"], owner=project.owner, project=project) take_snapshot(issue, user=user) task = f.TaskFactory.create(external_reference=["github", "http://github.com/test/project/issues/11"], owner=project.owner, project=project) take_snapshot(task, user=user) us = f.UserStoryFactory.create(external_reference=["github", "http://github.com/test/project/issues/11"], owner=project.owner, project=project) take_snapshot(us, user=user) payload = { "action": "created", "issue": { "html_url": "http://github.com/test/project/issues/11", }, "comment": { "body": "Test body", }, "repository": { "html_url": "test", }, } mail.outbox = [] assert get_history_queryset_by_model_instance(issue).count() == 0 assert get_history_queryset_by_model_instance(task).count() == 0 assert get_history_queryset_by_model_instance(us).count() == 0 ev_hook = event_hooks.IssueCommentEventHook(issue.project, payload) ev_hook.process_event() issue_history = get_history_queryset_by_model_instance(issue) assert issue_history.count() == 1 assert "Test body" in issue_history[0].comment task_history = get_history_queryset_by_model_instance(task) assert task_history.count() == 1 assert "Test body" in issue_history[0].comment us_history = get_history_queryset_by_model_instance(us) assert us_history.count() == 1 assert "Test body" in issue_history[0].comment assert len(mail.outbox) == 3 def test_issue_comment_event_on_not_existing_issue_task_and_us(client): issue = f.IssueFactory.create(external_reference=["github", "10"]) take_snapshot(issue, user=issue.owner) task = f.TaskFactory.create(project=issue.project, external_reference=["github", "10"]) take_snapshot(task, user=task.owner) us = f.UserStoryFactory.create(project=issue.project, external_reference=["github", "10"]) take_snapshot(us, user=us.owner) payload = { "action": "created", "issue": { "html_url": "http://github.com/test/project/issues/11", }, "comment": { "body": "Test body", }, "repository": { "html_url": "test", }, } mail.outbox = [] assert get_history_queryset_by_model_instance(issue).count() == 0 assert get_history_queryset_by_model_instance(task).count() == 0 assert get_history_queryset_by_model_instance(us).count() == 0 ev_hook = event_hooks.IssueCommentEventHook(issue.project, payload) ev_hook.process_event() assert get_history_queryset_by_model_instance(issue).count() == 0 assert get_history_queryset_by_model_instance(task).count() == 0 assert get_history_queryset_by_model_instance(us).count() == 0 assert len(mail.outbox) == 0 def test_issues_event_bad_comment(client): issue = f.IssueFactory.create(external_reference=["github", "10"]) take_snapshot(issue, user=issue.owner) payload = { "action": "created", "issue": {}, "comment": {}, "repository": { "html_url": "test", }, } ev_hook = event_hooks.IssueCommentEventHook(issue.project, payload) mail.outbox = [] with pytest.raises(ActionSyntaxException) as excinfo: ev_hook.process_event() assert str(excinfo.value) == "Invalid issue comment information" assert Issue.objects.count() == 1 assert len(mail.outbox) == 0 def test_api_get_project_modules(client): project = f.create_project() f.MembershipFactory(project=project, user=project.owner, is_admin=True) url = reverse("projects-modules", args=(project.id,)) client.login(project.owner) response = client.get(url) assert response.status_code == 200 content = response.data assert "github" in content assert content["github"]["secret"] != "" assert content["github"]["webhooks_url"] != "" def test_api_patch_project_modules(client): project = f.create_project() f.MembershipFactory(project=project, user=project.owner, is_admin=True) url = reverse("projects-modules", args=(project.id,)) client.login(project.owner) data = { "github": { "secret": "test_secret", "url": "test_url", } } response = client.patch(url, json.dumps(data), content_type="application/json") assert response.status_code == 204 config = services.get_modules_config(project).config assert "github" in config assert config["github"]["secret"] == "test_secret" assert config["github"]["webhooks_url"] != "test_url" def test_replace_github_references(): ev_hook = event_hooks.BaseGitHubEventHook assert ev_hook.replace_github_references(None, "project-url", "#2") == "[GitHub#2](project-url/issues/2)" assert ev_hook.replace_github_references(None, "project-url", "#2 ") == "[GitHub#2](project-url/issues/2) " assert ev_hook.replace_github_references(None, "project-url", " #2 ") == " [GitHub#2](project-url/issues/2) " assert ev_hook.replace_github_references(None, "project-url", " #2") == " [GitHub#2](project-url/issues/2)" assert ev_hook.replace_github_references(None, "project-url", "#test") == "#test" assert ev_hook.replace_github_references(None, "project-url", None) == ""
20,817
0
598
eb161353e603201191dc9cea20c9382bbb35662d
4,600
py
Python
mrcnn/prediction_detection.py
Stephen-HWJ/Mask_RCNN
4994683c5d694221b00a6b8470e78555c31bfc87
[ "MIT" ]
null
null
null
mrcnn/prediction_detection.py
Stephen-HWJ/Mask_RCNN
4994683c5d694221b00a6b8470e78555c31bfc87
[ "MIT" ]
null
null
null
mrcnn/prediction_detection.py
Stephen-HWJ/Mask_RCNN
4994683c5d694221b00a6b8470e78555c31bfc87
[ "MIT" ]
null
null
null
import os import sys import random import math import re import time import numpy as np import tensorflow as tf import matplotlib import matplotlib.pyplot as plt import matplotlib.patches as patches import shutil import glob import os.path as osp # Root directory of the project ROOT_DIR = os.path.abspath("../../") # Import Mask RCNN sys.path.append(ROOT_DIR) # To find local version of the library from mrcnn import utils from mrcnn import visualize_edited as visualize from mrcnn.visualize_edited import display_images import mrcnn.model as modellib from mrcnn.model import log import skimage.draw import cv2 # %matplotlib inline # Directory to save logs and trained model MODEL_DIR = os.path.join(ROOT_DIR, "logs") # Local path to trained weights file COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5") # Download COCO trained weights from Releases if needed if not os.path.exists(COCO_MODEL_PATH): utils.download_trained_weights(COCO_MODEL_PATH) # Path to Shapes trained weights SHAPES_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_shapes.h5") from mrcnn.config import Config class ObjectDetectionConfig(Config): """Configuration for training on the buildings and ground detection. Derives from the base Config class and overrides some values. """ # Give the configuration a recognizable name NAME = "objectDetection" # We use a GPU with 12GB memory, which can fit two images. # Adjust down if you use a smaller GPU. IMAGES_PER_GPU = 2 # Number of classes (including background) NUM_CLASSES = 1 + 5 # Background + building-ground classes # Number of training steps per epoch STEPS_PER_EPOCH = 500 # Skip detections with < 90% confidence DETECTION_MIN_CONFIDENCE = 0.9 # my object detection config: config = InferenceConfig() data_DIR_images = "F:\\MaskRCNN\\Mask_RCNN\\myproject\\objectDetection\\finalDatasets\\valing\\images\\" data_DIR_lables = "F:\\MaskRCNN\\Mask_RCNN\\myproject\\objectDetection\\finalDatasets\\valing\\labels\\" data_DIR_thermals = "F:\\MaskRCNN\\Mask_RCNN\\myproject\\objectDetection\\finalDatasets\\valing\\thermals\\" data_DIR_predicts = "F:\\MaskRCNN\\Mask_RCNN\\myproject\\objectDetection\\finalDatasets\\valing\\predicts\\" # Override the training configurations with a few # changes for inferencing. config = InferenceConfig() DEVICE = "/cpu:0" # /cpu:0 or /gpu:0 # Inspect the model in training or inference modes # values: 'inference' or 'training' # TODO: code for 'training' test mode not ready yet TEST_MODE = "inference" class_names = ['background','building_roof', 'ground_cars', 'building_facade', 'ground_cars', 'building_roof'] # Create model in inference mode with tf.device(DEVICE): model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config) weights_path = model.find_last() # Load weights print("Loading weights ", weights_path) model.load_weights(weights_path, by_name=True) names = [x for x in os.listdir(data_DIR_images) if ".jpg" in x] #new for name in names: name = name.split(".")[0] image = skimage.io.imread(data_DIR_images + name+".jpg") thermal = skimage.io.imread(data_DIR_thermals + name+".jpg") image = np.concatenate((image, thermal), axis=2) gt_image = cv2.imread(data_DIR_lables+name+".png") # Run object detection results = model.detect([image], verbose=1) # Display results r = results[0] pred_image = visualize.return_save(image, r['rois'], r['masks'], r['class_ids'], class_names, r['scores'], title="Predictions") gt_image = cv2.cvtColor(gt_image, cv2.COLOR_BGR2RGB) pred_image = pred_image[:, :, ::-1] # pred_image = np.array(pred_image,dtype=np.uint8) # pred_image = cv2.cvtColor(pred_image, cv2.COLOR_BGR2RGB) plt.imshow(pred_image) plt.show() plt.imshow(image) plt.show() plt.imshow(gt_image) plt.show() print(gt_image[900,400]) print(pred_image[1000,400]) # cv2.imwrite(data_DIR_predicts+name+".png", pred_image) skimage.io.imsave(data_DIR_predicts+name+".png", pred_image)
31.081081
132
0.707391
import os import sys import random import math import re import time import numpy as np import tensorflow as tf import matplotlib import matplotlib.pyplot as plt import matplotlib.patches as patches import shutil import glob import os.path as osp # Root directory of the project ROOT_DIR = os.path.abspath("../../") # Import Mask RCNN sys.path.append(ROOT_DIR) # To find local version of the library from mrcnn import utils from mrcnn import visualize_edited as visualize from mrcnn.visualize_edited import display_images import mrcnn.model as modellib from mrcnn.model import log import skimage.draw import cv2 # %matplotlib inline # Directory to save logs and trained model MODEL_DIR = os.path.join(ROOT_DIR, "logs") # Local path to trained weights file COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5") # Download COCO trained weights from Releases if needed if not os.path.exists(COCO_MODEL_PATH): utils.download_trained_weights(COCO_MODEL_PATH) # Path to Shapes trained weights SHAPES_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_shapes.h5") from mrcnn.config import Config class ObjectDetectionConfig(Config): """Configuration for training on the buildings and ground detection. Derives from the base Config class and overrides some values. """ # Give the configuration a recognizable name NAME = "objectDetection" # We use a GPU with 12GB memory, which can fit two images. # Adjust down if you use a smaller GPU. IMAGES_PER_GPU = 2 # Number of classes (including background) NUM_CLASSES = 1 + 5 # Background + building-ground classes # Number of training steps per epoch STEPS_PER_EPOCH = 500 # Skip detections with < 90% confidence DETECTION_MIN_CONFIDENCE = 0.9 class InferenceConfig(ObjectDetectionConfig): # Set batch size to 1 since we'll be running inference on # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU GPU_COUNT = 1 IMAGES_PER_GPU = 1 # my object detection config: config = InferenceConfig() data_DIR_images = "F:\\MaskRCNN\\Mask_RCNN\\myproject\\objectDetection\\finalDatasets\\valing\\images\\" data_DIR_lables = "F:\\MaskRCNN\\Mask_RCNN\\myproject\\objectDetection\\finalDatasets\\valing\\labels\\" data_DIR_thermals = "F:\\MaskRCNN\\Mask_RCNN\\myproject\\objectDetection\\finalDatasets\\valing\\thermals\\" data_DIR_predicts = "F:\\MaskRCNN\\Mask_RCNN\\myproject\\objectDetection\\finalDatasets\\valing\\predicts\\" # Override the training configurations with a few # changes for inferencing. class InferenceConfig(config.__class__): # Run detection on one image at a time GPU_COUNT = 1 IMAGES_PER_GPU = 1 config = InferenceConfig() DEVICE = "/cpu:0" # /cpu:0 or /gpu:0 # Inspect the model in training or inference modes # values: 'inference' or 'training' # TODO: code for 'training' test mode not ready yet TEST_MODE = "inference" class_names = ['background','building_roof', 'ground_cars', 'building_facade', 'ground_cars', 'building_roof'] # Create model in inference mode with tf.device(DEVICE): model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config) weights_path = model.find_last() # Load weights print("Loading weights ", weights_path) model.load_weights(weights_path, by_name=True) names = [x for x in os.listdir(data_DIR_images) if ".jpg" in x] #new for name in names: name = name.split(".")[0] image = skimage.io.imread(data_DIR_images + name+".jpg") thermal = skimage.io.imread(data_DIR_thermals + name+".jpg") image = np.concatenate((image, thermal), axis=2) gt_image = cv2.imread(data_DIR_lables+name+".png") # Run object detection results = model.detect([image], verbose=1) # Display results r = results[0] pred_image = visualize.return_save(image, r['rois'], r['masks'], r['class_ids'], class_names, r['scores'], title="Predictions") gt_image = cv2.cvtColor(gt_image, cv2.COLOR_BGR2RGB) pred_image = pred_image[:, :, ::-1] # pred_image = np.array(pred_image,dtype=np.uint8) # pred_image = cv2.cvtColor(pred_image, cv2.COLOR_BGR2RGB) plt.imshow(pred_image) plt.show() plt.imshow(image) plt.show() plt.imshow(gt_image) plt.show() print(gt_image[900,400]) print(pred_image[1000,400]) # cv2.imwrite(data_DIR_predicts+name+".png", pred_image) skimage.io.imsave(data_DIR_predicts+name+".png", pred_image)
0
304
48
b3002caf6fad62fa4323c65c68724aa877cc6ad3
2,953
py
Python
kyu_6/count_letters_in_string/test_count_letters_in_string.py
pedrocodacyorg2/codewars
ba3ea81125b6082d867f0ae34c6c9be15e153966
[ "Unlicense" ]
1
2022-02-12T05:56:04.000Z
2022-02-12T05:56:04.000Z
kyu_6/count_letters_in_string/test_count_letters_in_string.py
pedrocodacyorg2/codewars
ba3ea81125b6082d867f0ae34c6c9be15e153966
[ "Unlicense" ]
182
2020-04-30T00:51:36.000Z
2021-09-07T04:15:05.000Z
kyu_6/count_letters_in_string/test_count_letters_in_string.py
pedrocodacyorg2/codewars
ba3ea81125b6082d867f0ae34c6c9be15e153966
[ "Unlicense" ]
4
2020-04-29T22:04:20.000Z
2021-07-13T20:04:14.000Z
# Created by Egor Kostan. # GitHub: https://github.com/ikostan # LinkedIn: https://www.linkedin.com/in/egor-kostan/ # FUNDAMENTALS STRINGS HASHES DATA STRUCTURES import unittest import allure from utils.log_func import print_log from kyu_6.count_letters_in_string.count_letters_in_string import letter_count @allure.epic('6 kyu') @allure.parent_suite('Novice') @allure.suite("Data Structures") @allure.sub_suite("Unit Tests") @allure.feature("String") @allure.story('Count letters in string') @allure.tag('FUNDAMENTALS', 'STRINGS', 'HASHES', 'DATA STRUCTURES') @allure.link(url='', name='Source/Kata') class CountLettersInStringTestCase(unittest.TestCase): """ Testing 'letter_count' function """ def test_count_letters_in_string(self): """ Testing 'letter_count' function :return: """ allure.dynamic.title("Testing 'letter_count' function") allure.dynamic.severity(allure.severity_level.NORMAL) allure.dynamic.description_html('<h3>Codewars badge:</h3>' '<img src="https://www.codewars.com/users/myFirstCode' '/badges/large">' '<h3>Test Description:</h3>' "<p></p>") with allure.step("Enter test string and verify the output"): string = "codewars" expected = {"a": 1, "c": 1, "d": 1, "e": 1, "o": 1, "r": 1, "s": 1, "w": 1} print_log(string=string, expected=expected) self.assertEqual(expected, letter_count(string)) with allure.step("Enter test string and verify the output"): string = "activity" expected = {"a": 1, "c": 1, "i": 2, "t": 2, "v": 1, "y": 1} print_log(string=string, expected=expected) self.assertEqual(expected, letter_count(string)) with allure.step("Enter test string and verify the output"): string = "arithmetics" expected = {"a": 1, "c": 1, "e": 1, "h": 1, "i": 2, "m": 1, "r": 1, "s": 1, "t": 2} print_log(string=string, expected=expected) self.assertEqual(expected, letter_count(string)) with allure.step("Enter test string and verify the output"): string = "traveller" expected = {"a": 1, "e": 2, "l": 2, "r": 2, "t": 1, "v": 1} print_log(string=string, expected=expected) self.assertEqual(expected, letter_count(string)) with allure.step("Enter test string and verify the output"): string = "daydreamer" expected = {"a": 2, "d": 2, "e": 2, "m": 1, "r": 2, "y": 1} print_log(string=string, expected=expected) self.assertEqual(expected, letter_count(string))
34.741176
94
0.552997
# Created by Egor Kostan. # GitHub: https://github.com/ikostan # LinkedIn: https://www.linkedin.com/in/egor-kostan/ # FUNDAMENTALS STRINGS HASHES DATA STRUCTURES import unittest import allure from utils.log_func import print_log from kyu_6.count_letters_in_string.count_letters_in_string import letter_count @allure.epic('6 kyu') @allure.parent_suite('Novice') @allure.suite("Data Structures") @allure.sub_suite("Unit Tests") @allure.feature("String") @allure.story('Count letters in string') @allure.tag('FUNDAMENTALS', 'STRINGS', 'HASHES', 'DATA STRUCTURES') @allure.link(url='', name='Source/Kata') class CountLettersInStringTestCase(unittest.TestCase): """ Testing 'letter_count' function """ def test_count_letters_in_string(self): """ Testing 'letter_count' function :return: """ allure.dynamic.title("Testing 'letter_count' function") allure.dynamic.severity(allure.severity_level.NORMAL) allure.dynamic.description_html('<h3>Codewars badge:</h3>' '<img src="https://www.codewars.com/users/myFirstCode' '/badges/large">' '<h3>Test Description:</h3>' "<p></p>") with allure.step("Enter test string and verify the output"): string = "codewars" expected = {"a": 1, "c": 1, "d": 1, "e": 1, "o": 1, "r": 1, "s": 1, "w": 1} print_log(string=string, expected=expected) self.assertEqual(expected, letter_count(string)) with allure.step("Enter test string and verify the output"): string = "activity" expected = {"a": 1, "c": 1, "i": 2, "t": 2, "v": 1, "y": 1} print_log(string=string, expected=expected) self.assertEqual(expected, letter_count(string)) with allure.step("Enter test string and verify the output"): string = "arithmetics" expected = {"a": 1, "c": 1, "e": 1, "h": 1, "i": 2, "m": 1, "r": 1, "s": 1, "t": 2} print_log(string=string, expected=expected) self.assertEqual(expected, letter_count(string)) with allure.step("Enter test string and verify the output"): string = "traveller" expected = {"a": 1, "e": 2, "l": 2, "r": 2, "t": 1, "v": 1} print_log(string=string, expected=expected) self.assertEqual(expected, letter_count(string)) with allure.step("Enter test string and verify the output"): string = "daydreamer" expected = {"a": 2, "d": 2, "e": 2, "m": 1, "r": 2, "y": 1} print_log(string=string, expected=expected) self.assertEqual(expected, letter_count(string))
0
0
0
4f16a3131b11e34227efd2b6d285bf5071c9a537
2,895
py
Python
torch/nested/_nestedtensor.py
jiyuanzFB/pytorch
d047e475f830631d8fcc877ea17eac8fb34748d7
[ "Intel" ]
1
2022-03-08T14:43:39.000Z
2022-03-08T14:43:39.000Z
torch/nested/_nestedtensor.py
jiyuanzFB/pytorch
d047e475f830631d8fcc877ea17eac8fb34748d7
[ "Intel" ]
null
null
null
torch/nested/_nestedtensor.py
jiyuanzFB/pytorch
d047e475f830631d8fcc877ea17eac8fb34748d7
[ "Intel" ]
null
null
null
import torch from functools import wraps @wraps(torch._nested_tensor) # TODO: This entire class is not really necessary now that NestedTensor lives # in tree; before it lived out of tree and there was no way to conveniently # override the string printing behavior. Now that we are in tree, we can # directly override _tensor_str to capture this behavior, and the wrapper subclass # is not necessary. See also https://github.com/pytorch/pytorch/issues/73506
27.056075
82
0.543351
import torch from functools import wraps @wraps(torch._nested_tensor) def nested_tensor(*args, **kwargs): return NestedTensor(torch._nested_tensor(*args, **kwargs)) # TODO: This entire class is not really necessary now that NestedTensor lives # in tree; before it lived out of tree and there was no way to conveniently # override the string printing behavior. Now that we are in tree, we can # directly override _tensor_str to capture this behavior, and the wrapper subclass # is not necessary. See also https://github.com/pytorch/pytorch/issues/73506 class NestedTensor: # data is a torch.Tensor backed by a NestedTensorImpl def __init__(self, impl): self._impl = impl @property def dtype(self): """ The data type of ```self``` NestedTensor. """ return self._impl.dtype @property def layout(self): """ The layout of ```self``` NestedTensor. """ return self._impl.layout @property def device(self): """ The device of ```self``` NestedTensor. """ return self._impl.device @property def requires_grad(self): """ Is ```True``` if gradients need to be computed for this Tensor. """ return self._impl.requires_grad def stride(self): """ NestedTensor currently does not have a stride. This will throw. """ return self._impl.stride() def size(self): """ NestedTensor currently does not have a size. This will throw. """ return self._impl.size() def dim(self): """ The dimension of ```self``` NestedTensor. """ return self._impl.dim() def numel(self): """ The number of elements of ```self``` NestedTensor. """ return self._impl.numel() def is_contiguous(self): """ Returns true if ```self``` NestedTensor is contiguous. """ return self._impl.is_contiguous() def __str__(self): def _str(x, indent=0, tab=" "): s = indent * tab + "[\n" strs = list(map(str, x.unbind())) strs = list( map( lambda xi: "\n".join( map(lambda xij: (indent + 1) * tab + xij, xi.split("\n")) ), strs, ) ) s += ",\n".join(strs) s += "\n" + indent * tab + "]" return s return "nested_tensor(" + _str(self) + ")" def __repr__(self): return self.__str__() def unbind(self, dim=None): if dim is None: unbound = torch.ops.aten.unbind.int(self._impl, 0) if len(unbound) == 0: return () return unbound return torch.ops.aten.unbind.int(self._impl, dim)
895
1,494
44
9429614cea37db85cc533b5f30311212d8acc0b1
2,918
py
Python
divia_api/stop.py
filau/pda_demo
fa7095bba31b1a74ad05add7c7827df9641f0210
[ "BSD-3-Clause" ]
null
null
null
divia_api/stop.py
filau/pda_demo
fa7095bba31b1a74ad05add7c7827df9641f0210
[ "BSD-3-Clause" ]
null
null
null
divia_api/stop.py
filau/pda_demo
fa7095bba31b1a74ad05add7c7827df9641f0210
[ "BSD-3-Clause" ]
null
null
null
# coding=utf-8 """ stop.py divia_api is a Python library that allows to retrieve the timetable of Divia’s bus and tramways straight from a Python script. Copyright (C) 2021 Firmin Launay 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. """ from browser import ajax from datetime import datetime, timedelta two_minutes = timedelta(minutes=2) one_day = timedelta(days=1)
37.896104
160
0.620288
# coding=utf-8 """ stop.py divia_api is a Python library that allows to retrieve the timetable of Divia’s bus and tramways straight from a Python script. Copyright (C) 2021 Firmin Launay 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. """ from browser import ajax from datetime import datetime, timedelta two_minutes = timedelta(minutes=2) one_day = timedelta(days=1) class Stop: def __init__(self, api_data, line, stop_data): self.api_data = api_data self.line = line self.stop_data = stop_data def totem(self) -> list: """Get the results of TOTEM for the line, the stop and the way you specified.""" self.totem_result = [] try: html_totem = ajax.post("https://www.divia.fr/bus-tram?type=479", headers={ "Content-Type": "application/x-www-form-urlencoded", "X-Requested-With": "XMLHttpRequest" }, data=f"requete=arret_prochainpassage&requete_val%5Bid_ligne%5D={self.line.line_data['id']}&requete_val%5Bid_arret%5D={self.stop_data['code']}", oncomplete=self.totem_after_req, blocking=True ) finally: return self.totem_result def totem_after_req(self, result): try: html_totem = result.text two = False if html_totem.count("<span class=\"uk-badge\">") > 1: two = True now = datetime.now() time_1 = html_totem.split("<span class=\"uk-badge\"> ")[1].split("</span>")[0].split(":") time_1_today = datetime(now.year, now.month, now.day, int(time_1[0]), int(time_1[1]), 0) if (now - two_minutes) > time_1_today: self.totem_result.append(time_1_today + one_day) else: self.totem_result.append(time_1_today) if two: time_2 = html_totem.split("<span class=\"uk-badge\"> ")[2].split("</span>")[0].split(":") time_2_today = datetime(now.year, now.month, now.day, int(time_2[0]), int(time_2[1]), 0) if (now - two_minutes) > time_2_today: self.totem_result.append(time_2_today + one_day) else: self.totem_result.append(time_2_today) except: pass
1,193
760
23
3b9395c7e5a302b543a851cb1d2f5ab62adda620
5,544
py
Python
bitrix24_bridge/amqp/amqp.py
initflow/bitrix24-bridge-oscar
fd50985fa354a92d7163055c9e3adfd5c4f4d7a9
[ "BSD-3-Clause" ]
null
null
null
bitrix24_bridge/amqp/amqp.py
initflow/bitrix24-bridge-oscar
fd50985fa354a92d7163055c9e3adfd5c4f4d7a9
[ "BSD-3-Clause" ]
13
2020-02-12T00:58:41.000Z
2022-03-11T23:53:16.000Z
bitrix24_bridge/amqp/amqp.py
initflow/bitrix24-bridge-oscar
fd50985fa354a92d7163055c9e3adfd5c4f4d7a9
[ "BSD-3-Clause" ]
null
null
null
import functools from abc import ABC, abstractmethod from dataclasses import dataclass, field import pika import ujson from django.conf import settings from typing import Callable, Any, Optional, List """ BB = Bitrix24 Bridge """ def get_var(name) -> Callable[[], Optional[Any]]: """ Safe wraper over settings :param name: :return: Callable[[], Optional[Any]] - get param from settings if it defined, else return None """ return functools.partial(getattr, settings, name, None) @dataclass @dataclass
31.146067
109
0.674784
import functools from abc import ABC, abstractmethod from dataclasses import dataclass, field import pika import ujson from django.conf import settings from typing import Callable, Any, Optional, List """ BB = Bitrix24 Bridge """ def get_var(name) -> Callable[[], Optional[Any]]: """ Safe wraper over settings :param name: :return: Callable[[], Optional[Any]] - get param from settings if it defined, else return None """ return functools.partial(getattr, settings, name, None) class MessageProducer(ABC): @abstractmethod def connect(self): raise NotImplemented @abstractmethod def close(self): raise NotImplemented @abstractmethod def send(self, message): raise NotImplemented def __enter__(self): self.connect() return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() class Meta: abstract = True @dataclass class RabbitMQProducer(MessageProducer): connection_url: Optional[str] = field(default_factory=get_var('BB_RABBITMQ_URL')) host: str = field(default_factory=get_var('BB_RABBITMQ_HOST')) port: int = field(default_factory=get_var('BB_RABBITMQ_PORT')) virtual_host: str = field(default_factory=get_var('BB_RABBITMQ_VIRTUAL_HOST')) user: str = field(default_factory=get_var('BB_RABBITMQ_USER')) password: str = field(default_factory=get_var('BB_RABBITMQ_PASS')) routing_key: str = field(default_factory=get_var('BB_RABBITMQ_ROUTING_KEY')) exchange: str = field(default_factory=get_var('BB_RABBITMQ_EXCHANGE')) exchange_type: str = field(default_factory=get_var('BB_RABBITMQ_EXCHANGE_TYPE')) exchange_durable: str = field(default_factory=get_var('BB_RABBITMQ_EXCHANGE_DURABLE')) connection: Optional[pika.BlockingConnection] = None def connect(self): if self.connection is None or self.connection.is_closed: credentials = pika.PlainCredentials(self.user, self.password) if self.connection_url: conn_params = pika.URLParameters(self.connection_url) else: conn_params = pika.ConnectionParameters(self.host, self.port, self.virtual_host, credentials) self.connection = pika.BlockingConnection(parameters=conn_params) return self.connection def close(self): if self.connection.is_open: self.connection.close() def send(self, message): channel = self.connect().channel() channel.basic_publish( self.exchange, self.routing_key, ujson.dumps(message), pika.BasicProperties( content_type='application/json; charset=utf-8' )) class MessageConsumer(ABC): @abstractmethod def connect(self): raise NotImplemented @abstractmethod def close(self): raise NotImplemented @abstractmethod def receive(self, message): raise NotImplemented def __enter__(self): self.connect() return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() class Meta: abstract = True @dataclass class RabbitMQConsumer(MessageConsumer): connection_url: Optional[str] = field(default_factory=get_var('BB_RABBITMQ_URL')) host: str = field(default_factory=get_var('BB_RABBITMQ_HOST')) port: int = field(default_factory=get_var('BB_RABBITMQ_PORT')) virtual_host: str = field(default_factory=get_var('BB_RABBITMQ_VIRTUAL_HOST')) user: str = field(default_factory=get_var('BB_RABBITMQ_USER')) password: str = field(default_factory=get_var('BB_RABBITMQ_PASS')) queue: str = field(default_factory=get_var('BB_RABBITMQ_MESSAGE_QUEUE')) routing_key: str = field(default_factory=get_var('BB_RABBITMQ_ROUTING_KEY')) exchange: str = field(default_factory=get_var('BB_RABBITMQ_EXCHANGE')) exchange_type: str = field(default_factory=get_var('BB_RABBITMQ_EXCHANGE_TYPE')) exchange_durable: str = field(default_factory=get_var('BB_RABBITMQ_EXCHANGE_DURABLE')) connection: Optional[pika.BlockingConnection] = None buffer: List = field(init=False, repr=False, compare=False, default_factory=list) def connect(self): if self.connection is None or self.connection.is_closed: credentials = pika.PlainCredentials(self.user, self.password) if self.connection_url: conn_params = pika.URLParameters(self.connection_url) else: conn_params = pika.ConnectionParameters( host=self.host, port=self.port, virtual_host=self.virtual_host, credentials=credentials, ) self.connection = pika.BlockingConnection(parameters=conn_params) return self.connection def default_callback(self, channel, method_frame, header_frame, body): try: msg = ujson.loads(body) except Exception: msg = "¯\_(ツ)_/¯" self.buffer.append(msg) def close(self): if self.connection and self.connection.is_open(): self.connection.close() def receive(self, callback=None): if callback is None: callback = self.default_callback connection = self.connect() channel = connection.channel() channel.basic_consume(self.queue, callback) try: channel.start_consuming() except KeyboardInterrupt: channel.stop_consuming()
2,378
2,545
90
d838e226a7de7b9cd782061fb6f64b3134bc06cc
3,053
py
Python
setup.py
jay-johnson/antinex-client
76a3cfbe8a8d174d87aba37de3d8acaf8c4864ba
[ "Apache-2.0" ]
5
2018-03-24T08:12:36.000Z
2019-09-10T14:38:36.000Z
setup.py
jay-johnson/antinex-client
76a3cfbe8a8d174d87aba37de3d8acaf8c4864ba
[ "Apache-2.0" ]
1
2020-06-03T13:40:22.000Z
2020-09-05T12:53:22.000Z
setup.py
jay-johnson/antinex-client
76a3cfbe8a8d174d87aba37de3d8acaf8c4864ba
[ "Apache-2.0" ]
null
null
null
import os import sys import warnings import unittest try: from setuptools import setup except ImportError: from distutils.core import setup from setuptools.command.test import test as TestCommand """ https://packaging.python.org/guides/making-a-pypi-friendly-readme/ check the README.rst works on pypi as the long_description with: twine check dist/* """ long_description = open('README.rst').read() cur_path, cur_script = os.path.split(sys.argv[0]) os.chdir(os.path.abspath(cur_path)) install_requires = [ "colorlog", "coverage", "flake8", "matplotlib", "numpy", "pandas", "pep8", "pipenv", "pycodestyle", "pylint", "recommonmark", "requests", "seaborn", "sphinx", "sphinx-autobuild", "sphinx_rtd_theme", "spylunking", "tox", "tqdm", "unittest2", "mock" ] if sys.version_info < (3, 5): warnings.warn( "Less than Python 3.5 is not supported.", DeprecationWarning) # Do not import antinex_client module here, since deps may not be installed sys.path.insert(0, os.path.join(os.path.dirname(__file__), "antinex_client")) setup( name="antinex-client", cmdclass={"test": PyTest}, version="1.3.6", description=("AntiNex Python client"), long_description_content_type='text/x-rst', long_description=long_description, author="Jay Johnson", author_email="jay.p.h.johnson@gmail.com", url="https://github.com/jay-johnson/antinex-client", packages=[ "antinex_client", "antinex_client.scripts", "antinex_client.log" ], package_data={}, install_requires=install_requires, test_suite="setup.antinex_client_test_suite", tests_require=[ "pytest" ], scripts=[ "./antinex_client/scripts/ai", "./antinex_client/scripts/ai_env_predict.py", "./antinex_client/scripts/ai_get_prepared_dataset.py", "./antinex_client/scripts/ai_get_job.py", "./antinex_client/scripts/ai_get_results.py", "./antinex_client/scripts/ai_prepare_dataset.py", "./antinex_client/scripts/ai_train_dnn.py" ], use_2to3=True, classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development :: Libraries :: Python Modules", ])
26.780702
77
0.651163
import os import sys import warnings import unittest try: from setuptools import setup except ImportError: from distutils.core import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): user_options = [('pytest-args=', 'a', "Arguments to pass to pytest")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = '' def run_tests(self): import shlex # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(shlex.split(self.pytest_args)) sys.exit(errno) """ https://packaging.python.org/guides/making-a-pypi-friendly-readme/ check the README.rst works on pypi as the long_description with: twine check dist/* """ long_description = open('README.rst').read() cur_path, cur_script = os.path.split(sys.argv[0]) os.chdir(os.path.abspath(cur_path)) install_requires = [ "colorlog", "coverage", "flake8", "matplotlib", "numpy", "pandas", "pep8", "pipenv", "pycodestyle", "pylint", "recommonmark", "requests", "seaborn", "sphinx", "sphinx-autobuild", "sphinx_rtd_theme", "spylunking", "tox", "tqdm", "unittest2", "mock" ] if sys.version_info < (3, 5): warnings.warn( "Less than Python 3.5 is not supported.", DeprecationWarning) # Do not import antinex_client module here, since deps may not be installed sys.path.insert(0, os.path.join(os.path.dirname(__file__), "antinex_client")) setup( name="antinex-client", cmdclass={"test": PyTest}, version="1.3.6", description=("AntiNex Python client"), long_description_content_type='text/x-rst', long_description=long_description, author="Jay Johnson", author_email="jay.p.h.johnson@gmail.com", url="https://github.com/jay-johnson/antinex-client", packages=[ "antinex_client", "antinex_client.scripts", "antinex_client.log" ], package_data={}, install_requires=install_requires, test_suite="setup.antinex_client_test_suite", tests_require=[ "pytest" ], scripts=[ "./antinex_client/scripts/ai", "./antinex_client/scripts/ai_env_predict.py", "./antinex_client/scripts/ai_get_prepared_dataset.py", "./antinex_client/scripts/ai_get_job.py", "./antinex_client/scripts/ai_get_results.py", "./antinex_client/scripts/ai_prepare_dataset.py", "./antinex_client/scripts/ai_train_dnn.py" ], use_2to3=True, classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development :: Libraries :: Python Modules", ])
268
133
23
d88c3550018e2ef9933db5e686b6cf597d8637e6
441
py
Python
lambdas/setup_upload_artifacts/genpath.py
aws-samples/aws-bikenow-demo
aec204b446910022985ba5e1731a24ddcfb6fcac
[ "MIT-0" ]
16
2020-03-26T16:05:26.000Z
2021-11-04T20:00:53.000Z
lambdas/setup_upload_artifacts/genpath.py
aws-samples/aws-bikenow-demo
aec204b446910022985ba5e1731a24ddcfb6fcac
[ "MIT-0" ]
1
2022-02-27T10:55:00.000Z
2022-02-27T10:55:00.000Z
lambdas/setup_upload_artifacts/genpath.py
aws-samples/aws-bikenow-demo
aec204b446910022985ba5e1731a24ddcfb6fcac
[ "MIT-0" ]
6
2020-06-08T11:43:40.000Z
2021-01-09T20:31:08.000Z
import json import os from os import listdir from os.path import isfile, join SCRIPT_BUCKET = 'mybucket' SCRIPT_FOLDER = 'artifacts' # Copy Glue script files to S3 bucket script_path = 'artifacts' #my_bucket = s3.Bucket(SCRIPT_BUCKET) for path, subdirs, files in os.walk(script_path): path = path.replace("\\","/") directory_name = path.replace(script_path, "") for file in files: print(SCRIPT_FOLDER + directory_name + '/' + file)
24.5
52
0.734694
import json import os from os import listdir from os.path import isfile, join SCRIPT_BUCKET = 'mybucket' SCRIPT_FOLDER = 'artifacts' # Copy Glue script files to S3 bucket script_path = 'artifacts' #my_bucket = s3.Bucket(SCRIPT_BUCKET) for path, subdirs, files in os.walk(script_path): path = path.replace("\\","/") directory_name = path.replace(script_path, "") for file in files: print(SCRIPT_FOLDER + directory_name + '/' + file)
0
0
0
dd2a6ae145b8d2bc6728daea6b5f1f476832af35
1,313
py
Python
Zadania1/3_zadanie.py
ViktoriaGallikova/basic-python
71152f9a1de0e863428e1dd4f4784c129543d015
[ "MIT" ]
null
null
null
Zadania1/3_zadanie.py
ViktoriaGallikova/basic-python
71152f9a1de0e863428e1dd4f4784c129543d015
[ "MIT" ]
null
null
null
Zadania1/3_zadanie.py
ViktoriaGallikova/basic-python
71152f9a1de0e863428e1dd4f4784c129543d015
[ "MIT" ]
null
null
null
# Sekvencia DNA sa skladá zo štyroch typov nukleových báz (A, C, G, T). Relatívna početnosť bázy vyjadruje, aká časť sekvencie je tvorená daným typom bázy (počet výskytov bázy / dĺžka sekvencie). Súčet relatívnej početnosti je teda vždy rovna 1. # Napíšte definíciu funkcie funkcia3, ktorá zoberie ako parameter sekvenciu DNA a vráti slovník s relatívnou početnosťou nukleových báz. (Poznámka: funkcia pprint v doctestu vypisuje obsah slovníka zoradenu podľa kľúčov, poradie teda nemusíte riešiť. Hodnoty nie je potreba nijak zaokrúhľovať.) from typing import Dict, List, Tuple from pprint import pprint import math def funkcia3(sekvencia: str) -> Dict[str, float]: """Spočítaj relativnu četnosť baz v sekvencii DNA. >>> pprint(funkcia3('ACGTTTTGAG')) {'A': 0.2, 'C': 0.1, 'G': 0.3, 'T': 0.4} >>> pprint(funkcia3('AAA')) {'A': 1.0, 'C': 0.0, 'G': 0.0, 'T': 0.0} """ dlzka = len(sekvencia) relativna_cetnost = {baza: sekvencia.count(baza) / dlzka for baza in 'ATGC'} return relativna_cetnost # # Alternatívne riešenie: # cetnost = {'A': 0, 'C': 0, 'G': 0, 'T': 0} # for baza in sekvencia: # cetnost[baza] += 1 # dlzka = len(sekvencia) # for baza in cetnost: # cetnost[baza] /= dlzka # return cetnost print(funkcia3('ACGTTTTGAG'))
45.275862
294
0.675552
# Sekvencia DNA sa skladá zo štyroch typov nukleových báz (A, C, G, T). Relatívna početnosť bázy vyjadruje, aká časť sekvencie je tvorená daným typom bázy (počet výskytov bázy / dĺžka sekvencie). Súčet relatívnej početnosti je teda vždy rovna 1. # Napíšte definíciu funkcie funkcia3, ktorá zoberie ako parameter sekvenciu DNA a vráti slovník s relatívnou početnosťou nukleových báz. (Poznámka: funkcia pprint v doctestu vypisuje obsah slovníka zoradenu podľa kľúčov, poradie teda nemusíte riešiť. Hodnoty nie je potreba nijak zaokrúhľovať.) from typing import Dict, List, Tuple from pprint import pprint import math def funkcia3(sekvencia: str) -> Dict[str, float]: """Spočítaj relativnu četnosť baz v sekvencii DNA. >>> pprint(funkcia3('ACGTTTTGAG')) {'A': 0.2, 'C': 0.1, 'G': 0.3, 'T': 0.4} >>> pprint(funkcia3('AAA')) {'A': 1.0, 'C': 0.0, 'G': 0.0, 'T': 0.0} """ dlzka = len(sekvencia) relativna_cetnost = {baza: sekvencia.count(baza) / dlzka for baza in 'ATGC'} return relativna_cetnost # # Alternatívne riešenie: # cetnost = {'A': 0, 'C': 0, 'G': 0, 'T': 0} # for baza in sekvencia: # cetnost[baza] += 1 # dlzka = len(sekvencia) # for baza in cetnost: # cetnost[baza] /= dlzka # return cetnost print(funkcia3('ACGTTTTGAG'))
0
0
0
8bcb83df4019ec4e0aba861e8793a5b4505212d3
312
py
Python
MITx6002/Lec7Exc3.py
osamadel/Python
6c7e26a96d4b8f875755de98f16eba89e81d94d2
[ "MIT" ]
null
null
null
MITx6002/Lec7Exc3.py
osamadel/Python
6c7e26a96d4b8f875755de98f16eba89e81d94d2
[ "MIT" ]
null
null
null
MITx6002/Lec7Exc3.py
osamadel/Python
6c7e26a96d4b8f875755de98f16eba89e81d94d2
[ "MIT" ]
null
null
null
L = ['apples', 'oranges', 'kiwis', 'pineapples'] print(stdDevOfLengths(L))
26
56
0.528846
def stdDevOfLengths(L): N = len(L) std = 0 if N == 0: return float('NaN') mean = sum(list(map(lambda x: len(x),L))) / float(N) for item in L: std += (len(item) - mean) ** 2 return (std / N) ** 0.5 L = ['apples', 'oranges', 'kiwis', 'pineapples'] print(stdDevOfLengths(L))
215
0
22
2b2ba3652a6b9cdf4b3663e5f95cf9ff4429b79c
9,352
py
Python
nuqql/conversation/history.py
hwipl/nuqql
410ea5bd42e455d656b1b34612c3b0d5a0b433ef
[ "MIT" ]
3
2019-04-15T18:33:36.000Z
2019-04-21T19:18:10.000Z
nuqql/conversation/history.py
hwipl/nuqql
410ea5bd42e455d656b1b34612c3b0d5a0b433ef
[ "MIT" ]
15
2019-04-15T18:35:56.000Z
2019-09-14T08:24:32.000Z
nuqql/conversation/history.py
hwipl/nuqql
410ea5bd42e455d656b1b34612c3b0d5a0b433ef
[ "MIT" ]
1
2019-06-16T12:00:30.000Z
2019-06-16T12:00:30.000Z
""" History: (file) logging for nuqql conversations """ import datetime import logging import pathlib import os from typing import List, Optional, TYPE_CHECKING import nuqql.config from .logmessage import LogMessage if TYPE_CHECKING: # imports for typing # pylint: disable=cyclic-import from .conversation import Conversation # noqa logger = logging.getLogger(__name__) HISTORY_FILE = "/history" LASTREAD_FILE = "/lastread" class History: """ Message history """ def _get_conv_path(self) -> str: """ Get path for conversation history as a string and make sure it exists """ # construct directory path assert self.conv.backend and self.conv.account conv_dir = str(nuqql.config.get("dir")) + \ (f"/conversation/{self.conv.backend.name}/" f"{self.conv.account.aid}/{self.conv.name}") # make sure directory exists pathlib.Path(conv_dir).mkdir(parents=True, exist_ok=True) return conv_dir @staticmethod def _get_logger(name, file_name: str) -> logging.Logger: """ Create a logger for a conversation """ # create logger conv_logger = logging.getLogger(name) conv_logger.propagate = False conv_logger.setLevel(logging.DEBUG) # create handler fileh = logging.FileHandler(file_name) fileh.setLevel(logging.DEBUG) fileh.terminator = "\r\n" # create formatter formatter = logging.Formatter( # fmt="%(asctime)s %(levelname)-5.5s [%(name)s] %(message)s", fmt="%(message)s", datefmt="%s") # add formatter to handler fileh.setFormatter(formatter) # add handler to logger if not conv_logger.hasHandlers(): conv_logger.addHandler(fileh) # return logger to caller return conv_logger def init_logger(self) -> None: """ Init logger for a conversation """ logger.debug("initializing logger of conversation %s", self.conv.name) # get log dir and make sure it exists assert self.conv.backend and self.conv.account self.conv_path = self._get_conv_path() # create logger with log name and log file log_name = (f"nuqql.history.{self.conv.backend.name}." f"{self.conv.account.aid}.{self.conv.name}") self.log_file = self.conv_path + HISTORY_FILE self.logger = self._get_logger(log_name, self.log_file) @staticmethod def _parse_log_line(line: str) -> LogMessage: """ Parse line from log file and return a LogMessage """ # parse line parts = line.split(sep=" ", maxsplit=3) # tstamp = parts[0] direction = parts[1] is_own = False if direction == "OUT": is_own = True sender = parts[2] msg = parts[3][:-2] tstamp = datetime.datetime.fromtimestamp(int(parts[0])) # create and return LogMessage log_msg = LogMessage(tstamp, sender, msg, own=is_own) return log_msg @staticmethod def _create_log_line(log_msg: LogMessage) -> str: """ Create a line for the log files from a LogMessage """ # determine log line contents tstamp = round(log_msg.tstamp.timestamp()) direction = "IN" sender = log_msg.sender if log_msg.own: direction = "OUT" sender = "you" msg = log_msg.msg return f"{tstamp} {direction} {sender} {msg}" def get_lastread(self) -> Optional[LogMessage]: """ Get last read message from "lastread" file of the conversation """ logger.debug("getting lastread of conversation %s", self.conv.name) lastread_file = self.conv_path + LASTREAD_FILE try: with open(lastread_file, encoding='UTF-8', newline="\r\n") as in_file: for line in in_file: log_msg = self._parse_log_line(line) log_msg.is_read = True return log_msg logger.debug("lastread file of conversation %s is empty", self.conv.name) return None except FileNotFoundError: logger.debug("lastread file of conversation %s not found", self.conv.name) return None def set_lastread(self, log_msg: LogMessage) -> None: """ Set last read message in "lastread" file of the conversation """ logger.debug("setting lastread of conversation %s", self.conv.name) # create log line and write it to lastread file line = self._create_log_line(log_msg) + "\r\n" lines = [] lines.append(line) lastread_file = self.conv_path + LASTREAD_FILE with open(lastread_file, "w+", encoding='UTF-8') as out_file: out_file.writelines(lines) def get_last_log_line(self) -> Optional[LogMessage]: """ Read last LogMessage from log file """ logger.debug("getting last log line of conversation %s", self.conv.name) history_file = self.conv_path + HISTORY_FILE try: # negative seeking requires binary mode with open(history_file, "rb") as in_file: # check if file contains at least 2 bytes in_file.seek(0, os.SEEK_END) if in_file.tell() < 3: logger.debug("log of conversation %s seems to be empty", self.conv.name) return None # try to find last line in_file.seek(-3, os.SEEK_END) while in_file.read(2) != b"\r\n": try: in_file.seek(-3, os.SEEK_CUR) except IOError: in_file.seek(-2, os.SEEK_CUR) if in_file.tell() == 0: break # read and return last line as LogMessage last_line = in_file.read() log_msg = self._parse_log_line(last_line.decode()) return log_msg except FileNotFoundError: logger.debug("log file of conversation %s not found", self.conv.name) return None def init_log_from_file(self) -> None: """ Initialize a conversation's log from the conversation's log file """ logger.debug("initializing log of conversation %s from file %s", self.conv.name, self.log_file) # get last read log message last_read = self.get_lastread() is_read = True with open(self.log_file, encoding='UTF-8', newline="\r\n") as in_file: prev_msg = None for line in in_file: # parse log line and create log message log_msg = self._parse_log_line(line) log_msg.is_read = is_read # check if date changed between two messages, and print event if prev_msg and \ prev_msg.tstamp.date() != log_msg.tstamp.date(): date_change_msg = LogMessage( log_msg.tstamp, "<event>", (f"<Date changed to " f"{log_msg.tstamp.date()}>"), own=True) date_change_msg.is_read = True self.log.append(date_change_msg) prev_msg = log_msg # add log message to the conversation's log self.log.append(log_msg) # if this is the last read message, following message will be # marked as unread if last_read and last_read.is_equal(log_msg): is_read = False if self.log: # if there were any log messages in the log file, put a marker in # the log where the new messages start tstamp = datetime.datetime.now() tstamp_str = tstamp.strftime("%Y-%m-%d %H:%M:%S") new_conv_msg = f"<Started new conversation at {tstamp_str}.>" log_msg = LogMessage(tstamp, "<event>", new_conv_msg, own=True) log_msg.is_read = True self.log.append(log_msg) def log_to_file(self, log_msg: LogMessage) -> None: """ Write LogMessage to history log file and set lastread message """ logger.debug("logging msg to log file of conversation %s: %s", self.conv.name, log_msg) # create line and write it to history line = self._create_log_line(log_msg) assert self.logger self.logger.info(line) # assume user read all previous messages when user sends a message and # set lastread accordingly if log_msg.own: self.set_lastread(log_msg)
33.519713
78
0.561591
""" History: (file) logging for nuqql conversations """ import datetime import logging import pathlib import os from typing import List, Optional, TYPE_CHECKING import nuqql.config from .logmessage import LogMessage if TYPE_CHECKING: # imports for typing # pylint: disable=cyclic-import from .conversation import Conversation # noqa logger = logging.getLogger(__name__) HISTORY_FILE = "/history" LASTREAD_FILE = "/lastread" class History: """ Message history """ def __init__(self, conv: "Conversation") -> None: self.conv = conv self.conv_path = "" self.log: List[LogMessage] = [] self.logger: Optional[logging.Logger] = None self.log_file = "" # self.lastread_file = None def _get_conv_path(self) -> str: """ Get path for conversation history as a string and make sure it exists """ # construct directory path assert self.conv.backend and self.conv.account conv_dir = str(nuqql.config.get("dir")) + \ (f"/conversation/{self.conv.backend.name}/" f"{self.conv.account.aid}/{self.conv.name}") # make sure directory exists pathlib.Path(conv_dir).mkdir(parents=True, exist_ok=True) return conv_dir @staticmethod def _get_logger(name, file_name: str) -> logging.Logger: """ Create a logger for a conversation """ # create logger conv_logger = logging.getLogger(name) conv_logger.propagate = False conv_logger.setLevel(logging.DEBUG) # create handler fileh = logging.FileHandler(file_name) fileh.setLevel(logging.DEBUG) fileh.terminator = "\r\n" # create formatter formatter = logging.Formatter( # fmt="%(asctime)s %(levelname)-5.5s [%(name)s] %(message)s", fmt="%(message)s", datefmt="%s") # add formatter to handler fileh.setFormatter(formatter) # add handler to logger if not conv_logger.hasHandlers(): conv_logger.addHandler(fileh) # return logger to caller return conv_logger def init_logger(self) -> None: """ Init logger for a conversation """ logger.debug("initializing logger of conversation %s", self.conv.name) # get log dir and make sure it exists assert self.conv.backend and self.conv.account self.conv_path = self._get_conv_path() # create logger with log name and log file log_name = (f"nuqql.history.{self.conv.backend.name}." f"{self.conv.account.aid}.{self.conv.name}") self.log_file = self.conv_path + HISTORY_FILE self.logger = self._get_logger(log_name, self.log_file) @staticmethod def _parse_log_line(line: str) -> LogMessage: """ Parse line from log file and return a LogMessage """ # parse line parts = line.split(sep=" ", maxsplit=3) # tstamp = parts[0] direction = parts[1] is_own = False if direction == "OUT": is_own = True sender = parts[2] msg = parts[3][:-2] tstamp = datetime.datetime.fromtimestamp(int(parts[0])) # create and return LogMessage log_msg = LogMessage(tstamp, sender, msg, own=is_own) return log_msg @staticmethod def _create_log_line(log_msg: LogMessage) -> str: """ Create a line for the log files from a LogMessage """ # determine log line contents tstamp = round(log_msg.tstamp.timestamp()) direction = "IN" sender = log_msg.sender if log_msg.own: direction = "OUT" sender = "you" msg = log_msg.msg return f"{tstamp} {direction} {sender} {msg}" def get_lastread(self) -> Optional[LogMessage]: """ Get last read message from "lastread" file of the conversation """ logger.debug("getting lastread of conversation %s", self.conv.name) lastread_file = self.conv_path + LASTREAD_FILE try: with open(lastread_file, encoding='UTF-8', newline="\r\n") as in_file: for line in in_file: log_msg = self._parse_log_line(line) log_msg.is_read = True return log_msg logger.debug("lastread file of conversation %s is empty", self.conv.name) return None except FileNotFoundError: logger.debug("lastread file of conversation %s not found", self.conv.name) return None def set_lastread(self, log_msg: LogMessage) -> None: """ Set last read message in "lastread" file of the conversation """ logger.debug("setting lastread of conversation %s", self.conv.name) # create log line and write it to lastread file line = self._create_log_line(log_msg) + "\r\n" lines = [] lines.append(line) lastread_file = self.conv_path + LASTREAD_FILE with open(lastread_file, "w+", encoding='UTF-8') as out_file: out_file.writelines(lines) def get_last_log_line(self) -> Optional[LogMessage]: """ Read last LogMessage from log file """ logger.debug("getting last log line of conversation %s", self.conv.name) history_file = self.conv_path + HISTORY_FILE try: # negative seeking requires binary mode with open(history_file, "rb") as in_file: # check if file contains at least 2 bytes in_file.seek(0, os.SEEK_END) if in_file.tell() < 3: logger.debug("log of conversation %s seems to be empty", self.conv.name) return None # try to find last line in_file.seek(-3, os.SEEK_END) while in_file.read(2) != b"\r\n": try: in_file.seek(-3, os.SEEK_CUR) except IOError: in_file.seek(-2, os.SEEK_CUR) if in_file.tell() == 0: break # read and return last line as LogMessage last_line = in_file.read() log_msg = self._parse_log_line(last_line.decode()) return log_msg except FileNotFoundError: logger.debug("log file of conversation %s not found", self.conv.name) return None def init_log_from_file(self) -> None: """ Initialize a conversation's log from the conversation's log file """ logger.debug("initializing log of conversation %s from file %s", self.conv.name, self.log_file) # get last read log message last_read = self.get_lastread() is_read = True with open(self.log_file, encoding='UTF-8', newline="\r\n") as in_file: prev_msg = None for line in in_file: # parse log line and create log message log_msg = self._parse_log_line(line) log_msg.is_read = is_read # check if date changed between two messages, and print event if prev_msg and \ prev_msg.tstamp.date() != log_msg.tstamp.date(): date_change_msg = LogMessage( log_msg.tstamp, "<event>", (f"<Date changed to " f"{log_msg.tstamp.date()}>"), own=True) date_change_msg.is_read = True self.log.append(date_change_msg) prev_msg = log_msg # add log message to the conversation's log self.log.append(log_msg) # if this is the last read message, following message will be # marked as unread if last_read and last_read.is_equal(log_msg): is_read = False if self.log: # if there were any log messages in the log file, put a marker in # the log where the new messages start tstamp = datetime.datetime.now() tstamp_str = tstamp.strftime("%Y-%m-%d %H:%M:%S") new_conv_msg = f"<Started new conversation at {tstamp_str}.>" log_msg = LogMessage(tstamp, "<event>", new_conv_msg, own=True) log_msg.is_read = True self.log.append(log_msg) def log_to_file(self, log_msg: LogMessage) -> None: """ Write LogMessage to history log file and set lastread message """ logger.debug("logging msg to log file of conversation %s: %s", self.conv.name, log_msg) # create line and write it to history line = self._create_log_line(log_msg) assert self.logger self.logger.info(line) # assume user read all previous messages when user sends a message and # set lastread accordingly if log_msg.own: self.set_lastread(log_msg)
237
0
27
0340153eb1fc71ee60959c63e72695c6b41b4de0
22,086
py
Python
public/yum-3.2.28/yum/rpmtrans.py
chillaxor/blogbin
211202d513fa80a3d22fb3963f36a01a8dec5b68
[ "MIT" ]
8
2021-11-26T06:19:06.000Z
2022-01-11T01:30:11.000Z
initrd/usr/lib/python2.6/site-packages/yum/rpmtrans.py
OpenCloudOS/OpenCloudOS-tools
06b12aab3182f4207d78a5d8733be03f0d7b69a4
[ "MulanPSL-1.0" ]
5
2021-02-02T08:17:10.000Z
2022-02-27T06:53:42.000Z
public/yum-3.2.28/yum/rpmtrans.py
chillaxor/blogbin
211202d513fa80a3d22fb3963f36a01a8dec5b68
[ "MIT" ]
2
2021-12-21T08:36:02.000Z
2021-12-21T08:55:38.000Z
#!/usr/bin/python -t # 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. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # Copyright 2005 Duke University # Parts Copyright 2007 Red Hat, Inc import rpm import os import fcntl import time import logging import types import sys from yum.constants import * from yum import _ import misc import tempfile class RPMBaseCallback: ''' Base class for a RPMTransaction display callback class ''' def event(self, package, action, te_current, te_total, ts_current, ts_total): """ @param package: A yum package object or simple string of a package name @param action: A yum.constant transaction set state or in the obscure rpm repackage case it could be the string 'repackaging' @param te_current: Current number of bytes processed in the transaction element being processed @param te_total: Total number of bytes in the transaction element being processed @param ts_current: number of processes completed in whole transaction @param ts_total: total number of processes in the transaction. """ raise NotImplementedError() def scriptout(self, package, msgs): """package is the package. msgs is the messages that were output (if any).""" pass # This is ugly, but atm. rpm can go insane and run the "cleanup" phase # without the "install" phase if it gets an exception in it's callback. The # following means that we don't really need to know/care about that in the # display callback functions. # Note try/except's in RPMTransaction are for the same reason.
38.883803
99
0.566241
#!/usr/bin/python -t # 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. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # Copyright 2005 Duke University # Parts Copyright 2007 Red Hat, Inc import rpm import os import fcntl import time import logging import types import sys from yum.constants import * from yum import _ import misc import tempfile class NoOutputCallBack: def __init__(self): pass def event(self, package, action, te_current, te_total, ts_current, ts_total): """ @param package: A yum package object or simple string of a package name @param action: A yum.constant transaction set state or in the obscure rpm repackage case it could be the string 'repackaging' @param te_current: current number of bytes processed in the transaction element being processed @param te_total: total number of bytes in the transaction element being processed @param ts_current: number of processes completed in whole transaction @param ts_total: total number of processes in the transaction. """ # this is where a progress bar would be called pass def scriptout(self, package, msgs): """package is the package. msgs is the messages that were output (if any).""" pass def errorlog(self, msg): """takes a simple error msg string""" pass def filelog(self, package, action): # check package object type - if it is a string - just output it """package is the same as in event() - a package object or simple string action is also the same as in event()""" pass class RPMBaseCallback: ''' Base class for a RPMTransaction display callback class ''' def __init__(self): self.action = { TS_UPDATE : _('Updating'), TS_ERASE: _('Erasing'), TS_INSTALL: _('Installing'), TS_TRUEINSTALL : _('Installing'), TS_OBSOLETED: _('Obsoleted'), TS_OBSOLETING: _('Installing'), TS_UPDATED: _('Cleanup'), 'repackaging': _('Repackaging')} # The fileaction are not translated, most sane IMHO / Tim self.fileaction = { TS_UPDATE: 'Updated', TS_ERASE: 'Erased', TS_INSTALL: 'Installed', TS_TRUEINSTALL: 'Installed', TS_OBSOLETED: 'Obsoleted', TS_OBSOLETING: 'Installed', TS_UPDATED: 'Cleanup'} self.logger = logging.getLogger('yum.filelogging.RPMInstallCallback') def event(self, package, action, te_current, te_total, ts_current, ts_total): """ @param package: A yum package object or simple string of a package name @param action: A yum.constant transaction set state or in the obscure rpm repackage case it could be the string 'repackaging' @param te_current: Current number of bytes processed in the transaction element being processed @param te_total: Total number of bytes in the transaction element being processed @param ts_current: number of processes completed in whole transaction @param ts_total: total number of processes in the transaction. """ raise NotImplementedError() def scriptout(self, package, msgs): """package is the package. msgs is the messages that were output (if any).""" pass def errorlog(self, msg): # FIXME this should probably dump to the filelog, too print >> sys.stderr, msg def filelog(self, package, action): # If the action is not in the fileaction list then dump it as a string # hurky but, sadly, not much else if action in self.fileaction: msg = '%s: %s' % (self.fileaction[action], package) else: msg = '%s: %s' % (package, action) self.logger.info(msg) class SimpleCliCallBack(RPMBaseCallback): def __init__(self): RPMBaseCallback.__init__(self) self.lastmsg = None self.lastpackage = None # name of last package we looked at def event(self, package, action, te_current, te_total, ts_current, ts_total): # this is where a progress bar would be called msg = '%s: %s %s/%s [%s/%s]' % (self.action[action], package, te_current, te_total, ts_current, ts_total) if msg != self.lastmsg: print msg self.lastmsg = msg self.lastpackage = package def scriptout(self, package, msgs): if msgs: print msgs, # This is ugly, but atm. rpm can go insane and run the "cleanup" phase # without the "install" phase if it gets an exception in it's callback. The # following means that we don't really need to know/care about that in the # display callback functions. # Note try/except's in RPMTransaction are for the same reason. class _WrapNoExceptions: def __init__(self, parent): self.__parent = parent def __getattr__(self, name): """ Wraps all access to the parent functions. This is so it'll eat all exceptions because rpm doesn't like exceptions in the callback. """ func = getattr(self.__parent, name) def newFunc(*args, **kwargs): try: func(*args, **kwargs) except: pass newFunc.__name__ = func.__name__ newFunc.__doc__ = func.__doc__ newFunc.__dict__.update(func.__dict__) return newFunc class RPMTransaction: def __init__(self, base, test=False, display=NoOutputCallBack): if not callable(display): self.display = display else: self.display = display() # display callback self.display = _WrapNoExceptions(self.display) self.base = base # base yum object b/c we need so much self.test = test # are we a test? self.trans_running = False self.filehandles = {} self.total_actions = 0 self.total_installed = 0 self.complete_actions = 0 self.installed_pkg_names = [] self.total_removed = 0 self.logger = logging.getLogger('yum.filelogging.RPMInstallCallback') self.filelog = False self._setupOutputLogging(base.conf.rpmverbosity) if not os.path.exists(self.base.conf.persistdir): os.makedirs(self.base.conf.persistdir) # make the dir, just in case # Error checking? -- these should probably be where else def _fdSetNonblock(self, fd): """ Set the Non-blocking flag for a filedescriptor. """ flag = os.O_NONBLOCK current_flags = fcntl.fcntl(fd, fcntl.F_GETFL) if current_flags & flag: return fcntl.fcntl(fd, fcntl.F_SETFL, current_flags | flag) def _fdSetCloseOnExec(self, fd): """ Set the close on exec. flag for a filedescriptor. """ flag = fcntl.FD_CLOEXEC current_flags = fcntl.fcntl(fd, fcntl.F_GETFD) if current_flags & flag: return fcntl.fcntl(fd, fcntl.F_SETFD, current_flags | flag) def _setupOutputLogging(self, rpmverbosity="info"): # UGLY... set up the transaction to record output from scriptlets io_r = tempfile.NamedTemporaryFile() self._readpipe = io_r self._writepipe = open(io_r.name, 'w+b') # This is dark magic, it really needs to be "base.ts.ts". self.base.ts.ts.scriptFd = self._writepipe.fileno() rpmverbosity = {'critical' : 'crit', 'emergency' : 'emerg', 'error' : 'err', 'information' : 'info', 'warn' : 'warning'}.get(rpmverbosity, rpmverbosity) rpmverbosity = 'RPMLOG_' + rpmverbosity.upper() if not hasattr(rpm, rpmverbosity): rpmverbosity = 'RPMLOG_INFO' rpm.setVerbosity(getattr(rpm, rpmverbosity)) rpm.setLogFile(self._writepipe) def _shutdownOutputLogging(self): # reset rpm bits from reording output rpm.setVerbosity(rpm.RPMLOG_NOTICE) rpm.setLogFile(sys.stderr) try: self._writepipe.close() except: pass def _scriptOutput(self): try: out = self._readpipe.read() if not out: return None return out except IOError: pass def _scriptout(self, data): msgs = self._scriptOutput() self.display.scriptout(data, msgs) self.base.history.log_scriptlet_output(data, msgs) def __del__(self): self._shutdownOutputLogging() def _dopkgtup(self, hdr): tmpepoch = hdr['epoch'] if tmpepoch is None: epoch = '0' else: epoch = str(tmpepoch) return (hdr['name'], hdr['arch'], epoch, hdr['version'], hdr['release']) def _makeHandle(self, hdr): handle = '%s:%s.%s-%s-%s' % (hdr['epoch'], hdr['name'], hdr['version'], hdr['release'], hdr['arch']) return handle def ts_done(self, package, action): """writes out the portions of the transaction which have completed""" if self.test: return if not hasattr(self, '_ts_done'): self.ts_done_fn = '%s/transaction-done.%s' % (self.base.conf.persistdir, self._ts_time) try: self._ts_done = open(self.ts_done_fn, 'w') except (IOError, OSError), e: self.display.errorlog('could not open ts_done file: %s' % e) return self._fdSetCloseOnExec(self._ts_done.fileno()) # walk back through self._te_tuples # make sure the package and the action make some kind of sense # write it out and pop(0) from the list # make sure we have a list to work from if len(self._te_tuples) == 0: # if we don't then this is pretrans or postrans or a trigger # either way we have to respond correctly so just return and don't # emit anything return (t,e,n,v,r,a) = self._te_tuples[0] # what we should be on # make sure we're in the right action state msg = 'ts_done state is %s %s should be %s %s' % (package, action, t, n) if action in TS_REMOVE_STATES: if t != 'erase': self.display.filelog(package, msg) if action in TS_INSTALL_STATES: if t != 'install': self.display.filelog(package, msg) # check the pkg name out to make sure it matches if type(package) in types.StringTypes: name = package else: name = package.name if n != name: msg = 'ts_done name in te is %s should be %s' % (n, package) self.display.filelog(package, msg) # hope springs eternal that this isn't wrong msg = '%s %s:%s-%s-%s.%s\n' % (t,e,n,v,r,a) try: self._ts_done.write(msg) self._ts_done.flush() except (IOError, OSError), e: # Having incomplete transactions is probably worse than having # nothing. del self._ts_done misc.unlink_f(self.ts_done_fn) self._te_tuples.pop(0) def ts_all(self): """write out what our transaction will do""" # save the transaction elements into a list so we can run across them if not hasattr(self, '_te_tuples'): self._te_tuples = [] for te in self.base.ts: n = te.N() a = te.A() v = te.V() r = te.R() e = te.E() if e is None: e = '0' if te.Type() == 1: t = 'install' elif te.Type() == 2: t = 'erase' else: t = te.Type() # save this in a list self._te_tuples.append((t,e,n,v,r,a)) # write to a file self._ts_time = time.strftime('%Y-%m-%d.%H:%M.%S') tsfn = '%s/transaction-all.%s' % (self.base.conf.persistdir, self._ts_time) self.ts_all_fn = tsfn # to handle us being inside a chroot at this point # we hand back the right path to those 'outside' of the chroot() calls # but we're using the right path inside. if self.base.conf.installroot != '/': tsfn = tsfn.replace(os.path.normpath(self.base.conf.installroot),'') try: if not os.path.exists(os.path.dirname(tsfn)): os.makedirs(os.path.dirname(tsfn)) # make the dir, fo = open(tsfn, 'w') except (IOError, OSError), e: self.display.errorlog('could not open ts_all file: %s' % e) return try: for (t,e,n,v,r,a) in self._te_tuples: msg = "%s %s:%s-%s-%s.%s\n" % (t,e,n,v,r,a) fo.write(msg) fo.flush() fo.close() except (IOError, OSError), e: # Having incomplete transactions is probably worse than having # nothing. misc.unlink_f(tsfn) def callback( self, what, bytes, total, h, user ): if what == rpm.RPMCALLBACK_TRANS_START: self._transStart( bytes, total, h ) elif what == rpm.RPMCALLBACK_TRANS_PROGRESS: self._transProgress( bytes, total, h ) elif what == rpm.RPMCALLBACK_TRANS_STOP: self._transStop( bytes, total, h ) elif what == rpm.RPMCALLBACK_INST_OPEN_FILE: return self._instOpenFile( bytes, total, h ) elif what == rpm.RPMCALLBACK_INST_CLOSE_FILE: self._instCloseFile( bytes, total, h ) elif what == rpm.RPMCALLBACK_INST_PROGRESS: self._instProgress( bytes, total, h ) elif what == rpm.RPMCALLBACK_UNINST_START: self._unInstStart( bytes, total, h ) elif what == rpm.RPMCALLBACK_UNINST_PROGRESS: self._unInstProgress( bytes, total, h ) elif what == rpm.RPMCALLBACK_UNINST_STOP: self._unInstStop( bytes, total, h ) elif what == rpm.RPMCALLBACK_REPACKAGE_START: self._rePackageStart( bytes, total, h ) elif what == rpm.RPMCALLBACK_REPACKAGE_STOP: self._rePackageStop( bytes, total, h ) elif what == rpm.RPMCALLBACK_REPACKAGE_PROGRESS: self._rePackageProgress( bytes, total, h ) elif what == rpm.RPMCALLBACK_CPIO_ERROR: self._cpioError(bytes, total, h) elif what == rpm.RPMCALLBACK_UNPACK_ERROR: self._unpackError(bytes, total, h) # SCRIPT_ERROR is only in rpm >= 4.6.0 elif hasattr(rpm, "RPMCALLBACK_SCRIPT_ERROR") and what == rpm.RPMCALLBACK_SCRIPT_ERROR: self._scriptError(bytes, total, h) def _transStart(self, bytes, total, h): if bytes == 6: self.total_actions = total if self.test: return self.trans_running = True self.ts_all() # write out what transaction will do def _transProgress(self, bytes, total, h): pass def _transStop(self, bytes, total, h): pass def _instOpenFile(self, bytes, total, h): self.lastmsg = None hdr = None if h is not None: hdr, rpmloc = h[0], h[1] handle = self._makeHandle(hdr) try: fd = os.open(rpmloc, os.O_RDONLY) except OSError, e: self.display.errorlog("Error: Cannot open file %s: %s" % (rpmloc, e)) else: self.filehandles[handle]=fd if self.trans_running: self.total_installed += 1 self.complete_actions += 1 self.installed_pkg_names.append(hdr['name']) return fd else: self.display.errorlog("Error: No Header to INST_OPEN_FILE") def _instCloseFile(self, bytes, total, h): hdr = None if h is not None: hdr, rpmloc = h[0], h[1] handle = self._makeHandle(hdr) os.close(self.filehandles[handle]) fd = 0 if self.test: return if self.trans_running: pkgtup = self._dopkgtup(hdr) txmbrs = self.base.tsInfo.getMembers(pkgtup=pkgtup) for txmbr in txmbrs: self.display.filelog(txmbr.po, txmbr.output_state) self._scriptout(txmbr.po) # NOTE: We only do this for install, not erase atm. # because we don't get pkgtup data for erase (this # includes "Updated" pkgs). pid = self.base.history.pkg2pid(txmbr.po) state = self.base.history.txmbr2state(txmbr) self.base.history.trans_data_pid_end(pid, state) self.ts_done(txmbr.po, txmbr.output_state) def _instProgress(self, bytes, total, h): if h is not None: # If h is a string, we're repackaging. # Why the RPMCALLBACK_REPACKAGE_PROGRESS flag isn't set, I have no idea if type(h) == type(""): self.display.event(h, 'repackaging', bytes, total, self.complete_actions, self.total_actions) else: hdr, rpmloc = h[0], h[1] pkgtup = self._dopkgtup(hdr) txmbrs = self.base.tsInfo.getMembers(pkgtup=pkgtup) for txmbr in txmbrs: action = txmbr.output_state self.display.event(txmbr.po, action, bytes, total, self.complete_actions, self.total_actions) def _unInstStart(self, bytes, total, h): pass def _unInstProgress(self, bytes, total, h): pass def _unInstStop(self, bytes, total, h): self.total_removed += 1 self.complete_actions += 1 if h not in self.installed_pkg_names: self.display.filelog(h, TS_ERASE) action = TS_ERASE else: action = TS_UPDATED self.display.event(h, action, 100, 100, self.complete_actions, self.total_actions) self._scriptout(h) if self.test: return # and we're done self.ts_done(h, action) def _rePackageStart(self, bytes, total, h): pass def _rePackageStop(self, bytes, total, h): pass def _rePackageProgress(self, bytes, total, h): pass def _cpioError(self, bytes, total, h): hdr, rpmloc = h[0], h[1] pkgtup = self._dopkgtup(hdr) txmbrs = self.base.tsInfo.getMembers(pkgtup=pkgtup) for txmbr in txmbrs: msg = "Error in cpio payload of rpm package %s" % txmbr.po txmbr.output_state = TS_FAILED self.display.errorlog(msg) # FIXME - what else should we do here? raise a failure and abort? def _unpackError(self, bytes, total, h): hdr, rpmloc = h[0], h[1] pkgtup = self._dopkgtup(hdr) txmbrs = self.base.tsInfo.getMembers(pkgtup=pkgtup) for txmbr in txmbrs: txmbr.output_state = TS_FAILED msg = "Error unpacking rpm package %s" % txmbr.po self.display.errorlog(msg) # FIXME - should we raise? I need a test case pkg to see what the # right behavior should be def _scriptError(self, bytes, total, h): if not isinstance(h, types.TupleType): # fun with install/erase transactions, see rhbz#484729 h = (h, None) hdr, rpmloc = h[0], h[1] remove_hdr = False # if we're in a clean up/remove then hdr will not be an rpm.hdr if not isinstance(hdr, rpm.hdr): txmbrs = [hdr] remove_hdr = True else: pkgtup = self._dopkgtup(hdr) txmbrs = self.base.tsInfo.getMembers(pkgtup=pkgtup) for pkg in txmbrs: # "bytes" carries the failed scriptlet tag, # "total" carries fatal/non-fatal status scriptlet_name = rpm.tagnames.get(bytes, "<unknown>") if remove_hdr: package_name = pkg else: package_name = pkg.po if total: msg = ("Error in %s scriptlet in rpm package %s" % (scriptlet_name, package_name)) if not remove_hdr: pkg.output_state = TS_FAILED else: msg = ("Non-fatal %s scriptlet failure in rpm package %s" % (scriptlet_name, package_name)) self.display.errorlog(msg) # FIXME - what else should we do here? raise a failure and abort?
12,047
7,436
267
a3ff02be149a9bc975912b020d952fc202992fa1
6,662
py
Python
Code/0_only_conditioning_to_global_features/util_scripts.py
SCRFpublic/GeoModeling_Conditional_ProGAN
fb8df86f555fa19572ba7fd9ae719ede5cd961ff
[ "MIT" ]
8
2020-06-30T02:39:17.000Z
2022-03-17T07:14:11.000Z
Code/0_only_conditioning_to_global_features/util_scripts.py
SuihongSong/GeoModeling_Conditional_ProGAN
1ad99865743e161811d46ac96972885432d575e6
[ "MIT" ]
null
null
null
Code/0_only_conditioning_to_global_features/util_scripts.py
SuihongSong/GeoModeling_Conditional_ProGAN
1ad99865743e161811d46ac96972885432d575e6
[ "MIT" ]
6
2020-08-29T01:04:41.000Z
2022-01-04T06:04:30.000Z
import os import time import re import bisect from collections import OrderedDict import numpy as np import tensorflow as tf import scipy.ndimage import scipy.misc import config import misc import tfutil import train import dataset #---------------------------------------------------------------------------- # Generate random images or image grids using a previously trained network. # To run, uncomment the appropriate line in config.py and launch train.py. #---------------------------------------------------------------------------- # Generate MP4 video of random interpolations using a previously trained network. # To run, uncomment the appropriate line in config.py and launch train.py. #---------------------------------------------------------------------------- # Generate MP4 video of training progress for a previous training run. # To run, uncomment the appropriate line in config.py and launch train.py.
52.046875
239
0.641099
import os import time import re import bisect from collections import OrderedDict import numpy as np import tensorflow as tf import scipy.ndimage import scipy.misc import config import misc import tfutil import train import dataset #---------------------------------------------------------------------------- # Generate random images or image grids using a previously trained network. # To run, uncomment the appropriate line in config.py and launch train.py. def generate_fake_images(run_id, snapshot=None, grid_size=[1,1], num_pngs=1, image_shrink=1, png_prefix=None, random_seed=1000, minibatch_size=8): network_pkl = misc.locate_network_pkl(run_id, snapshot) if png_prefix is None: png_prefix = misc.get_id_string_for_network_pkl(network_pkl) + '-' random_state = np.random.RandomState(random_seed) print('Loading network from "%s"...' % network_pkl) G, D, Gs = misc.load_network_pkl(run_id, snapshot) result_subdir = misc.create_result_subdir(config.result_dir, config.desc) for png_idx in range(num_pngs): print('Generating png %d / %d...' % (png_idx, num_pngs)) latents = misc.random_latents(np.prod(grid_size), Gs, random_state=random_state) labels = np.zeros([latents.shape[0], 0], np.float32) images = Gs.run(latents, labels, minibatch_size=minibatch_size, num_gpus=config.num_gpus, out_mul=127.5, out_add=127.5, out_shrink=image_shrink, out_dtype=np.uint8) misc.save_image_grid(images, os.path.join(result_subdir, '%s%06d.png' % (png_prefix, png_idx)), [0,255], grid_size) open(os.path.join(result_subdir, '_done.txt'), 'wt').close() #---------------------------------------------------------------------------- # Generate MP4 video of random interpolations using a previously trained network. # To run, uncomment the appropriate line in config.py and launch train.py. def generate_interpolation_video(run_id, snapshot=None, grid_size=[1,1], image_shrink=1, image_zoom=1, duration_sec=60.0, smoothing_sec=1.0, mp4=None, mp4_fps=30, mp4_codec='libx265', mp4_bitrate='16M', random_seed=1000, minibatch_size=8): network_pkl = misc.locate_network_pkl(run_id, snapshot) if mp4 is None: mp4 = misc.get_id_string_for_network_pkl(network_pkl) + '-lerp.mp4' num_frames = int(np.rint(duration_sec * mp4_fps)) random_state = np.random.RandomState(random_seed) print('Loading network from "%s"...' % network_pkl) G, D, Gs = misc.load_network_pkl(run_id, snapshot) print('Generating latent vectors...') shape = [num_frames, np.prod(grid_size)] + Gs.input_shape[1:] # [frame, image, channel, component] all_latents = random_state.randn(*shape).astype(np.float32) all_latents = scipy.ndimage.gaussian_filter(all_latents, [smoothing_sec * mp4_fps] + [0] * len(Gs.input_shape), mode='wrap') all_latents /= np.sqrt(np.mean(np.square(all_latents))) # Frame generation func for moviepy. def make_frame(t): frame_idx = int(np.clip(np.round(t * mp4_fps), 0, num_frames - 1)) latents = all_latents[frame_idx] labels = np.zeros([latents.shape[0], 0], np.float32) images = Gs.run(latents, labels, minibatch_size=minibatch_size, num_gpus=config.num_gpus, out_mul=127.5, out_add=127.5, out_shrink=image_shrink, out_dtype=np.uint8) grid = misc.create_image_grid(images, grid_size).transpose(1, 2, 0) # HWC if image_zoom > 1: grid = scipy.ndimage.zoom(grid, [image_zoom, image_zoom, 1], order=0) if grid.shape[2] == 1: grid = grid.repeat(3, 2) # grayscale => RGB return grid # Generate video. import moviepy.editor # pip install moviepy result_subdir = misc.create_result_subdir(config.result_dir, config.desc) moviepy.editor.VideoClip(make_frame, duration=duration_sec).write_videofile(os.path.join(result_subdir, mp4), fps=mp4_fps, codec='libx264', bitrate=mp4_bitrate) open(os.path.join(result_subdir, '_done.txt'), 'wt').close() #---------------------------------------------------------------------------- # Generate MP4 video of training progress for a previous training run. # To run, uncomment the appropriate line in config.py and launch train.py. def generate_training_video(run_id, duration_sec=20.0, time_warp=1.5, mp4=None, mp4_fps=30, mp4_codec='libx265', mp4_bitrate='16M'): src_result_subdir = misc.locate_result_subdir(run_id) if mp4 is None: mp4 = os.path.basename(src_result_subdir) + '-train.mp4' # Parse log. times = [] snaps = [] # [(png, kimg, lod), ...] with open(os.path.join(src_result_subdir, 'log.txt'), 'rt') as log: for line in log: k = re.search(r'kimg ([\d\.]+) ', line) l = re.search(r'lod ([\d\.]+) ', line) t = re.search(r'time (\d+d)? *(\d+h)? *(\d+m)? *(\d+s)? ', line) if k and l and t: k = float(k.group(1)) l = float(l.group(1)) t = [int(t.group(i)[:-1]) if t.group(i) else 0 for i in range(1, 5)] t = t[0] * 24*60*60 + t[1] * 60*60 + t[2] * 60 + t[3] png = os.path.join(src_result_subdir, 'fakes%06d.png' % int(np.floor(k))) if os.path.isfile(png): times.append(t) snaps.append((png, k, l)) assert len(times) # Frame generation func for moviepy. png_cache = [None, None] # [png, img] def make_frame(t): wallclock = ((t / duration_sec) ** time_warp) * times[-1] png, kimg, lod = snaps[max(bisect.bisect(times, wallclock) - 1, 0)] if png_cache[0] == png: img = png_cache[1] else: img = scipy.misc.imread(png) while img.shape[1] > 1920 or img.shape[0] > 1080: img = img.astype(np.float32).reshape(img.shape[0]//2, 2, img.shape[1]//2, 2, -1).mean(axis=(1,3)) png_cache[:] = [png, img] img = misc.draw_text_label(img, 'lod %.2f' % lod, 16, img.shape[0]-4, alignx=0.0, aligny=1.0) img = misc.draw_text_label(img, misc.format_time(int(np.rint(wallclock))), img.shape[1]//2, img.shape[0]-4, alignx=0.5, aligny=1.0) img = misc.draw_text_label(img, '%.0f kimg' % kimg, img.shape[1]-16, img.shape[0]-4, alignx=1.0, aligny=1.0) return img # Generate video. import moviepy.editor # pip install moviepy result_subdir = misc.create_result_subdir(config.result_dir, config.desc) moviepy.editor.VideoClip(make_frame, duration=duration_sec).write_videofile(os.path.join(result_subdir, mp4), fps=mp4_fps, codec='libx264', bitrate=mp4_bitrate) open(os.path.join(result_subdir, '_done.txt'), 'wt').close()
5,668
0
70
e6a4498e34d586e63ac231efaeaa708038779a59
663
py
Python
sparse_causal_model_learner_rl/loss/autoencoder.py
sergeivolodin/causality-disentanglement-rl
5a41b4a2e3d85fa7e9c8450215fdc6cf954df867
[ "CC0-1.0" ]
2
2020-12-11T05:26:24.000Z
2021-04-21T06:12:58.000Z
sparse_causal_model_learner_rl/loss/autoencoder.py
sergeivolodin/causality-disentanglement-rl
5a41b4a2e3d85fa7e9c8450215fdc6cf954df867
[ "CC0-1.0" ]
9
2020-04-30T16:29:50.000Z
2021-03-26T07:32:18.000Z
sparse_causal_model_learner_rl/loss/autoencoder.py
sergeivolodin/causality-disentanglement-rl
5a41b4a2e3d85fa7e9c8450215fdc6cf954df867
[ "CC0-1.0" ]
null
null
null
import gin import torch @gin.configurable def pow_loss(X, X_true, power=2, **kwargs): """Difference between items to a power, avg over dataset, sum over items.""" assert X.shape == X_true.shape, (X.shape, X_true.shape) abs_diff = torch.abs(X - X_true) loss = torch.pow(abs_diff, power) # mean over batches loss = torch.mean(loss, dim=0) # sum over the rest loss = torch.sum(loss) return loss @gin.configurable def ae_loss(autoencoder, X_chw, loss_fcn, **kwargs): """Vanilla autoencoder loss.""" reconstructed = autoencoder(X_chw) value = loss_fcn(X_chw, reconstructed) return value
26.52
81
0.653092
import gin import torch @gin.configurable def pow_loss(X, X_true, power=2, **kwargs): """Difference between items to a power, avg over dataset, sum over items.""" assert X.shape == X_true.shape, (X.shape, X_true.shape) abs_diff = torch.abs(X - X_true) loss = torch.pow(abs_diff, power) # mean over batches loss = torch.mean(loss, dim=0) # sum over the rest loss = torch.sum(loss) return loss @gin.configurable def ae_loss(autoencoder, X_chw, loss_fcn, **kwargs): """Vanilla autoencoder loss.""" reconstructed = autoencoder(X_chw) value = loss_fcn(X_chw, reconstructed) return value
0
0
0
35704a18f20d0f4295ef668109534846720c2409
405
py
Python
funolympics/migrations/0002_auto_20200522_1531.py
codeema/Yokiyo
2e710bca487ee393784c116b7db2db7337f73d40
[ "MIT" ]
null
null
null
funolympics/migrations/0002_auto_20200522_1531.py
codeema/Yokiyo
2e710bca487ee393784c116b7db2db7337f73d40
[ "MIT" ]
6
2020-05-20T15:29:55.000Z
2021-09-08T02:02:43.000Z
funolympics/migrations/0002_auto_20200522_1531.py
codeema/Yokiyo
2e710bca487ee393784c116b7db2db7337f73d40
[ "MIT" ]
null
null
null
# Generated by Django 3.0.6 on 2020-05-22 15:31 from django.db import migrations, models
21.315789
75
0.604938
# Generated by Django 3.0.6 on 2020-05-22 15:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('funolympics', '0001_initial'), ] operations = [ migrations.AlterField( model_name='blog', name='blogimage', field=models.ImageField(upload_to='static/images/blogimages/'), ), ]
0
291
23
a700309f30bff5775f2751480b9a77e37e2435af
5,731
py
Python
b4sacr.py
DarthLayer/CapitalCalculator
8d637e0dd68edaec33f9c96b505889c64b3df15f
[ "MIT" ]
2
2018-01-04T20:44:04.000Z
2018-11-01T09:54:33.000Z
b4sacr.py
DarthLayer/CapitalCalculator
8d637e0dd68edaec33f9c96b505889c64b3df15f
[ "MIT" ]
null
null
null
b4sacr.py
DarthLayer/CapitalCalculator
8d637e0dd68edaec33f9c96b505889c64b3df15f
[ "MIT" ]
null
null
null
""" Basel IV Standardised Approach to Credit Risk.py (b4sacr.py) ---------------- This package encapsulates the Basel Committee on Bank Supervision's finalisation of Basel III for standardised credit risk. The text is found at https://www.bis.org/bcbs/publ/d424.htm This will serve as the foundation of any Basel 4 impact analysis. ----------------- Blake Stratton A key objective of the revisions in this document is to reduce excessive variability of risk- weighted assets (RWAs). The revisions (i) enhance the robustness and risk sensitivity of the standardised approaches for credit risk and operational risk; (ii) constrain the use of internally-modelled approaches (particularly for low default exposures such as FIs and large corporates); and (iii) complement the risk-weighted capital ratio with a finalised leverage ratio and a standardised RWA capital floor. A comment on nomenclature: BCBS calls this package of reforms Basel III finalisation however the industry - atleast for the time being - refers to it as Basel IV. We will refer to these changes as Basel IV until such a time that it no longer suits. This package is structured as: - classes for each of the exposure classes See Basel4.py script for overarching logic for Basel 4 packages. """ """ Version 0.1 2017-12-12 Written introduction and start on sacr Version 0.2 2018-01-01 """ """ Insert dependencies here """ import pandas as pd class sacr(): """ """ "TO INSERT LOOKUPS BASED ON BOOKING ENTITY AND CTPYID ONCE BASEL4.PY BUILT TO GET VALUES LIKE SUPERVISOR____"
39.253425
116
0.558367
""" Basel IV Standardised Approach to Credit Risk.py (b4sacr.py) ---------------- This package encapsulates the Basel Committee on Bank Supervision's finalisation of Basel III for standardised credit risk. The text is found at https://www.bis.org/bcbs/publ/d424.htm This will serve as the foundation of any Basel 4 impact analysis. ----------------- Blake Stratton A key objective of the revisions in this document is to reduce excessive variability of risk- weighted assets (RWAs). The revisions (i) enhance the robustness and risk sensitivity of the standardised approaches for credit risk and operational risk; (ii) constrain the use of internally-modelled approaches (particularly for low default exposures such as FIs and large corporates); and (iii) complement the risk-weighted capital ratio with a finalised leverage ratio and a standardised RWA capital floor. A comment on nomenclature: BCBS calls this package of reforms Basel III finalisation however the industry - atleast for the time being - refers to it as Basel IV. We will refer to these changes as Basel IV until such a time that it no longer suits. This package is structured as: - classes for each of the exposure classes See Basel4.py script for overarching logic for Basel 4 packages. """ """ Version 0.1 2017-12-12 Written introduction and start on sacr Version 0.2 2018-01-01 """ """ Insert dependencies here """ import pandas as pd class sacr(): """ """ def __init__(self,bookingentity,dealid,ctptyid,exposureclass,extcrrating,oecdeca): self.bookingentity = bookingentity self.dealid = dealid self.ctptyid = ctptyid self.exposureclass = exposureclass self.extcrrating = extcrrating self.oecdeca = oecdeca "TO INSERT LOOKUPS BASED ON BOOKING ENTITY AND CTPYID ONCE BASEL4.PY BUILT TO GET VALUES LIKE SUPERVISOR____" def RW(self,exposureclass,extcrrating,oecdeca,ctptyid): if exposureclass == "Sovereign": """Note for where national regulators set lower RW See paragraph BCBS d424 A.8. If national regulator allows lower risk-weight for exposures denominated in local currency with corresponding liabilities then a lower risk-weight may apply for sovereigns. """ """ See paragraph A.10. Exposures to counterparties in this list may a 0% risk-weight. TO BE UPDATED WITH ACTUAL COUNTERPARTY IDs OR PASSED IN AS LIST """ if ctptyid in [ "Bank for International Settlments", "The International Monetary Fund", "The European Union", "The European Stability Mechanism" ]: self.rwtreatment == "SACR-Sovereign-0%Multinationals" return 0.00 elif supervisoroecdused is True: """For national regulators who recognise ECA scores. See paragraph A.9. """ self.rwtreatment == "SACR-Sovereign-OECD{oecdeca}" if oecdeca in [0,1]: return 0.00 elif oecdeca == 2: return 0.20 elif oecdeca == 3: return 0.50 elif oecdeca in [4,5,6]: return 1.00 elif oecdeca == 7: return 1.50 else: return None else: """The standard risk-weight table See paragraph A.7. Exposures to sovereigns and their central banks will be risk-weighted as follows, after taking into account the preceding logic. Below logic is based on S&P credit rating mapping. Input will need to be mapped to S&P equivalent. Unchanged since Basel II framework (June 2006). """ self.rwtreatment == "SACR-Sovereign-ExtCR{extcrrating}" if extcrrating in ["AAA","AA+","AA","AA-"]: return 0.00 elif extcrrating in ["A+","A","A-"]: return 0.20 elif extcrrating in ["BBB+","BBB","BBB-"]: return 0.50 elif extcrrating in ["BB+","BB","BB-","B+","B","B-"]: return 1.00 elif extcrrating in ["CCC","CC","C"]: return 1.50 elif extcrrating == "D": return 0.00 elif extcrrating == "NR"#Not rated return 1.00 else: return None if exposureclass == "Public Sector": """Exposures to domestic public sector entities Risk weighted according to either of the following two options dictated by the national supervisor """ if supervisorsacrpseoption == 1: """Based on external credit rating of """ if extcrrating in ["AAA","AA+","AA","AA-"]: return 0.00 elif extcrrating in ["A+","A","A-"]: return 0.20 elif extcrrating in ["BBB+","BBB","BBB-"]: return 0.50 elif extcrrating in ["BB+","BB","BB-","B+","B","B-"]: return 1.00 elif extcrrating in ["CCC","CC","C"]: return 1.50 elif extcrrating == "D": return 0.00 elif extcrrating == "NR"#Not rated return 1.00 else: return None
4,107
0
54
fb4d06256f950ae197b74762203759121b1aa3dc
8,646
py
Python
bbp/utils/batch/bbp_converge.py
ZhangHCFJEA/bbp
33bd999cf8d719c49f9a904872c62f02eb5850d1
[ "BSD-3-Clause" ]
28
2017-10-31T09:16:30.000Z
2022-02-28T23:44:29.000Z
bbp/utils/batch/bbp_converge.py
ZhangHCFJEA/bbp
33bd999cf8d719c49f9a904872c62f02eb5850d1
[ "BSD-3-Clause" ]
37
2017-05-23T15:15:35.000Z
2022-02-05T09:13:18.000Z
bbp/utils/batch/bbp_converge.py
ZhangHCFJEA/bbp
33bd999cf8d719c49f9a904872c62f02eb5850d1
[ "BSD-3-Clause" ]
26
2017-09-21T17:43:33.000Z
2021-11-29T06:34:30.000Z
#!/usr/bin/env python """ Copyright 2010-2019 University Of Southern California Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Program used to learn how many realizations are needed for a method to converge. This program is based on the original bbp_converge script from Karen Assatourians, Western University """ from __future__ import division, print_function # Import Python modules import os import sys import glob import math import curses import random import shutil import argparse import numpy as np import matplotlib as mpl if mpl.get_backend() != 'agg': mpl.use('Agg') # Disables use of Tk/X11 import pylab # Import Broadband modules import bband_utils import plot_config DEFAULT_SEED = 123456789 def update_progress_bar(progress, total): """ Keeps the progress bar moving """ bar_size = 40 completed = int(progress * bar_size / total) missing = bar_size - completed progress_bar = "%s%s" % ("*" * completed, "-" * missing) print("\r Iteration: %s : %d" % (progress_bar, progress), end="") sys.stdout.flush() def parse_arguments(): """ This function takes care of parsing the command-line arguments and asking the user for any missing parameters that we need """ parser = argparse.ArgumentParser(description="Learn how many " " realizations are needed " " for methods to converge.") parser.add_argument("--input_dir", "-i", dest="input_dir", required=True, help="input directory") parser.add_argument("-o", "--output", dest="output_file", required=True, help="output png file") parser.add_argument("--limit", "-l", type=float, dest="limit", default=0.02, help="difference limit") parser.add_argument("--ns", type=int, default=10000, dest="sampling", help="number of sampling") parser.add_argument("-c", "--codebase", required=True, dest="codebase", help="method used for the simulation") parser.add_argument("--colormap", default="Paired", dest="colormap", help="matplotlib colormap to use") args = parser.parse_args() return args def read_input_bias_data(input_dir): """ Read the bias data from all realizations """ periods = [] data = [] event_label = None realizations = sorted(os.listdir(input_dir)) for realization in realizations: basedir = os.path.join(input_dir, realization) bias_file = glob.glob("%s%s*-rotd50.bias" % (basedir, os.sep)) if len(bias_file) != 1: raise bband_utils.ProcessingError("Bias file not found for " "realization %s!" % (realization)) bias_file = bias_file[0] # Let's capture the event label if event_label is None: event_label = os.path.basename(bias_file).split("-")[0] input_file = open(bias_file, 'r') cur_periods = [] cur_data = [] for line in input_file: line = line.strip() # Skip comments and empty lines if line.startswith("#") or line.startswith("%") or not line: continue tokens = [float(token) for token in line.split()] cur_periods.append(tokens[0]) cur_data.append(tokens[1]) # Close input_file input_file.close() # Keep list of periods if not already done if not periods: periods = cur_periods # And keep data data.append(cur_data) bias_data = {} bias_data["num_periods"] = len(periods) bias_data["periods"] = periods bias_data["num_realizations"] = len(realizations) bias_data["data"] = data bias_data["event_label"] = event_label return bias_data def find_gavg(bias_data): """ Calculate averages """ gavg = np.zeros(bias_data["num_periods"]) data = bias_data["data"] num_realizations = float(bias_data["num_realizations"]) for realization in data: for cur_period in range(0, bias_data["num_periods"]): gavg[cur_period] = (gavg[cur_period] + realization[cur_period] / num_realizations) bias_data["gavg"] = gavg return bias_data def calculate_probabilities(bias_data, limit, sampling): """ Calculate the probabilities """ ratios_by_period = [[] for _ in range(0, bias_data["num_periods"])] random.seed(DEFAULT_SEED) for cur_realization in range(1, bias_data["num_realizations"] + 1): update_progress_bar(cur_realization, bias_data["num_realizations"]) ratio = np.zeros(bias_data["num_periods"]) for _ in range(0, sampling): avg = np.zeros(bias_data["num_periods"]) for _ in range(0, cur_realization): random_int = (int(random.random() * bias_data["num_realizations"])) if random_int > bias_data["num_realizations"]: random_int = bias_data["num_realizations"] for nper in range(0, bias_data["num_periods"]): avg[nper] = (avg[nper] + bias_data["data"][random_int][nper] / float(cur_realization)) for nper in range(0, bias_data["num_periods"]): if abs(avg[nper] - bias_data["gavg"][nper]) <= limit: ratio[nper] = ratio[nper] + 1 ratio = ratio / sampling # Now re-shuffle so that we split by periods not realizations for val, dest in zip(ratio, ratios_by_period): dest.append(val) # Save calculated data bias_data["ratios"] = ratios_by_period print() return bias_data def plot_results(bias_data, codebase, colormap, output_file): """ Generate plot showing results calculated from all realizations """ fig, ax = pylab.plt.subplots() xlocs = range(1, bias_data["num_periods"] + 1) ylocs = list(np.full(bias_data["num_periods"], bias_data["num_realizations"])) bars = ax.bar(xlocs, ylocs) ax = bars[0].axes lim = ax.get_xlim() + ax.get_ylim() for bar, ratio in zip(bars, bias_data["ratios"]): rev_ratio = ratio[::-1] gradient = np.atleast_2d(rev_ratio).T bar.set_zorder(1) bar.set_facecolor("none") x, y = bar.get_xy() w, h = bar.get_width(), bar.get_height() im = ax.imshow(gradient, extent=[x, x + w, y, y + h], cmap=pylab.get_cmap(colormap), vmin=0.0, vmax=1.0, aspect="auto", zorder=0) ax.axis(lim) fig.colorbar(im) pylab.xlim(0, bias_data["num_periods"] + 2) pylab.plt.xticks([val + 0.5 for val in xlocs], bias_data["periods"], rotation='vertical', fontsize=6) #frame1 = pylab.gca() #frame1.axes.xaxis.set_ticklabels([]) #frame1.axes.yaxis.set_ticklabels([]) pylab.xlabel("Periods") pylab.ylabel("Number of Realizations") pylab.title(("Convergence Plot - %s Method - %s" % (codebase, bias_data["event_label"])), size=10) # Save plot fig.savefig(output_file, format="png", transparent=False, dpi=plot_config.dpi) def main(): """ Figure out how many realizations are needed for methods to converge """ # Parse command-line options args = parse_arguments() # Copy options limit = args.limit sampling = args.sampling base_input_dir = args.input_dir output_file = args.output_file colormap = args.colormap codebase = args.codebase # Read input data input_dir = os.path.join(base_input_dir, "Sims", "outdata") bias_data = read_input_bias_data(input_dir) bias_data = find_gavg(bias_data) bias_data = calculate_probabilities(bias_data, limit, sampling) plot_results(bias_data, codebase, colormap, output_file) if __name__ == "__main__": main()
34.862903
94
0.614157
#!/usr/bin/env python """ Copyright 2010-2019 University Of Southern California Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Program used to learn how many realizations are needed for a method to converge. This program is based on the original bbp_converge script from Karen Assatourians, Western University """ from __future__ import division, print_function # Import Python modules import os import sys import glob import math import curses import random import shutil import argparse import numpy as np import matplotlib as mpl if mpl.get_backend() != 'agg': mpl.use('Agg') # Disables use of Tk/X11 import pylab # Import Broadband modules import bband_utils import plot_config DEFAULT_SEED = 123456789 def update_progress_bar(progress, total): """ Keeps the progress bar moving """ bar_size = 40 completed = int(progress * bar_size / total) missing = bar_size - completed progress_bar = "%s%s" % ("*" * completed, "-" * missing) print("\r Iteration: %s : %d" % (progress_bar, progress), end="") sys.stdout.flush() def parse_arguments(): """ This function takes care of parsing the command-line arguments and asking the user for any missing parameters that we need """ parser = argparse.ArgumentParser(description="Learn how many " " realizations are needed " " for methods to converge.") parser.add_argument("--input_dir", "-i", dest="input_dir", required=True, help="input directory") parser.add_argument("-o", "--output", dest="output_file", required=True, help="output png file") parser.add_argument("--limit", "-l", type=float, dest="limit", default=0.02, help="difference limit") parser.add_argument("--ns", type=int, default=10000, dest="sampling", help="number of sampling") parser.add_argument("-c", "--codebase", required=True, dest="codebase", help="method used for the simulation") parser.add_argument("--colormap", default="Paired", dest="colormap", help="matplotlib colormap to use") args = parser.parse_args() return args def read_input_bias_data(input_dir): """ Read the bias data from all realizations """ periods = [] data = [] event_label = None realizations = sorted(os.listdir(input_dir)) for realization in realizations: basedir = os.path.join(input_dir, realization) bias_file = glob.glob("%s%s*-rotd50.bias" % (basedir, os.sep)) if len(bias_file) != 1: raise bband_utils.ProcessingError("Bias file not found for " "realization %s!" % (realization)) bias_file = bias_file[0] # Let's capture the event label if event_label is None: event_label = os.path.basename(bias_file).split("-")[0] input_file = open(bias_file, 'r') cur_periods = [] cur_data = [] for line in input_file: line = line.strip() # Skip comments and empty lines if line.startswith("#") or line.startswith("%") or not line: continue tokens = [float(token) for token in line.split()] cur_periods.append(tokens[0]) cur_data.append(tokens[1]) # Close input_file input_file.close() # Keep list of periods if not already done if not periods: periods = cur_periods # And keep data data.append(cur_data) bias_data = {} bias_data["num_periods"] = len(periods) bias_data["periods"] = periods bias_data["num_realizations"] = len(realizations) bias_data["data"] = data bias_data["event_label"] = event_label return bias_data def find_gavg(bias_data): """ Calculate averages """ gavg = np.zeros(bias_data["num_periods"]) data = bias_data["data"] num_realizations = float(bias_data["num_realizations"]) for realization in data: for cur_period in range(0, bias_data["num_periods"]): gavg[cur_period] = (gavg[cur_period] + realization[cur_period] / num_realizations) bias_data["gavg"] = gavg return bias_data def calculate_probabilities(bias_data, limit, sampling): """ Calculate the probabilities """ ratios_by_period = [[] for _ in range(0, bias_data["num_periods"])] random.seed(DEFAULT_SEED) for cur_realization in range(1, bias_data["num_realizations"] + 1): update_progress_bar(cur_realization, bias_data["num_realizations"]) ratio = np.zeros(bias_data["num_periods"]) for _ in range(0, sampling): avg = np.zeros(bias_data["num_periods"]) for _ in range(0, cur_realization): random_int = (int(random.random() * bias_data["num_realizations"])) if random_int > bias_data["num_realizations"]: random_int = bias_data["num_realizations"] for nper in range(0, bias_data["num_periods"]): avg[nper] = (avg[nper] + bias_data["data"][random_int][nper] / float(cur_realization)) for nper in range(0, bias_data["num_periods"]): if abs(avg[nper] - bias_data["gavg"][nper]) <= limit: ratio[nper] = ratio[nper] + 1 ratio = ratio / sampling # Now re-shuffle so that we split by periods not realizations for val, dest in zip(ratio, ratios_by_period): dest.append(val) # Save calculated data bias_data["ratios"] = ratios_by_period print() return bias_data def plot_results(bias_data, codebase, colormap, output_file): """ Generate plot showing results calculated from all realizations """ fig, ax = pylab.plt.subplots() xlocs = range(1, bias_data["num_periods"] + 1) ylocs = list(np.full(bias_data["num_periods"], bias_data["num_realizations"])) bars = ax.bar(xlocs, ylocs) ax = bars[0].axes lim = ax.get_xlim() + ax.get_ylim() for bar, ratio in zip(bars, bias_data["ratios"]): rev_ratio = ratio[::-1] gradient = np.atleast_2d(rev_ratio).T bar.set_zorder(1) bar.set_facecolor("none") x, y = bar.get_xy() w, h = bar.get_width(), bar.get_height() im = ax.imshow(gradient, extent=[x, x + w, y, y + h], cmap=pylab.get_cmap(colormap), vmin=0.0, vmax=1.0, aspect="auto", zorder=0) ax.axis(lim) fig.colorbar(im) pylab.xlim(0, bias_data["num_periods"] + 2) pylab.plt.xticks([val + 0.5 for val in xlocs], bias_data["periods"], rotation='vertical', fontsize=6) #frame1 = pylab.gca() #frame1.axes.xaxis.set_ticklabels([]) #frame1.axes.yaxis.set_ticklabels([]) pylab.xlabel("Periods") pylab.ylabel("Number of Realizations") pylab.title(("Convergence Plot - %s Method - %s" % (codebase, bias_data["event_label"])), size=10) # Save plot fig.savefig(output_file, format="png", transparent=False, dpi=plot_config.dpi) def main(): """ Figure out how many realizations are needed for methods to converge """ # Parse command-line options args = parse_arguments() # Copy options limit = args.limit sampling = args.sampling base_input_dir = args.input_dir output_file = args.output_file colormap = args.colormap codebase = args.codebase # Read input data input_dir = os.path.join(base_input_dir, "Sims", "outdata") bias_data = read_input_bias_data(input_dir) bias_data = find_gavg(bias_data) bias_data = calculate_probabilities(bias_data, limit, sampling) plot_results(bias_data, codebase, colormap, output_file) if __name__ == "__main__": main()
0
0
0
8039d0bc14c0f908d62088df4ee384c5c13e5f06
1,704
py
Python
devilry/apps/core/models/__init__.py
aless80/devilry-django
416c262e75170d5662542f15e2d7fecf5ab84730
[ "BSD-3-Clause" ]
29
2015-01-18T22:56:23.000Z
2020-11-10T21:28:27.000Z
devilry/apps/core/models/__init__.py
aless80/devilry-django
416c262e75170d5662542f15e2d7fecf5ab84730
[ "BSD-3-Clause" ]
786
2015-01-06T16:10:18.000Z
2022-03-16T11:10:50.000Z
devilry/apps/core/models/__init__.py
aless80/devilry-django
416c262e75170d5662542f15e2d7fecf5ab84730
[ "BSD-3-Clause" ]
15
2015-04-06T06:18:43.000Z
2021-02-24T12:28:30.000Z
from .abstract_is_admin import AbstractIsAdmin from .abstract_is_examiner import AbstractIsExaminer from .abstract_is_candidate import AbstractIsCandidate from .basenode import BaseNode from .subject import Subject from .period import Period, PeriodApplicationKeyValue from .period_tag import PeriodTag from .relateduser import RelatedExaminer, RelatedStudent, RelatedStudentKeyValue from .assignment import Assignment from .pointrange_to_grade import PointRangeToGrade from .pointrange_to_grade import PointToGradeMap from .assignment_group import AssignmentGroup, AssignmentGroupTag from .assignment_group_history import AssignmentGroupHistory from .delivery import Delivery from .deadline import Deadline from .candidate import Candidate from .static_feedback import StaticFeedback, StaticFeedbackFileAttachment from .filemeta import FileMeta from .devilryuserprofile import DevilryUserProfile from .examiner import Examiner from .groupinvite import GroupInvite from .examiner_candidate_group_history import ExaminerAssignmentGroupHistory, CandidateAssignmentGroupHistory __all__ = ("AbstractIsAdmin", "AbstractIsExaminer", "AbstractIsCandidate", "BaseNode", "Subject", "Period", "PeriodTag", 'RelatedExaminer', 'RelatedStudent', "RelatedStudentKeyValue", "Assignment", "AssignmentGroup", "AssignmentGroupTag", "Delivery", "Deadline", "Candidate", "StaticFeedback", "FileMeta", "DevilryUserProfile", 'PeriodApplicationKeyValue', 'Examiner', 'GroupInvite', 'StaticFeedbackFileAttachment', 'PointRangeToGrade', 'PointToGradeMap', 'AssignmentGroupHistory', 'ExaminerAssignmentGroupHistory', 'CandidateAssignmentGroupHistory')
53.25
109
0.814554
from .abstract_is_admin import AbstractIsAdmin from .abstract_is_examiner import AbstractIsExaminer from .abstract_is_candidate import AbstractIsCandidate from .basenode import BaseNode from .subject import Subject from .period import Period, PeriodApplicationKeyValue from .period_tag import PeriodTag from .relateduser import RelatedExaminer, RelatedStudent, RelatedStudentKeyValue from .assignment import Assignment from .pointrange_to_grade import PointRangeToGrade from .pointrange_to_grade import PointToGradeMap from .assignment_group import AssignmentGroup, AssignmentGroupTag from .assignment_group_history import AssignmentGroupHistory from .delivery import Delivery from .deadline import Deadline from .candidate import Candidate from .static_feedback import StaticFeedback, StaticFeedbackFileAttachment from .filemeta import FileMeta from .devilryuserprofile import DevilryUserProfile from .examiner import Examiner from .groupinvite import GroupInvite from .examiner_candidate_group_history import ExaminerAssignmentGroupHistory, CandidateAssignmentGroupHistory __all__ = ("AbstractIsAdmin", "AbstractIsExaminer", "AbstractIsCandidate", "BaseNode", "Subject", "Period", "PeriodTag", 'RelatedExaminer', 'RelatedStudent', "RelatedStudentKeyValue", "Assignment", "AssignmentGroup", "AssignmentGroupTag", "Delivery", "Deadline", "Candidate", "StaticFeedback", "FileMeta", "DevilryUserProfile", 'PeriodApplicationKeyValue', 'Examiner', 'GroupInvite', 'StaticFeedbackFileAttachment', 'PointRangeToGrade', 'PointToGradeMap', 'AssignmentGroupHistory', 'ExaminerAssignmentGroupHistory', 'CandidateAssignmentGroupHistory')
0
0
0
6c23ab9b4be608106c13982dd7e9c7f2ae389499
13,591
py
Python
sdk/redis/azure-mgmt-redis/tests/test_cli_mgmt_redis.py
rsdoherty/azure-sdk-for-python
6bba5326677468e6660845a703686327178bb7b1
[ "MIT" ]
2,728
2015-01-09T10:19:32.000Z
2022-03-31T14:50:33.000Z
sdk/redis/azure-mgmt-redis/tests/test_cli_mgmt_redis.py
rsdoherty/azure-sdk-for-python
6bba5326677468e6660845a703686327178bb7b1
[ "MIT" ]
17,773
2015-01-05T15:57:17.000Z
2022-03-31T23:50:25.000Z
sdk/redis/azure-mgmt-redis/tests/test_cli_mgmt_redis.py
rsdoherty/azure-sdk-for-python
6bba5326677468e6660845a703686327178bb7b1
[ "MIT" ]
1,916
2015-01-19T05:05:41.000Z
2022-03-31T19:36:44.000Z
# coding: utf-8 #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #-------------------------------------------------------------------------- # TEST SCENARIO COVERAGE # ---------------------- # Methods Total : 26 # Methods Covered : 26 # Examples Total : 26 # Examples Tested : 20 # Coverage % : 77 # ---------------------- # Current Operation Coverage: # Operations: 1/1 # Redis: 10/13 # FirewallRules: 4/4 # PatchSchedules: 4/4 # LinkedServer: 1/4 import time import unittest import azure.mgmt.redis from devtools_testutils import AzureMgmtTestCase, RandomNameResourceGroupPreparer AZURE_LOCATION = 'eastus' #------------------------------------------------------------------------------ if __name__ == '__main__': unittest.main()
44.854785
198
0.452579
# coding: utf-8 #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #-------------------------------------------------------------------------- # TEST SCENARIO COVERAGE # ---------------------- # Methods Total : 26 # Methods Covered : 26 # Examples Total : 26 # Examples Tested : 20 # Coverage % : 77 # ---------------------- # Current Operation Coverage: # Operations: 1/1 # Redis: 10/13 # FirewallRules: 4/4 # PatchSchedules: 4/4 # LinkedServer: 1/4 import time import unittest import azure.mgmt.redis from devtools_testutils import AzureMgmtTestCase, RandomNameResourceGroupPreparer AZURE_LOCATION = 'eastus' class MgmtRedisTest(AzureMgmtTestCase): def setUp(self): super(MgmtRedisTest, self).setUp() self.mgmt_client = self.create_mgmt_client( azure.mgmt.redis.RedisManagementClient ) if self.is_live: from azure.mgmt.network import NetworkManagementClient self.network_client = self.create_mgmt_client( NetworkManagementClient ) def create_virtual_network(self, group_name, location, network_name, subnet_name): azure_operation_poller = self.network_client.virtual_networks.begin_create_or_update( group_name, network_name, { 'location': location, 'address_space': { 'address_prefixes': ['10.0.0.0/16'] } }, ) result_create = azure_operation_poller.result() async_subnet_creation = self.network_client.subnets.begin_create_or_update( group_name, network_name, subnet_name, {'address_prefix': '10.0.0.0/24'} ) subnet_info = async_subnet_creation.result() return subnet_info @unittest.skip('hard to test') @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) def test_redis(self, resource_group): # UNIQUE = resource_group.name[-4:] SUBSCRIPTION_ID = self.settings.SUBSCRIPTION_ID TENANT_ID = self.settings.TENANT_ID RESOURCE_GROUP = resource_group.name NAME = "myosgkxy" VIRTUAL_NETWORK_NAME = "myVirtualNetwork" SUBNET_NAME = "mySubnet" # CACHE_NAME = "myCache" CACHE_NAME = NAME RULE_NAME = "myRule" DEFAULT = "default" LINKED_SERVER_NAME = "myLinkedServer" REDIS_NAME = "myRedis" if self.is_live: self.create_virtual_network(RESOURCE_GROUP, AZURE_LOCATION, VIRTUAL_NETWORK_NAME, SUBNET_NAME) #-------------------------------------------------------------------------- # /Redis/put/RedisCacheCreate[put] #-------------------------------------------------------------------------- BODY = { "location": AZURE_LOCATION, "zones": [ "1" ], "sku": { "name": "Premium", "family": "P", "capacity": "1" }, "enable_non_ssl_port": True, "shard_count": "2", # "replicas_per_master": "2", "redis_configuration": { "maxmemory-policy": "allkeys-lru" }, "subnet_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Network/virtualNetworks/" + VIRTUAL_NETWORK_NAME + "/subnets/" + SUBNET_NAME, "static_ip": "10.0.0.5", "minimum_tls_version": "1.2" } result = self.mgmt_client.redis.begin_create(resource_group_name=RESOURCE_GROUP, name=NAME, parameters=BODY) result = result.result() #-------------------------------------------------------------------------- # /PatchSchedules/put/RedisCachePatchSchedulesCreateOrUpdate[put] #-------------------------------------------------------------------------- BODY = { "schedule_entries": [ { "day_of_week": "Monday", "start_hour_utc": "12", "maintenance_window": "PT5H" }, { "day_of_week": "Tuesday", "start_hour_utc": "12" } ] } result = self.mgmt_client.patch_schedules.create_or_update(resource_group_name=RESOURCE_GROUP, name=NAME, default=DEFAULT, parameters=BODY) if self.is_live: time.sleep(1800) #-------------------------------------------------------------------------- # /FirewallRules/put/RedisCacheFirewallRuleCreate[put] #-------------------------------------------------------------------------- BODY = { "start_ip": "10.0.1.1", "end_ip": "10.0.1.4" } result = self.mgmt_client.firewall_rules.create_or_update(resource_group_name=RESOURCE_GROUP, cache_name=CACHE_NAME, rule_name=RULE_NAME, parameters=BODY) #-------------------------------------------------------------------------- # /LinkedServer/put/LinkedServer_Create[put] #-------------------------------------------------------------------------- BODY = { "linked_redis_cache_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Cache/Redis/" + REDIS_NAME, "linked_redis_cache_location": "West US", "server_role": "Secondary" } # result = self.mgmt_client.linked_server.begin_create(resource_group_name=RESOURCE_GROUP, name=NAME, linked_server_name=LINKED_SERVER_NAME, parameters=BODY) # result = result.result() #-------------------------------------------------------------------------- # /LinkedServer/get/LinkedServer_Get[get] #-------------------------------------------------------------------------- # result = self.mgmt_client.linked_server.get(resource_group_name=RESOURCE_GROUP, name=NAME, linked_server_name=LINKED_SERVER_NAME) #-------------------------------------------------------------------------- # /FirewallRules/get/RedisCacheFirewallRuleGet[get] #-------------------------------------------------------------------------- result = self.mgmt_client.firewall_rules.get(resource_group_name=RESOURCE_GROUP, cache_name=CACHE_NAME, rule_name=RULE_NAME) #-------------------------------------------------------------------------- # /PatchSchedules/get/RedisCachePatchSchedulesGet[get] #-------------------------------------------------------------------------- # result = self.mgmt_client.patch_schedules.get(resource_group_name=RESOURCE_GROUP, name=NAME, default=DEFAULT) #-------------------------------------------------------------------------- # /Redis/get/RedisCacheGet[get] #-------------------------------------------------------------------------- # result = self.mgmt_client.redis.list_upgrade_notifications(resource_group_name=RESOURCE_GROUP, name=NAME, history="5000") #-------------------------------------------------------------------------- # /PatchSchedules/get/RedisCachePatchSchedulesList[get] #-------------------------------------------------------------------------- result = self.mgmt_client.patch_schedules.list_by_redis_resource(resource_group_name=RESOURCE_GROUP, cache_name=CACHE_NAME) #-------------------------------------------------------------------------- # /FirewallRules/get/RedisCacheFirewallRulesList[get] #-------------------------------------------------------------------------- result = self.mgmt_client.firewall_rules.list_by_redis_resource(resource_group_name=RESOURCE_GROUP, cache_name=CACHE_NAME) #-------------------------------------------------------------------------- # /LinkedServer/get/LinkedServer_List[get] #-------------------------------------------------------------------------- result = self.mgmt_client.linked_server.list(resource_group_name=RESOURCE_GROUP, name=NAME) #-------------------------------------------------------------------------- # /Redis/get/RedisCacheGet[get] #-------------------------------------------------------------------------- result = self.mgmt_client.redis.get(resource_group_name=RESOURCE_GROUP, name=NAME) #-------------------------------------------------------------------------- # /Redis/get/RedisCacheListByResourceGroup[get] #-------------------------------------------------------------------------- result = self.mgmt_client.redis.list_by_resource_group(resource_group_name=RESOURCE_GROUP) #-------------------------------------------------------------------------- # /Redis/get/RedisCacheList[get] #-------------------------------------------------------------------------- result = self.mgmt_client.redis.list() #-------------------------------------------------------------------------- # /Operations/get/Operations_List[get] #-------------------------------------------------------------------------- result = self.mgmt_client.operations.list() #-------------------------------------------------------------------------- # /Redis/post/RedisCacheRegenerateKey[post] #-------------------------------------------------------------------------- BODY = { "key_type": "Primary" } result = self.mgmt_client.redis.regenerate_key(resource_group_name=RESOURCE_GROUP, name=NAME, parameters=BODY) #-------------------------------------------------------------------------- # /Redis/post/RedisCacheForceReboot[post] #-------------------------------------------------------------------------- BODY = { "shard_id": "0", "reboot_type": "AllNodes" } result = self.mgmt_client.redis.force_reboot(resource_group_name=RESOURCE_GROUP, name=NAME, parameters=BODY) #-------------------------------------------------------------------------- # /Redis/post/RedisCacheListKeys[post] #-------------------------------------------------------------------------- result = self.mgmt_client.redis.list_keys(resource_group_name=RESOURCE_GROUP, name=NAME) #-------------------------------------------------------------------------- # /Redis/post/RedisCacheImport[post] #-------------------------------------------------------------------------- BODY = { "format": "RDB", "files": [ "http://fileuris.contoso.com/pathtofile1" ] } # result = self.mgmt_client.redis.begin_import_data(resource_group_name=RESOURCE_GROUP, name=NAME, parameters=BODY) # result = result.result() #-------------------------------------------------------------------------- # /Redis/post/RedisCacheExport[post] #-------------------------------------------------------------------------- BODY = { "format": "RDB", "prefix": "datadump1", "container": "https://contosostorage.blob.core.window.net/urltoBlobContainer?sasKeyParameters" } # result = self.mgmt_client.redis.begin_export_data(resource_group_name=RESOURCE_GROUP, name=NAME, parameters=BODY) # result = result.result() #-------------------------------------------------------------------------- # /Redis/patch/RedisCacheUpdate[patch] #-------------------------------------------------------------------------- BODY = { "enable_non_ssl_port": True } result = self.mgmt_client.redis.update(resource_group_name=RESOURCE_GROUP, name=NAME, parameters=BODY) #-------------------------------------------------------------------------- # /Redis/post/RedisCacheList[post] #-------------------------------------------------------------------------- BODY = { "type": "Microsoft.Cache/Redis", "name": "cacheName" } result = self.mgmt_client.redis.check_name_availability(parameters=BODY) #-------------------------------------------------------------------------- # /LinkedServer/delete/LinkedServerDelete[delete] #-------------------------------------------------------------------------- # result = self.mgmt_client.linked_server.delete(resource_group_name=RESOURCE_GROUP, name=NAME, linked_server_name=LINKED_SERVER_NAME) #-------------------------------------------------------------------------- # /FirewallRules/delete/RedisCacheFirewallRuleDelete[delete] #-------------------------------------------------------------------------- result = self.mgmt_client.firewall_rules.delete(resource_group_name=RESOURCE_GROUP, cache_name=CACHE_NAME, rule_name=RULE_NAME) #-------------------------------------------------------------------------- # /PatchSchedules/delete/RedisCachePatchSchedulesDelete[delete] #-------------------------------------------------------------------------- result = self.mgmt_client.patch_schedules.delete(resource_group_name=RESOURCE_GROUP, name=NAME, default=DEFAULT) #-------------------------------------------------------------------------- # /Redis/delete/RedisCacheDelete[delete] #-------------------------------------------------------------------------- result = self.mgmt_client.redis.begin_delete(resource_group_name=RESOURCE_GROUP, name=NAME) result = result.result() #------------------------------------------------------------------------------ if __name__ == '__main__': unittest.main()
12,426
196
23
5eddc88d8268ee6a26346c3f53c14bb8f057cbc0
790
py
Python
hardhat/recipes/gmime.py
stangelandcl/hardhat
1ad0c5dec16728c0243023acb9594f435ef18f9c
[ "MIT" ]
null
null
null
hardhat/recipes/gmime.py
stangelandcl/hardhat
1ad0c5dec16728c0243023acb9594f435ef18f9c
[ "MIT" ]
null
null
null
hardhat/recipes/gmime.py
stangelandcl/hardhat
1ad0c5dec16728c0243023acb9594f435ef18f9c
[ "MIT" ]
null
null
null
from .base import GnuRecipe
37.619048
68
0.586076
from .base import GnuRecipe class GMimeRecipe(GnuRecipe): def __init__(self, *args, **kwargs): super(GMimeRecipe, self).__init__(*args, **kwargs) self.sha256 = '75ec6033f9192488ff37745792c107b3' \ 'd0ab0a36c2d3e4f732901a771755d7e0' # self.depends = ['gobject-introspection', 'vala'] self.name = 'gmime' self.version = '3.2.0' short_version = '.'.join(self.version.split('.')[:2]) self.url = 'http://ftp.gnome.org/pub/gnome/sources/gmime/' \ '%s/gmime-$version.tar.xz' % short_version self.configure_strip_cross_compile() self.configure_args += [ '--build=%s' % self.target_triplet, '--host=%s' % self.target_triplet, '--disable-vala']
704
8
49
5c58439ee9959d6f9631b302618c291c2126ccbd
6,260
py
Python
Practicas/Practica_07/codigoFuente/src/indexados.py
CodeRevenge/Proyecto-seminario-traductores-i
a5c6a500a6be8d5a1b24b4ecacd73e6f67a34041
[ "MIT" ]
null
null
null
Practicas/Practica_07/codigoFuente/src/indexados.py
CodeRevenge/Proyecto-seminario-traductores-i
a5c6a500a6be8d5a1b24b4ecacd73e6f67a34041
[ "MIT" ]
null
null
null
Practicas/Practica_07/codigoFuente/src/indexados.py
CodeRevenge/Proyecto-seminario-traductores-i
a5c6a500a6be8d5a1b24b4ecacd73e6f67a34041
[ "MIT" ]
null
null
null
from bitstring import Bits from baseconvert import base from src.funcionalidades import Funcionalidad
33.655914
136
0.503674
from bitstring import Bits from baseconvert import base from src.funcionalidades import Funcionalidad class Indexados(Funcionalidad): def __init__(self): Funcionalidad.__init__(self) self.R_X = '00' self.R_Y = '01' self.R_SP = '10' self.R_PC = '11' self.REGISTRO_A = 'A' self.REGISTRO_B = 'B' self.REGISTRO_D = 'D' self.REGISTRO_X = 'X' self.REGISTRO_Y = 'Y' self.REGISTRO_SP = 'SP' self.REGISTRO_PC = 'PC' self.IDX = 'IDX' self.IDX_1 = 'IDX1' self.IDX_2 = 'IDX2' self.MAX_5_B = 15 self.MIN_5_B = -16 self.MAX_9_B = 255 self.MIN_9_B = -256 self.MAX_16_B = 65535 self.MIN_16_B = -32768 def analizarInstruccion(self, obj, instruccion, ocurrencias): operadores = instruccion[2] codOp = ocurrencias[-1][3] if operadores[1].startswith('+') or operadores[1].startswith('-') or operadores[1].endswith('+') or operadores[1].endswith('-'): pass else: if self.verificarRegistro(obj, operadores[1]): if self.verificarRegistroAcc(obj, operadores[0]): pass else: # if obj.esLetra(operadores[0]): # pass # else: size = self.determinarTamaño(obj, operadores[0]) if size == 16: nem = [valor for indice, valor in enumerate(ocurrencias) if valor[2] == self.IDX_2] nem = nem[0] codOp = codOp + ''.zfill(int(nem[4])) posAct = obj.posicionHex() obj.sumarPosicion(len(codOp), tipo=False) return [posAct, codOp, nem, instruccion, self.IDX_2] elif size == 9: nem = [valor for indice, valor in enumerate(ocurrencias) if valor[2] == self.IDX_1] nem = nem[0] codOp = codOp + ''.zfill(int(nem[4])) posAct = obj.posicionHex() obj.sumarPosicion(len(codOp), tipo=False) return [posAct, codOp, nem, instruccion, self.IDX_1] elif size == 5: nem = [valor for indice, valor in enumerate(ocurrencias) if valor[2] == self.IDX] nem = nem[0] codOp = codOp + ''.zfill(int(nem[4])) posAct = obj.posicionHex() obj.sumarPosicion(len(codOp), tipo=False) return [posAct, codOp, nem, instruccion, self.IDX] else: return False else: print('Error: Se esperaba un nombre de registro y se recibio {}'.format(operadores[1])) def verificarRegistro(self, obj, operador): x = operador == obj.REGISTRO_X y = operador == obj.REGISTRO_Y sp = operador == obj.REGISTRO_SP pc = operador == obj.REGISTRO_PC if x or y or sp or pc: return True def verificarRegistroAcc(self, obj, operador): a = operador == obj.REGISTRO_A b = operador == obj.REGISTRO_B d = operador == obj.REGISTRO_D if a or b or d: return True def determinarTamaño(self, obj, operador): if obj.esEtiquetaInd(operador): return 16 op = self.verificarBaseFull(operador) if type(op) == str: opInt = int(self.hex2Dec(op)) else: opInt = op if opInt > self.MAX_16_B or opInt < self.MIN_16_B: print('El operador {} esta fuera de rango'.format(opInt)) return False elif opInt > self.MAX_9_B or opInt < self.MIN_9_B: return 16 elif opInt > self.MAX_5_B or opInt < self.MIN_5_B: return 9 else: return 5 def obtenerCodRegistro(self, registro): if registro == self.REGISTRO_X: return self.R_X elif registro == self.REGISTRO_Y: return self.R_Y elif registro == self.REGISTRO_SP: return self.R_SP elif registro == self.REGISTRO_PC: return self.R_PC def verificarIndexados(self, obj, instruccion): switch = { 'IDX':self.funcion01, 'IDX1':self.funcion02, 'IDX2':self.funcion02, } return switch.get(instruccion[4],self.default)(obj, instruccion) def funcion01(self, obj, instruccion): codop = instruccion[1][:2] num = int(self.verificarBaseFull(instruccion[3][2][0])) rr = self.obtenerCodRegistro(instruccion[3][2][1]) if num >= 0: n = '0' else: n = '1' nnnn = Bits(int=num, length=8).bin[4:] return codop + base(rr + '0' + n + nnnn,2,16,string=True).zfill(int(instruccion[2][4])) def funcion02(self, obj, instruccion): if instruccion[4] == self.IDX_1: codop = instruccion[1][:2] num = int(self.verificarBaseFull(instruccion[3][2][0])) rr = self.obtenerCodRegistro(instruccion[3][2][1]) z = '0' if num >= 0: s = '0' else: s = '1' offset = Bits(int=num, length=12).bin[4:] else: codop = instruccion[1][:2] a = obj.existeIdentificador(instruccion[3][2][0]) if a[0]: idNum = a[1][1] num = int(self.verificarBaseFull(idNum)) else: num = int(self.verificarBaseFull(instruccion[3][2][0])) rr = self.obtenerCodRegistro(instruccion[3][2][1]) z = '1' if num >= 0: s = '0' offset = Bits(uint=num, length=16).bin else: s = '1' offset = Bits(int=num, length=16).bin[4:] return codop + base('111' + rr + '0' + z + s + offset,2,16,string=True).zfill(int(instruccion[2][4])) def default(self): print('No existe este tipo de indexado')
5,844
10
300
f076ccc3477f3a026008f48bbcf3c7e496ea44d6
1,459
py
Python
Application.py
ReedGraff/High-Low
c8ba0339d7818e344cacf9a73a83d24dc539c2ca
[ "MIT" ]
1
2022-01-06T05:50:53.000Z
2022-01-06T05:50:53.000Z
Application.py
ReedGraff/High-Low
c8ba0339d7818e344cacf9a73a83d24dc539c2ca
[ "MIT" ]
null
null
null
Application.py
ReedGraff/High-Low
c8ba0339d7818e344cacf9a73a83d24dc539c2ca
[ "MIT" ]
null
null
null
import Bot # This is the local Python Module that we made # Initialization bot_1 = Bot.Bot("ya boi", "just got bamboozled", "Bot_1") # Find Functionality find_input = { "function_name": "One_Stock", "parameters": [ "FIS" ] } find_output = bot_1.Find(find_input) # Finance Functionality finance_input = { "function_name": "Set", "parameters": [ 10, # 10 dollars False # 10 dollars infinitely... If it was False, then it would be limited to 10 dollars ] } """ finance_input = { "function_name": "Set", "parameters": [ 10, # 10 dollars True # 10 dollars infinitely... If it was False, then it would be limited to 10 dollars ] } """ finance_output = bot_1.Finance(finance_input) # Algorithm Functionality algorithm_input = { "function_name": "Gates", "parameters": [ find_output, finance_output ] } bot_1.Algorithm(algorithm_input) """ ways for this to work: 1. import all functions in the beginning... and have the application.py file run the logic explicitely... 2. import programmatically based on name... then allow json entry to decide the parameters of the other functions... ____ find fuctions return json... finance fuctions return json... algorithm function is in a while true loop that runs depending on: - find json - finance json - any additionals parameters ... some algorithms will not need find json or finance json """
19.197368
113
0.67512
import Bot # This is the local Python Module that we made # Initialization bot_1 = Bot.Bot("ya boi", "just got bamboozled", "Bot_1") # Find Functionality find_input = { "function_name": "One_Stock", "parameters": [ "FIS" ] } find_output = bot_1.Find(find_input) # Finance Functionality finance_input = { "function_name": "Set", "parameters": [ 10, # 10 dollars False # 10 dollars infinitely... If it was False, then it would be limited to 10 dollars ] } """ finance_input = { "function_name": "Set", "parameters": [ 10, # 10 dollars True # 10 dollars infinitely... If it was False, then it would be limited to 10 dollars ] } """ finance_output = bot_1.Finance(finance_input) # Algorithm Functionality algorithm_input = { "function_name": "Gates", "parameters": [ find_output, finance_output ] } bot_1.Algorithm(algorithm_input) """ ways for this to work: 1. import all functions in the beginning... and have the application.py file run the logic explicitely... 2. import programmatically based on name... then allow json entry to decide the parameters of the other functions... ____ find fuctions return json... finance fuctions return json... algorithm function is in a while true loop that runs depending on: - find json - finance json - any additionals parameters ... some algorithms will not need find json or finance json """
0
0
0
667ea3dbd8baf0753a75fcb05bd9436ff06b3e79
118
py
Python
tests/conftest.py
jgirardet/qmlbot
37eb46b3c5c6b0886b2b64a00b71ecd609bd896b
[ "MIT" ]
null
null
null
tests/conftest.py
jgirardet/qmlbot
37eb46b3c5c6b0886b2b64a00b71ecd609bd896b
[ "MIT" ]
null
null
null
tests/conftest.py
jgirardet/qmlbot
37eb46b3c5c6b0886b2b64a00b71ecd609bd896b
[ "MIT" ]
null
null
null
from pathlib import Path import pytest @pytest.fixture
16.857143
45
0.754237
from pathlib import Path import pytest @pytest.fixture def dir_test(): return Path(__file__).parent / "dir_test"
40
0
22
0705ee39b935392e5ad1eb56149463ca5a4842d9
10,251
py
Python
nodes/visualise_with_mocapped_tag.py
wtabib/extrinsics_calibrator
b0957e45e9c1c09e60ec115c1ec94991a0b338a0
[ "BSD-3-Clause" ]
3
2020-10-10T21:19:02.000Z
2022-03-06T06:42:53.000Z
nodes/visualise_with_mocapped_tag.py
wtabib/extrinsics_calibrator
b0957e45e9c1c09e60ec115c1ec94991a0b338a0
[ "BSD-3-Clause" ]
null
null
null
nodes/visualise_with_mocapped_tag.py
wtabib/extrinsics_calibrator
b0957e45e9c1c09e60ec115c1ec94991a0b338a0
[ "BSD-3-Clause" ]
1
2019-09-05T21:39:55.000Z
2019-09-05T21:39:55.000Z
#!/usr/bin/env python2.7 import numpy as np import sys import cv2 import tf import pdb import yaml import rosbag import rospy from sensor_msgs.msg import Image from nav_msgs.msg import Odometry from message_filters import ApproximateTimeSynchronizer, Subscriber from cv_bridge import CvBridge from apriltag_tracker._AprilTagTracker import AprilTagTracker from apriltag_tracker.msg import Apriltags from geometry import SE3, se3 datatype = np.float32 np.set_printoptions(precision=4, suppress=True) config_file = '../config/extrinsics_calib.yaml' with open(config_file, 'r') as f: file_node = yaml.load(f) node = file_node['apriltag_tracker_params'] tag_size = node['tag_size'] s = tag_size/2.0 K = np.array(node['K']).reshape(3, 3) path = file_node['extrinsics_calib_params']['bag_file'] tracker = AprilTagTracker(config_file) rospy.init_node('broadcaster') bridge = CvBridge() broadcaster = tf.TransformBroadcaster() img_pub = rospy.Publisher('debug_img', Image) data_tuples = [] use_bag = True visualize = True buffer_size = 100 topics_to_parse = ['/kinect2/qhd/image_color_rect', '/kinect_one/vicon_odom', '/apriltag_27_board/vicon_odom'] subs = [] subs.append(Subscriber(topics_to_parse[0], Image)) subs.append(Subscriber(topics_to_parse[1], Odometry)) subs.append(Subscriber(topics_to_parse[2], Odometry)) synchronizer = ApproximateTimeSynchronizer(subs, 10, 0.05) synchronizer.registerCallback(got_tuple) if use_bag: with rosbag.Bag(path, 'r') as bag: counter = 0 for topic, msg, t in bag.read_messages(topics_to_parse): if topic in topics_to_parse: index = topics_to_parse.index(topic) subs[index].signalMessage(msg) counter += 1 if counter%1000 == 0: print 'Read {0} tuples'.format(counter) # Try to use a black box optimizer print 'Starting optimization...' from scipy.optimize import minimize initial_guess = np.array([0,0,0,0,0,0,-0.1]) # Since initial guess is pretty close to unity result = minimize(cost_function_tuple_offset, initial_guess, bounds=np.array([[-1,1],[-1,1],[-1,1],[-1,1],[-1,1],[-1,1], [-1, 1]])) print 'Done, results is' print result print SE3.group_from_algebra(se3.algebra_from_vector(result.x[:6])) print result.x[6] pdb.set_trace() else: rospy.Subscriber(topics_to_parse[0], Image, lambda msg: subs[0].signalMessage(msg)) rospy.Subscriber(topics_to_parse[1], Odometry, lambda msg: subs[1].signalMessage(msg)) rospy.Subscriber(topics_to_parse[2], Odometry, lambda msg: subs[2].signalMessage(msg)) rospy.spin()
40.517787
135
0.581504
#!/usr/bin/env python2.7 import numpy as np import sys import cv2 import tf import pdb import yaml import rosbag import rospy from sensor_msgs.msg import Image from nav_msgs.msg import Odometry from message_filters import ApproximateTimeSynchronizer, Subscriber from cv_bridge import CvBridge from apriltag_tracker._AprilTagTracker import AprilTagTracker from apriltag_tracker.msg import Apriltags from geometry import SE3, se3 datatype = np.float32 np.set_printoptions(precision=4, suppress=True) config_file = '../config/extrinsics_calib.yaml' with open(config_file, 'r') as f: file_node = yaml.load(f) node = file_node['apriltag_tracker_params'] tag_size = node['tag_size'] s = tag_size/2.0 K = np.array(node['K']).reshape(3, 3) path = file_node['extrinsics_calib_params']['bag_file'] tracker = AprilTagTracker(config_file) rospy.init_node('broadcaster') bridge = CvBridge() broadcaster = tf.TransformBroadcaster() img_pub = rospy.Publisher('debug_img', Image) data_tuples = [] use_bag = True visualize = True def transform_matrix_from_odom(msg): translation = np.array( [msg.pose.pose.position.x, msg.pose.pose.position.y, msg.pose.pose.position.z]) quaternion = np.array([msg.pose.pose.orientation.x, msg.pose.pose.orientation.y, msg.pose.pose.orientation.z, msg.pose.pose.orientation.w]) # translation = np.array([msg.transform.translation.x, msg.transform.translation.y, msg.transform.translation.z]) # quaternion = np.array([msg.transform.rotation.x, msg.transform.rotation.y, msg.transform.rotation.z, msg.transform.rotation.w]) T = tf.transformations.quaternion_matrix(quaternion) T[:3, 3] = translation return T def cost_function( cam_to_body_log): cam_to_body = SE3.group_from_algebra(se3.algebra_from_vector(cam_to_body_log)) error = 0 for measurement, body_to_world, board_to_world in data_tuples: cam_to_world = np.dot(body_to_world, cam_to_body) tag_pts = np.array([[-s, -s, 0, 1], [s, -s, 0, 1], [s, s, 0, 1], [-s, s, 0, 1]]).transpose() tag_in_board = np.array( [[0, -1, 0, s], [1, 0, 0, s], [0, 0, 1, 0], [0, 0, 0, 1]]) tag_pts_in_world = np.dot( board_to_world, np.dot(tag_in_board, tag_pts)) tag_pts_in_cam = np.dot(np.linalg.inv(cam_to_world), tag_pts_in_world) projections = np.dot(K, tag_pts_in_cam[:3, :]) projections /= projections[2] projections = projections[:2].transpose() error += np.linalg.norm(measurement - projections) return error buffer_size = 100 def cost_function_tuple_offset( params): cam_to_body = SE3.group_from_algebra(se3.algebra_from_vector(params[:6])) tuple_offset = int(params[6]*100) # Use a central region of data tuples +- 100 # The offset determines the start of the measurement offset # pdb.set_trace() # measurements_offset = data_tuples[buffer_size + tuple_offset: -buffer_size + tuple_offset, 0] # bodys_to_world_tuple_offset = data_tuples[buffer_size:-buffer_size, 1] # boards_to_world_tuple_offset = data_tuples[buffer_size:-buffer_size, 2] # offset_tuples = np.concatenate(measurements_offset, bodys_to_world_offset, boards_to_world_offset, axis=1) error = 0 for i in range(len(data_tuples) - buffer_size*2): measurement = data_tuples[i + buffer_size + tuple_offset][0] body_to_world = data_tuples[i + buffer_size][1] board_to_world = data_tuples[i + buffer_size][2] cam_to_world = np.dot(body_to_world, cam_to_body) tag_pts = np.array([[-s, -s, 0, 1], [s, -s, 0, 1], [s, s, 0, 1], [-s, s, 0, 1]]).transpose() tag_in_board = np.array( [[0, -1, 0, s], [1, 0, 0, s], [0, 0, 1, 0], [0, 0, 0, 1]]) tag_pts_in_world = np.dot( board_to_world, np.dot(tag_in_board, tag_pts)) tag_pts_in_cam = np.dot(np.linalg.inv(cam_to_world), tag_pts_in_world) projections = np.dot(K, tag_pts_in_cam[:3, :]) projections /= projections[2] projections = projections[:2].transpose() error += np.linalg.norm(measurement - projections) return error def got_tuple(img_msg, cam_odom, board_odom): img = bridge.imgmsg_to_cv2(img_msg, "bgr8") img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) body_to_world = transform_matrix_from_odom(cam_odom) board_to_world = transform_matrix_from_odom(board_odom) # Get detection from tracker pixels = [] debug_img = bridge.imgmsg_to_cv2(img_msg, "bgr8") pixels = tracker.detect_tag(img, debug_img) pixels = np.array(pixels) if pixels.shape[0] > 0: pixels = pixels.reshape(4, 2) data_tuples.append([pixels, body_to_world, board_to_world]) # Get detection from tracker if visualize: tag_in_cam = np.eye(4).astype(datatype) if tracker.track(img, tag_in_cam): # cam_to_body = np.array([[0.998634, -0.0329651, -0.0405292, 0.013017],#0.001775], # [0.0332441, 0.999428, 0.00622975, 0.00547],#0.0235], # [0.0403007, -0.00756861, 0.999159, -0.0230],#-0.034787], # [0, 0, 0, 1]]) cam_to_body = np.load('cam_in_body.npy') cam_to_world = np.dot(body_to_world, cam_to_body) tag_in_world = np.dot(cam_to_world, tag_in_cam) board_in_cam = np.dot(np.linalg.inv(cam_to_world), board_to_world) tag_in_board = np.array( [[0, -1, 0, s], [1, 0, 0, s], [0, 0, 1, 0], [0, 0, 0, 1]]) # print 'tag_in_cam:: ' # print tag_in_cam # print 'board_in_cam:: ' # print board_in_cam # print 'tag_in_world:: ' # print tag_in_world # print 'board_in_world:: ' # print board_to_world broadcaster.sendTransform(body_to_world[:3, 3], tf.transformations.quaternion_from_matrix( body_to_world), rospy.Time.now(), 'body', "world") broadcaster.sendTransform(board_to_world[:3, 3], tf.transformations.quaternion_from_matrix( board_to_world), rospy.Time.now(), 'board', "world") broadcaster.sendTransform(cam_to_body[:3, 3], tf.transformations.quaternion_from_matrix( cam_to_body), rospy.Time.now(), 'cam', "body") broadcaster.sendTransform(tag_in_cam[:3, 3], tf.transformations.quaternion_from_matrix( tag_in_cam), rospy.Time.now(), 'tag', "cam") broadcaster.sendTransform(tag_in_board[:3, 3], tf.transformations.quaternion_from_matrix( tag_in_board), rospy.Time.now(), 'tag_gt', "board") # Now see if the 3D points projected make sense. tag_pts = np.array([[-s, -s, 0, 1], [s, -s, 0, 1], [s, s, 0, 1], [-s, s, 0, 1]]).transpose() tag_pts_in_world = np.dot( board_to_world, np.dot(tag_in_board, tag_pts)) tag_pts_in_cam = np.dot(np.linalg.inv(cam_to_world), tag_pts_in_world) projections = np.dot(K, tag_pts_in_cam[:3, :]) projections /= projections[2] projections = projections[:2].transpose() pixels = [] debug_img = bridge.imgmsg_to_cv2(img_msg, "bgr8") pixels = tracker.detect_tag(img, debug_img) pixels = np.array(pixels).reshape(4, 2) # Draw these pixels cv2.polylines(debug_img, np.int32([projections]), 1, (0, 255, 0), 3) img_pub.publish(bridge.cv2_to_imgmsg(debug_img)) # pdb.set_trace() topics_to_parse = ['/kinect2/qhd/image_color_rect', '/kinect_one/vicon_odom', '/apriltag_27_board/vicon_odom'] subs = [] subs.append(Subscriber(topics_to_parse[0], Image)) subs.append(Subscriber(topics_to_parse[1], Odometry)) subs.append(Subscriber(topics_to_parse[2], Odometry)) synchronizer = ApproximateTimeSynchronizer(subs, 10, 0.05) synchronizer.registerCallback(got_tuple) if use_bag: with rosbag.Bag(path, 'r') as bag: counter = 0 for topic, msg, t in bag.read_messages(topics_to_parse): if topic in topics_to_parse: index = topics_to_parse.index(topic) subs[index].signalMessage(msg) counter += 1 if counter%1000 == 0: print 'Read {0} tuples'.format(counter) # Try to use a black box optimizer print 'Starting optimization...' from scipy.optimize import minimize initial_guess = np.array([0,0,0,0,0,0,-0.1]) # Since initial guess is pretty close to unity result = minimize(cost_function_tuple_offset, initial_guess, bounds=np.array([[-1,1],[-1,1],[-1,1],[-1,1],[-1,1],[-1,1], [-1, 1]])) print 'Done, results is' print result print SE3.group_from_algebra(se3.algebra_from_vector(result.x[:6])) print result.x[6] pdb.set_trace() else: rospy.Subscriber(topics_to_parse[0], Image, lambda msg: subs[0].signalMessage(msg)) rospy.Subscriber(topics_to_parse[1], Odometry, lambda msg: subs[1].signalMessage(msg)) rospy.Subscriber(topics_to_parse[2], Odometry, lambda msg: subs[2].signalMessage(msg)) rospy.spin()
7,414
0
92
ca3f25ac2cef6d613b36315d25c655d910c24d48
2,969
py
Python
cloudscale/__init__.py
resmo/python-cloudscale
e194e3f74c4df549e59781861d4a0a1e1abf62fc
[ "MIT" ]
6
2019-11-21T15:08:58.000Z
2019-12-18T07:46:01.000Z
cloudscale/__init__.py
resmo/python-cloudscale
e194e3f74c4df549e59781861d4a0a1e1abf62fc
[ "MIT" ]
15
2019-11-26T19:48:12.000Z
2020-05-01T14:52:07.000Z
cloudscale/__init__.py
resmo/python-cloudscale
e194e3f74c4df549e59781861d4a0a1e1abf62fc
[ "MIT" ]
null
null
null
import os import configparser from .client import RestAPI from .lib.server import Server from .lib.server_group import ServerGroup from .lib.volume import Volume from .lib.flavor import Flavor from .lib.floating_ip import FloatingIp from .lib.image import Image from .lib.region import Region from .lib.network import Network from .lib.subnet import Subnet from .lib.objects_user import ObjectsUser from .error import CloudscaleException, CloudscaleApiException # noqa F401 from .version import __version__ APP_NAME = 'cloudscale-cli' CLOUDSCALE_API_ENDPOINT = 'https://api.cloudscale.ch/v1' CLOUDSCALE_CONFIG = 'cloudscale.ini'
29.989899
124
0.617043
import os import configparser from .client import RestAPI from .lib.server import Server from .lib.server_group import ServerGroup from .lib.volume import Volume from .lib.flavor import Flavor from .lib.floating_ip import FloatingIp from .lib.image import Image from .lib.region import Region from .lib.network import Network from .lib.subnet import Subnet from .lib.objects_user import ObjectsUser from .error import CloudscaleException, CloudscaleApiException # noqa F401 from .version import __version__ APP_NAME = 'cloudscale-cli' CLOUDSCALE_API_ENDPOINT = 'https://api.cloudscale.ch/v1' CLOUDSCALE_CONFIG = 'cloudscale.ini' class Cloudscale: def __init__(self, api_token=None, profile=None, verbose=False): if api_token and profile: raise CloudscaleException("API token and profile are mutually exclusive") # Read ini configs self.config = self._read_from_configfile(profile=profile) if api_token: self.api_token = api_token else: self.api_token = self.config.get('api_token') # Configre requests timeout self.timeout = self.config.get('timeout', 60) if not self.api_token: raise CloudscaleException("Missing API key: see -h for help") self.verbose = verbose self.service_classes = { 'server': Server, 'server_group': ServerGroup, 'volume': Volume, 'flavor': Flavor, 'floating_ip': FloatingIp, 'image': Image, 'region': Region, 'network': Network, 'subnet': Subnet, 'objects_user': ObjectsUser, } def _read_from_configfile(self, profile=None): config_file = os.getenv('CLOUDSCALE_CONFIG', CLOUDSCALE_CONFIG) paths = ( os.path.join(os.path.expanduser('~'), '.{}'.format(config_file)), os.path.join(os.getcwd(), config_file), ) conf = configparser.ConfigParser() conf.read(paths) if profile: if profile not in conf._sections: raise CloudscaleException("Profile '{}' not found in config files: ({})".format(profile, ', '. join(paths))) else: profile = os.getenv('CLOUDSCALE_PROFILE', 'default') if not conf._sections.get(profile): return dict() return dict(conf.items(profile)) def __getattr__(self, name): try: client = RestAPI( api_token=self.api_token, endpoint=CLOUDSCALE_API_ENDPOINT, user_agent="python-cloudscale {}".format(__version__), timeout=self.timeout, ) obj = self.service_classes[name]() obj._client = client obj.verbose = self.verbose return obj except KeyError as e: msg = "{} not implemented".format(e) raise NotImplementedError(msg)
2,234
-4
104
8a1860b58ec96d9c88266a6269a225c2b2a8da79
3,458
py
Python
zulip_bots/zulip_bots/bots/google_translate/test_google_translate.py
iishiishii/python-zulip-api
8500a3238739a080e1809e204c54685437631457
[ "Apache-2.0" ]
null
null
null
zulip_bots/zulip_bots/bots/google_translate/test_google_translate.py
iishiishii/python-zulip-api
8500a3238739a080e1809e204c54685437631457
[ "Apache-2.0" ]
null
null
null
zulip_bots/zulip_bots/bots/google_translate/test_google_translate.py
iishiishii/python-zulip-api
8500a3238739a080e1809e204c54685437631457
[ "Apache-2.0" ]
null
null
null
from unittest.mock import patch from requests.exceptions import ConnectionError from zulip_bots.test_lib import BotTestCase, DefaultTests, StubBotHandler from zulip_bots.bots.google_translate.google_translate import TranslateError help_text = ''' Google translate bot Please format your message like: `@-mention "<text_to_translate>" <target-language> <source-language(optional)>` Visit [here](https://cloud.google.com/translate/docs/languages) for all languages '''
41.662651
95
0.637363
from unittest.mock import patch from requests.exceptions import ConnectionError from zulip_bots.test_lib import BotTestCase, DefaultTests, StubBotHandler from zulip_bots.bots.google_translate.google_translate import TranslateError help_text = ''' Google translate bot Please format your message like: `@-mention "<text_to_translate>" <target-language> <source-language(optional)>` Visit [here](https://cloud.google.com/translate/docs/languages) for all languages ''' class TestGoogleTranslateBot(BotTestCase, DefaultTests): bot_name = "google_translate" def _test(self, message, response, http_config_fixture, http_fixture=None): with self.mock_config_info({'key': 'abcdefg'}), \ self.mock_http_conversation(http_config_fixture): if http_fixture: with self.mock_http_conversation(http_fixture): self.verify_reply(message, response) else: self.verify_reply(message, response) def test_normal(self): self._test('"hello" de', 'Hallo (from Foo Test User)', 'test_languages', 'test_normal') def test_source_language_not_found(self): self._test('"hello" german foo', ('Source language not found. Visit [here]' '(https://cloud.google.com/translate/docs/languages) for all languages'), 'test_languages') def test_target_language_not_found(self): self._test('"hello" bar english', ('Target language not found. Visit [here]' '(https://cloud.google.com/translate/docs/languages) for all languages'), 'test_languages') def test_403(self): self._test('"hello" german english', 'Translate Error. Invalid API Key..', 'test_languages', 'test_403') # Override default function in BotTestCase def test_bot_responds_to_empty_message(self): self._test('', help_text, 'test_languages') def test_help_command(self): self._test('help', help_text, 'test_languages') def test_help_too_many_args(self): self._test('"hello" de english foo bar', help_text, 'test_languages') def test_help_no_langs(self): self._test('"hello"', help_text, 'test_languages') def test_quotation_in_text(self): self._test('"this has "quotation" marks in" english', 'this has "quotation" marks in (from Foo Test User)', 'test_languages', 'test_quotation') def test_exception(self): with patch('zulip_bots.bots.google_translate.google_translate.translate', side_effect=Exception): self._test('"hello" de', 'Error. .', 'test_languages') def test_invalid_api_key(self): with self.assertRaises(StubBotHandler.BotQuitException): self._test(None, None, 'test_invalid_api_key') def test_api_access_not_configured(self): with self.assertRaises(StubBotHandler.BotQuitException): self._test(None, None, 'test_api_access_not_configured') def test_connection_error(self): with patch('requests.post', side_effect=ConnectionError()), \ patch('logging.warning'): self._test('"test" en', 'Could not connect to Google Translate. .', 'test_languages')
2,472
494
23
6179c834456ca775447618cab2027627c767201c
273
py
Python
Model/opportunity.py
AIESECMX/ESPO_EXPA_CRM
c9c6d96b523380be0f7df2a02605d744ff3b681b
[ "MIT" ]
null
null
null
Model/opportunity.py
AIESECMX/ESPO_EXPA_CRM
c9c6d96b523380be0f7df2a02605d744ff3b681b
[ "MIT" ]
null
null
null
Model/opportunity.py
AIESECMX/ESPO_EXPA_CRM
c9c6d96b523380be0f7df2a02605d744ff3b681b
[ "MIT" ]
null
null
null
class Opp(object): """docstring for MC"""
24.818182
74
0.681319
class Opp(object): """docstring for MC""" def __init__(self, name, expa_id=0,espo_id=0, lc_id = 0, enabler_id = 0): super(Opp, self).__init__() self.name = name self.expa_id = expa_id self.espo_id = espo_id self.lc_id = lc_id self.enabler_id = enabler_id
203
0
23
be93709076b8fd49f51637fdf96cf29c49322281
2,219
py
Python
etl/etl.py
Ayazdi/MNIST_ANN
1419edcee275503030b418f0a64e094edffaa1b0
[ "MIT" ]
8
2020-05-21T18:57:57.000Z
2021-05-18T22:27:52.000Z
etl/etl.py
Ayazdi/MNIST_ANN
1419edcee275503030b418f0a64e094edffaa1b0
[ "MIT" ]
5
2020-05-18T13:56:12.000Z
2020-05-18T15:31:33.000Z
etl/etl.py
Ayazdi/MNIST_ANN
1419edcee275503030b418f0a64e094edffaa1b0
[ "MIT" ]
1
2020-08-16T16:09:16.000Z
2020-08-16T16:09:16.000Z
import pandas as pd from sqlalchemy import create_engine, exc from load_transform import extract_from_mongodb, extract_data_from_json from bert_model import load_bert_model, sentiment_prediction from logo_detection_model import logo_detection import time import logging from config import POSTGRES, TAG # Postgres connection PG = create_engine(POSTGRES) # Remove duplicates in Postgres QUERY = f""" DELETE FROM {TAG} T1 USING {TAG} T2 WHERE T1.ctid < T2.ctid AND T1.date_time = T2.date_time; """ def sentiment_analysis_on_scraped_data(df): """ Analyse the sentiment of the cleaned caption in the dataframe using the BERT sentiment analysis model and fill the sentiment column with the results. return: dataframe with sentiment analysis of the posts """ df_analyse = df[(df['language'] == 'en') & (df['clean_text_en'] != None)] # Only the English captions df_analyse['sentiment'] = df_analyse['clean_text_en'].apply(sentiment_prediction) df['sentiment'][df_analyse.index] = df_analyse['sentiment'] return df if __name__ == '__main__': while True: # Extract posts = extract_from_mongodb() if posts: total_post = len(posts['items']) + len(posts['ranked_items']) logging.critical(f"{total_post} posts have been extracted from mongodb") # Transform df = extract_data_from_json(posts) logging.critical("Sentiment analysis on the clean text has been started") df_analized = sentiment_analysis_on_scraped_data(df) logging.critical("Sentiment analysis is finished") logging.critical("Logo detection on the images has been started") df_analized['logos'] = df_analized['urls'].apply(logo_detection) logging.critical("Logo detection is finished") # Load logging.critical("Uploading data to AWS database") df_analized.to_sql(f'{TAG}', PG, if_exists='append') PG.execute(QUERY) # removing the duplicates logging.critical("Waiting for 10 minutes...") time.sleep(600)
38.929825
107
0.658855
import pandas as pd from sqlalchemy import create_engine, exc from load_transform import extract_from_mongodb, extract_data_from_json from bert_model import load_bert_model, sentiment_prediction from logo_detection_model import logo_detection import time import logging from config import POSTGRES, TAG # Postgres connection PG = create_engine(POSTGRES) # Remove duplicates in Postgres QUERY = f""" DELETE FROM {TAG} T1 USING {TAG} T2 WHERE T1.ctid < T2.ctid AND T1.date_time = T2.date_time; """ def sentiment_analysis_on_scraped_data(df): """ Analyse the sentiment of the cleaned caption in the dataframe using the BERT sentiment analysis model and fill the sentiment column with the results. return: dataframe with sentiment analysis of the posts """ df_analyse = df[(df['language'] == 'en') & (df['clean_text_en'] != None)] # Only the English captions df_analyse['sentiment'] = df_analyse['clean_text_en'].apply(sentiment_prediction) df['sentiment'][df_analyse.index] = df_analyse['sentiment'] return df if __name__ == '__main__': while True: # Extract posts = extract_from_mongodb() if posts: total_post = len(posts['items']) + len(posts['ranked_items']) logging.critical(f"{total_post} posts have been extracted from mongodb") # Transform df = extract_data_from_json(posts) logging.critical("Sentiment analysis on the clean text has been started") df_analized = sentiment_analysis_on_scraped_data(df) logging.critical("Sentiment analysis is finished") logging.critical("Logo detection on the images has been started") df_analized['logos'] = df_analized['urls'].apply(logo_detection) logging.critical("Logo detection is finished") # Load logging.critical("Uploading data to AWS database") df_analized.to_sql(f'{TAG}', PG, if_exists='append') PG.execute(QUERY) # removing the duplicates logging.critical("Waiting for 10 minutes...") time.sleep(600)
0
0
0
885c681e43f4eeb9bf3d35d5cbd928330055e951
3,110
py
Python
selenium_tests/CanonizerHelpPage.py
the-canonizer/MEAN_System
59bc6001cdb1346a1114aefec4178a464fc6e22c
[ "MIT" ]
null
null
null
selenium_tests/CanonizerHelpPage.py
the-canonizer/MEAN_System
59bc6001cdb1346a1114aefec4178a464fc6e22c
[ "MIT" ]
null
null
null
selenium_tests/CanonizerHelpPage.py
the-canonizer/MEAN_System
59bc6001cdb1346a1114aefec4178a464fc6e22c
[ "MIT" ]
null
null
null
from CanonizerBase import Page from Identifiers import HelpIdentifiers
36.588235
96
0.700643
from CanonizerBase import Page from Identifiers import HelpIdentifiers class CanonizerHelpPage(Page): def check_what_is_canonizer_help_page_loaded(self): """ This function verifies if the canonizer help page loads properly. :return: """ title = self.find_element(*HelpIdentifiers.TITTLE).text if title == 'Canonizer Main Page': self.hover(*HelpIdentifiers.HELP) self.find_element(*HelpIdentifiers.HELP).click() heading = self.find_element(*HelpIdentifiers.TITTLE_HELP).text if heading == 'Help': return CanonizerHelpPage(self.driver) def check_Steps_to_Create_a_New_Topic_page_loaded(self): """ This function verifies if the canonizer help page loads properly. :return: """ self.hover(*HelpIdentifiers.STEPS_TO_CREATE_A_NEW_TOPIC) self.find_element(*HelpIdentifiers.STEPS_TO_CREATE_A_NEW_TOPIC).click() return CanonizerHelpPage(self.driver) def check_Dealing_With_Disagreements_page_loaded(self): """ This function verifies if the canonizer help page loads properly. :return: """ self.hover(*HelpIdentifiers.DEALING_WITH_DISAGREEMENTS) self.find_element(*HelpIdentifiers.DEALING_WITH_DISAGREEMENTS).click() return CanonizerHelpPage(self.driver) def check_Wiki_Markup_Information_page_loaded(self): """ This function verifies if the canonizer help page loads properly. :return: """ self.hover(*HelpIdentifiers.WIKI_MARKUP_INFORMATION) self.find_element(*HelpIdentifiers.WIKI_MARKUP_INFORMATION).click() return CanonizerHelpPage(self.driver) def check_Adding_the_Canonizer_Feedback_Camp_Outline_to_Internet_Articles_page_loaded(self): """ This function verifies if the canonizer help page loads properly. :return: """ self.hover(*HelpIdentifiers.ADDING_CANO_FEEDBACK) self.find_element(*HelpIdentifiers.ADDING_CANO_FEEDBACK).click() return CanonizerHelpPage(self.driver) def check_Canonizer_is_the_final_word_on_everything_page_loaded(self): """ This function verifies if the canonizer help page loads properly. :return: """ self.hover(*HelpIdentifiers.CANONIZER_IS_THE_FINAL_WORD_ON_EVERYTHING) self.find_element(*HelpIdentifiers.CANONIZER_IS_THE_FINAL_WORD_ON_EVERYTHING).click() return CanonizerHelpPage(self.driver) def check_consensus_out_of_controversy_use_case_page_loaded(self): """ This function verifies if the canonizer help page loads properly. :return: """ self.hover(*HelpIdentifiers.CONSENSUS_OUT_OF_CONTROVERSY_USE_CASE) self.find_element(*HelpIdentifiers.CONSENSUS_OUT_OF_CONTROVERSY_USE_CASE).click() sub_heading = self.find_element(*HelpIdentifiers.SUB_HEADING).text print(sub_heading, "heading") if sub_heading == 'Camp Statement': return CanonizerHelpPage(self.driver)
0
3,012
23
683ca57b14bb5cb2c8ec809d20ecf08151387bef
478
py
Python
feewaiver/migrations/0037_park_entrance_fee.py
dbca-wa/feewaiver
7938a0e9d18924c12b27c0a411b6d7eccb40166b
[ "Apache-2.0" ]
null
null
null
feewaiver/migrations/0037_park_entrance_fee.py
dbca-wa/feewaiver
7938a0e9d18924c12b27c0a411b6d7eccb40166b
[ "Apache-2.0" ]
12
2021-02-24T02:33:01.000Z
2022-01-25T02:37:39.000Z
feewaiver/migrations/0037_park_entrance_fee.py
mintcoding/feewaiver
47d69db91386f760dd36d87cbb565a9bb72a27d5
[ "Apache-2.0" ]
1
2021-01-08T02:15:27.000Z
2021-01-08T02:15:27.000Z
# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2021-01-05 02:27 from __future__ import unicode_literals from django.db import migrations, models
22.761905
68
0.638075
# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2021-01-05 02:27 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('feewaiver', '0036_feewaivervisit_number_of_participants'), ] operations = [ migrations.AddField( model_name='park', name='entrance_fee', field=models.BooleanField(default=False), ), ]
0
298
23
c332a7841140f2f68889e6ccef881d02c241cce1
14,689
py
Python
doc8/tests/test_main.py
dependent-type/doc8
4b57d2e438021e1785ada9c3723d18a52dd0fff7
[ "Apache-2.0" ]
1
2019-07-12T10:49:29.000Z
2019-07-12T10:49:29.000Z
doc8/tests/test_main.py
dependent-type/doc8
4b57d2e438021e1785ada9c3723d18a52dd0fff7
[ "Apache-2.0" ]
2
2019-07-12T11:02:18.000Z
2020-02-07T15:25:52.000Z
doc8/tests/test_main.py
dependent-type/doc8
4b57d2e438021e1785ada9c3723d18a52dd0fff7
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- from mock import patch, MagicMock import os import six import shutil import sys import testtools from doc8.main import main, doc8 # Location to create test files TMPFS_DIR_NAME = ".tmp" # Expected output OUTPUT_CMD_NO_QUIET = """\ Scanning... Validating... {path}/invalid.rst:1: D002 Trailing whitespace {path}/invalid.rst:1: D005 No newline at end of file ======== Total files scanned = 1 Total files ignored = 0 Total accumulated errors = 2 Detailed error counts: - doc8.checks.CheckCarriageReturn = 0 - doc8.checks.CheckIndentationNoTab = 0 - doc8.checks.CheckMaxLineLength = 0 - doc8.checks.CheckNewlineEndOfFile = 1 - doc8.checks.CheckTrailingWhitespace = 1 - doc8.checks.CheckValidity = 0 """ OUTPUT_CMD_QUIET = """\ {path}/invalid.rst:1: D002 Trailing whitespace {path}/invalid.rst:1: D005 No newline at end of file """ OUTPUT_CMD_VERBOSE = """\ Scanning... Selecting '{path}/invalid.rst' Validating... Validating {path}/invalid.rst (ascii, 10 chars, 1 lines) Running check 'doc8.checks.CheckValidity' Running check 'doc8.checks.CheckTrailingWhitespace' - {path}/invalid.rst:1: D002 Trailing whitespace Running check 'doc8.checks.CheckIndentationNoTab' Running check 'doc8.checks.CheckCarriageReturn' Running check 'doc8.checks.CheckMaxLineLength' Running check 'doc8.checks.CheckNewlineEndOfFile' - {path}/invalid.rst:1: D005 No newline at end of file ======== Total files scanned = 1 Total files ignored = 0 Total accumulated errors = 2 Detailed error counts: - doc8.checks.CheckCarriageReturn = 0 - doc8.checks.CheckIndentationNoTab = 0 - doc8.checks.CheckMaxLineLength = 0 - doc8.checks.CheckNewlineEndOfFile = 1 - doc8.checks.CheckTrailingWhitespace = 1 - doc8.checks.CheckValidity = 0 """ OUTPUT_API_REPORT = """\ {path}/invalid.rst:1: D002 Trailing whitespace {path}/invalid.rst:1: D005 No newline at end of file ======== Total files scanned = 1 Total files ignored = 0 Total accumulated errors = 2 Detailed error counts: - doc8.checks.CheckCarriageReturn = 0 - doc8.checks.CheckIndentationNoTab = 0 - doc8.checks.CheckMaxLineLength = 0 - doc8.checks.CheckNewlineEndOfFile = 1 - doc8.checks.CheckTrailingWhitespace = 1 - doc8.checks.CheckValidity = 0""" class Capture(object): """ Context manager to capture output on stdout and stderr """ class TmpFs(object): """ Context manager to create and clean a temporary file area for testing """ def mock(self): """ Create a file which fails on a LineCheck and a ContentCheck """ self.create_file("invalid.rst", "D002 D005 ") def expected(self, template): """ Insert the path into a template to generate an expected test value """ return template.format(path=self.path) class FakeResult(object): """ Minimum valid result returned from doc8 """ total_errors = 0 class TestCommandLine(testtools.TestCase): """ Test command line invocation """ class TestApi(testtools.TestCase): """ Test direct code invocation """ class TestArguments(testtools.TestCase): """ Test that arguments are parsed correctly """
34.240093
88
0.579345
# -*- coding: utf-8 -*- from mock import patch, MagicMock import os import six import shutil import sys import testtools from doc8.main import main, doc8 # Location to create test files TMPFS_DIR_NAME = ".tmp" # Expected output OUTPUT_CMD_NO_QUIET = """\ Scanning... Validating... {path}/invalid.rst:1: D002 Trailing whitespace {path}/invalid.rst:1: D005 No newline at end of file ======== Total files scanned = 1 Total files ignored = 0 Total accumulated errors = 2 Detailed error counts: - doc8.checks.CheckCarriageReturn = 0 - doc8.checks.CheckIndentationNoTab = 0 - doc8.checks.CheckMaxLineLength = 0 - doc8.checks.CheckNewlineEndOfFile = 1 - doc8.checks.CheckTrailingWhitespace = 1 - doc8.checks.CheckValidity = 0 """ OUTPUT_CMD_QUIET = """\ {path}/invalid.rst:1: D002 Trailing whitespace {path}/invalid.rst:1: D005 No newline at end of file """ OUTPUT_CMD_VERBOSE = """\ Scanning... Selecting '{path}/invalid.rst' Validating... Validating {path}/invalid.rst (ascii, 10 chars, 1 lines) Running check 'doc8.checks.CheckValidity' Running check 'doc8.checks.CheckTrailingWhitespace' - {path}/invalid.rst:1: D002 Trailing whitespace Running check 'doc8.checks.CheckIndentationNoTab' Running check 'doc8.checks.CheckCarriageReturn' Running check 'doc8.checks.CheckMaxLineLength' Running check 'doc8.checks.CheckNewlineEndOfFile' - {path}/invalid.rst:1: D005 No newline at end of file ======== Total files scanned = 1 Total files ignored = 0 Total accumulated errors = 2 Detailed error counts: - doc8.checks.CheckCarriageReturn = 0 - doc8.checks.CheckIndentationNoTab = 0 - doc8.checks.CheckMaxLineLength = 0 - doc8.checks.CheckNewlineEndOfFile = 1 - doc8.checks.CheckTrailingWhitespace = 1 - doc8.checks.CheckValidity = 0 """ OUTPUT_API_REPORT = """\ {path}/invalid.rst:1: D002 Trailing whitespace {path}/invalid.rst:1: D005 No newline at end of file ======== Total files scanned = 1 Total files ignored = 0 Total accumulated errors = 2 Detailed error counts: - doc8.checks.CheckCarriageReturn = 0 - doc8.checks.CheckIndentationNoTab = 0 - doc8.checks.CheckMaxLineLength = 0 - doc8.checks.CheckNewlineEndOfFile = 1 - doc8.checks.CheckTrailingWhitespace = 1 - doc8.checks.CheckValidity = 0""" class Capture(object): """ Context manager to capture output on stdout and stderr """ def __enter__(self): self.old_out = sys.stdout self.old_err = sys.stderr self.out = six.StringIO() self.err = six.StringIO() sys.stdout = self.out sys.stderr = self.err return self.out, self.err def __exit__(self, *args): sys.stdout = self.out sys.stderr = self.err class TmpFs(object): """ Context manager to create and clean a temporary file area for testing """ def __enter__(self): self.path = os.path.join(os.getcwd(), TMPFS_DIR_NAME) if os.path.exists(self.path): raise ValueError( "Tmp dir found at %s - remove before running tests" % self.path ) os.mkdir(self.path) return self def __exit__(self, *args): shutil.rmtree(self.path) def create_file(self, filename, content): with open(os.path.join(self.path, filename), "w") as file: file.write(content) def mock(self): """ Create a file which fails on a LineCheck and a ContentCheck """ self.create_file("invalid.rst", "D002 D005 ") def expected(self, template): """ Insert the path into a template to generate an expected test value """ return template.format(path=self.path) class FakeResult(object): """ Minimum valid result returned from doc8 """ total_errors = 0 def report(self): return "" class TestCommandLine(testtools.TestCase): """ Test command line invocation """ def test_main__no_quiet_no_verbose__output_is_not_quiet(self): with TmpFs() as tmpfs, Capture() as (out, err), patch( "argparse._sys.argv", ["doc8", tmpfs.path] ): tmpfs.mock() state = main() self.assertEqual(out.getvalue(), tmpfs.expected(OUTPUT_CMD_NO_QUIET)) self.assertEqual(err.getvalue(), "") self.assertEqual(state, 1) def test_main__quiet_no_verbose__output_is_quiet(self): with TmpFs() as tmpfs, Capture() as (out, err), patch( "argparse._sys.argv", ["doc8", "--quiet", tmpfs.path] ): tmpfs.mock() state = main() self.assertEqual(out.getvalue(), tmpfs.expected(OUTPUT_CMD_QUIET)) self.assertEqual(err.getvalue(), "") self.assertEqual(state, 1) def test_main__no_quiet_verbose__output_is_verbose(self): with TmpFs() as tmpfs, Capture() as (out, err), patch( "argparse._sys.argv", ["doc8", "--verbose", tmpfs.path] ): tmpfs.mock() state = main() self.assertEqual(out.getvalue(), tmpfs.expected(OUTPUT_CMD_VERBOSE)) self.assertEqual(err.getvalue(), "") self.assertEqual(state, 1) class TestApi(testtools.TestCase): """ Test direct code invocation """ def test_doc8__defaults__no_output_and_report_as_expected(self): with TmpFs() as tmpfs, Capture() as (out, err): tmpfs.mock() result = doc8(paths=[tmpfs.path]) self.assertEqual(result.report(), tmpfs.expected(OUTPUT_API_REPORT)) self.assertEqual( result.errors, [ ( "doc8.checks.CheckTrailingWhitespace", "{}/invalid.rst".format(tmpfs.path), 1, "D002", "Trailing whitespace", ), ( "doc8.checks.CheckNewlineEndOfFile", "{}/invalid.rst".format(tmpfs.path), 1, "D005", "No newline at end of file", ), ], ) self.assertEqual(out.getvalue(), "") self.assertEqual(err.getvalue(), "") self.assertEqual(result.total_errors, 2) def test_doc8__verbose__verbose_overridden(self): with TmpFs() as tmpfs, Capture() as (out, err): tmpfs.mock() result = doc8(paths=[tmpfs.path], verbose=True) self.assertEqual(result.report(), tmpfs.expected(OUTPUT_API_REPORT)) self.assertEqual(out.getvalue(), "") self.assertEqual(err.getvalue(), "") self.assertEqual(result.total_errors, 2) class TestArguments(testtools.TestCase): """ Test that arguments are parsed correctly """ def get_args(self, **kwargs): # Defaults args = { "paths": [os.getcwd()], "config": [], "allow_long_titles": False, "ignore": set(), "sphinx": True, "ignore_path": [], "ignore_path_errors": {}, "default_extension": "", "file_encoding": "", "max_line_length": 79, "extension": list([".rst", ".txt"]), "quiet": False, "verbose": False, "version": False, } args.update(kwargs) return args def test_get_args__override__value_overridden(self): # Just checking a dict is a dict, but confirms nothing silly has happened # so we can make assumptions about get_args in other tests self.assertEqual( self.get_args(paths=["/tmp/does/not/exist"]), { "paths": ["/tmp/does/not/exist"], "config": [], "allow_long_titles": False, "ignore": set(), "sphinx": True, "ignore_path": [], "ignore_path_errors": {}, "default_extension": "", "file_encoding": "", "max_line_length": 79, "extension": [".rst", ".txt"], "quiet": False, "verbose": False, "version": False, }, ) def test_args__no_args__defaults(self): mock_scan = MagicMock(return_value=([], 0)) with patch("doc8.main.scan", mock_scan), patch("argparse._sys.argv", ["doc8"]): state = main() self.assertEqual(state, 0) mock_scan.assert_called_once_with(self.get_args()) def test_args__paths__overrides_default(self): mock_scan = MagicMock(return_value=([], 0)) with patch("doc8.main.scan", mock_scan), patch( "argparse._sys.argv", ["doc8", "path1", "path2"] ): state = main() self.assertEqual(state, 0) mock_scan.assert_called_once_with(self.get_args(paths=["path1", "path2"])) def test_args__config__overrides_default(self): mock_scan = MagicMock(return_value=([], 0)) mock_config = MagicMock(return_value={}) with patch("doc8.main.scan", mock_scan), patch( "doc8.main.extract_config", mock_config ), patch( "argparse._sys.argv", ["doc8", "--config", "path1", "--config", "path2"] ): state = main() self.assertEqual(state, 0) mock_scan.assert_called_once_with(self.get_args(config=["path1", "path2"])) def test_args__allow_long_titles__overrides_default(self): mock_scan = MagicMock(return_value=([], 0)) with patch("doc8.main.scan", mock_scan), patch( "argparse._sys.argv", ["doc8", "--allow-long-titles"] ): state = main() self.assertEqual(state, 0) mock_scan.assert_called_once_with(self.get_args(allow_long_titles=True)) def test_args__ignore__overrides_default(self): mock_scan = MagicMock(return_value=([], 0)) with patch("doc8.main.scan", mock_scan), patch( "argparse._sys.argv", ["doc8", "--ignore", "D002", "--ignore", "D002", "--ignore", "D005"], ): state = main() self.assertEqual(state, 0) mock_scan.assert_called_once_with(self.get_args(ignore={"D002", "D005"})) def test_args__sphinx__overrides_default(self): mock_scan = MagicMock(return_value=([], 0)) with patch("doc8.main.scan", mock_scan), patch( "argparse._sys.argv", ["doc8", "--no-sphinx"] ): state = main() self.assertEqual(state, 0) mock_scan.assert_called_once_with(self.get_args(sphinx=False)) def test_args__ignore_path__overrides_default(self): mock_scan = MagicMock(return_value=([], 0)) with patch("doc8.main.scan", mock_scan), patch( "argparse._sys.argv", ["doc8", "--ignore-path", "path1", "--ignore-path", "path2"], ): state = main() self.assertEqual(state, 0) mock_scan.assert_called_once_with( self.get_args(ignore_path=["path1", "path2"]) ) def test_args__ignore_path_errors__overrides_default(self): mock_scan = MagicMock(return_value=([], 0)) with patch("doc8.main.scan", mock_scan), patch( "argparse._sys.argv", [ "doc8", "--ignore-path-errors", "path1;D002", "--ignore-path-errors", "path2;D005", ], ): state = main() self.assertEqual(state, 0) mock_scan.assert_called_once_with( self.get_args(ignore_path_errors={"path1": {"D002"}, "path2": {"D005"}}) ) def test_args__default_extension__overrides_default(self): mock_scan = MagicMock(return_value=([], 0)) with patch("doc8.main.scan", mock_scan), patch( "argparse._sys.argv", ["doc8", "--default-extension", "rst"] ): state = main() self.assertEqual(state, 0) mock_scan.assert_called_once_with(self.get_args(default_extension="rst")) def test_args__file_encoding__overrides_default(self): mock_scan = MagicMock(return_value=([], 0)) with patch("doc8.main.scan", mock_scan), patch( "argparse._sys.argv", ["doc8", "--file-encoding", "utf8"] ): state = main() self.assertEqual(state, 0) mock_scan.assert_called_once_with(self.get_args(file_encoding="utf8")) def test_args__max_line_length__overrides_default(self): mock_scan = MagicMock(return_value=([], 0)) with patch("doc8.main.scan", mock_scan), patch( "argparse._sys.argv", ["doc8", "--max-line-length", "88"] ): state = main() self.assertEqual(state, 0) mock_scan.assert_called_once_with(self.get_args(max_line_length=88)) def test_args__extension__overrides_default(self): # ": [".rst", ".txt"], mock_scan = MagicMock(return_value=([], 0)) with patch("doc8.main.scan", mock_scan), patch( "argparse._sys.argv", ["doc8", "--extension", "ext1", "--extension", "ext2"] ): state = main() self.assertEqual(state, 0) mock_scan.assert_called_once_with( self.get_args(extension=[".rst", ".txt", "ext1", "ext2"]) ) def test_args__quiet__overrides_default(self): mock_scan = MagicMock(return_value=([], 0)) with patch("doc8.main.scan", mock_scan), patch( "argparse._sys.argv", ["doc8", "--quiet"] ): state = main() self.assertEqual(state, 0) mock_scan.assert_called_once_with(self.get_args(quiet=True)) def test_args__verbose__overrides_default(self): mock_scan = MagicMock(return_value=([], 0)) with patch("doc8.main.scan", mock_scan), patch( "argparse._sys.argv", ["doc8", "--verbose"] ): state = main() self.assertEqual(state, 0) mock_scan.assert_called_once_with(self.get_args(verbose=True)) def test_args__version__overrides_default(self): mock_scan = MagicMock(return_value=([], 0)) with patch("doc8.main.scan", mock_scan), patch( "argparse._sys.argv", ["doc8", "--version"] ): state = main() self.assertEqual(state, 0) mock_scan.assert_not_called()
10,685
0
756
d430b5316abd1e325a4aa326b5753ee4e591a779
912
py
Python
apps/home/forms.py
Rbc-1234/kcb
822d588ea4522dabb002bc6fbebe31e48532bd29
[ "MIT" ]
null
null
null
apps/home/forms.py
Rbc-1234/kcb
822d588ea4522dabb002bc6fbebe31e48532bd29
[ "MIT" ]
null
null
null
apps/home/forms.py
Rbc-1234/kcb
822d588ea4522dabb002bc6fbebe31e48532bd29
[ "MIT" ]
null
null
null
from .models import Brand,Size,BrandColor,Category,Master_Page from django import forms from django import forms
21.714286
113
0.640351
from .models import Brand,Size,BrandColor,Category,Master_Page from django import forms from django import forms class BrandForm(forms.ModelForm): class Meta: model = Brand fields = ('brandname','logo','status') class SizeForm(forms.ModelForm): class Meta: model = Size fields = ('brandsize',) class ColorForm(forms.ModelForm): class Meta: model = BrandColor fields = ('color',) class CategoryForm(forms.ModelForm): class Meta: model = Category fields = ('brandcategory',) class MasterForm(forms.ModelForm): class Meta: model = Master_Page fields = ('name','discription','document','brandsize','brandname','brandcategory','price','masterstatus') class ContactForm(forms.Form): email = forms.EmailField(required=True) message = forms.CharField(required=True)
0
642
138
78ce4496dcf69be39aa029c35de1e7db911c3ea3
5,290
py
Python
ROSCO_toolbox/sim.py
WillC-DNV/ROSCO
2b095d4c7a6b7f2fe0ef056969f423e6a014b6be
[ "Apache-2.0" ]
41
2020-01-31T01:21:04.000Z
2022-03-30T08:07:42.000Z
ROSCO_toolbox/sim.py
WillC-DNV/ROSCO
2b095d4c7a6b7f2fe0ef056969f423e6a014b6be
[ "Apache-2.0" ]
56
2020-03-26T13:15:36.000Z
2022-03-28T17:07:58.000Z
ROSCO_toolbox/sim.py
WillC-DNV/ROSCO
2b095d4c7a6b7f2fe0ef056969f423e6a014b6be
[ "Apache-2.0" ]
36
2020-01-10T21:39:17.000Z
2022-03-31T08:36:18.000Z
# Copyright 2019 NREL # Licensed under the Apache License, Version 2.0 (the "License"); you may not use # this file except in compliance with the License. You may obtain a copy of the # License at http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the # speROSCO_cific language governing permissions and limitations under the License. import numpy as np from ROSCO_toolbox import turbine as ROSCO_turbine import matplotlib.pyplot as plt import sys # Some useful constants deg2rad = np.deg2rad(1) rad2deg = np.rad2deg(1) rpm2RadSec = 2.0*(np.pi)/60.0 class Sim(): """ Simple controller simulation interface for a wind turbine. - Currently runs a 1DOF simple rotor model based on an OpenFAST model Note: Due to the complex nature of the wind speed estimators implemented in ROSCO, using them for simulations is known to cause problems for the simple simulator. We suggesting using WE_Mode = 0 for the simulator Methods: -------- sim_ws_series Parameters: ----------- turbine: class Turbine class containing wind turbine information from OpenFAST model controller_int: class Controller interface class to run compiled controller binary """ def __init__(self, turbine, controller_int): """ Setup the simulator """ self.turbine = turbine self.controller_int = controller_int def sim_ws_series(self,t_array,ws_array,rotor_rpm_init=10,init_pitch=0.0, make_plots=True): ''' Simulate simplified turbine model using a complied controller (.dll or similar). - currently a 1DOF rotor model Parameters: ----------- t_array: float Array of time steps, (s) ws_array: float Array of wind speeds, (s) rotor_rpm_init: float, optional initial rotor speed, (rpm) init_pitch: float, optional initial blade pitch angle, (deg) make_plots: bool, optional True: generate plots, False: don't. ''' print('Running simulation for %s wind turbine.' % self.turbine.TurbineName) # Store turbine data for conveniente dt = t_array[1] - t_array[0] R = self.turbine.rotor_radius GBRatio = self.turbine.Ng # Declare output arrays bld_pitch = np.ones_like(t_array) * init_pitch rot_speed = np.ones_like(t_array) * rotor_rpm_init * rpm2RadSec # represent rot speed in rad / s gen_speed = np.ones_like(t_array) * rotor_rpm_init * GBRatio * rpm2RadSec # represent gen speed in rad/s aero_torque = np.ones_like(t_array) * 1000.0 gen_torque = np.ones_like(t_array) # * trq_cont(turbine_dict, gen_speed[0]) gen_power = np.ones_like(t_array) * 0.0 # Loop through time for i, t in enumerate(t_array): if i == 0: continue # Skip the first run ws = ws_array[i] # Load current Cq data tsr = rot_speed[i-1] * self.turbine.rotor_radius / ws cq = self.turbine.Cq.interp_surface([bld_pitch[i-1]],tsr) # Update the turbine state # -- 1DOF model: rotor speed and generator speed (scaled by Ng) aero_torque[i] = 0.5 * self.turbine.rho * (np.pi * R**2) * cq * R * ws**2 rot_speed[i] = rot_speed[i-1] + (dt/self.turbine.J)*(aero_torque[i] * self.turbine.GenEff/100 - self.turbine.Ng * gen_torque[i-1]) gen_speed[i] = rot_speed[i] * self.turbine.Ng # Call the controller gen_torque[i], bld_pitch[i] = self.controller_int.call_controller(t,dt,bld_pitch[i-1],gen_torque[i-1],gen_speed[i],self.turbine.GenEff/100,rot_speed[i],ws) # Calculate the power gen_power[i] = gen_speed[i] * gen_torque[i] # Save these values self.bld_pitch = bld_pitch self.rot_speed = rot_speed self.gen_speed = gen_speed self.aero_torque = aero_torque self.gen_torque = gen_torque self.gen_power = gen_power self.t_array = t_array self.ws_array = ws_array # Close shared library when finished self.controller_int.kill_discon() if make_plots: fig, axarr = plt.subplots(4,1,sharex=True,figsize=(6,10)) ax = axarr[0] ax.plot(self.t_array,self.ws_array) ax.set_ylabel('Wind Speed (m/s)') ax.grid() ax = axarr[1] ax.plot(self.t_array,self.rot_speed) ax.set_ylabel('Rot Speed (rad/s)') ax.grid() ax = axarr[2] ax.plot(self.t_array,self.gen_torque) ax.set_ylabel('Gen Torque (N)') ax.grid() ax = axarr[3] ax.plot(self.t_array,self.bld_pitch*rad2deg) ax.set_ylabel('Bld Pitch (deg)') ax.set_xlabel('Time (s)') ax.grid()
36.736111
167
0.609452
# Copyright 2019 NREL # Licensed under the Apache License, Version 2.0 (the "License"); you may not use # this file except in compliance with the License. You may obtain a copy of the # License at http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the # speROSCO_cific language governing permissions and limitations under the License. import numpy as np from ROSCO_toolbox import turbine as ROSCO_turbine import matplotlib.pyplot as plt import sys # Some useful constants deg2rad = np.deg2rad(1) rad2deg = np.rad2deg(1) rpm2RadSec = 2.0*(np.pi)/60.0 class Sim(): """ Simple controller simulation interface for a wind turbine. - Currently runs a 1DOF simple rotor model based on an OpenFAST model Note: Due to the complex nature of the wind speed estimators implemented in ROSCO, using them for simulations is known to cause problems for the simple simulator. We suggesting using WE_Mode = 0 for the simulator Methods: -------- sim_ws_series Parameters: ----------- turbine: class Turbine class containing wind turbine information from OpenFAST model controller_int: class Controller interface class to run compiled controller binary """ def __init__(self, turbine, controller_int): """ Setup the simulator """ self.turbine = turbine self.controller_int = controller_int def sim_ws_series(self,t_array,ws_array,rotor_rpm_init=10,init_pitch=0.0, make_plots=True): ''' Simulate simplified turbine model using a complied controller (.dll or similar). - currently a 1DOF rotor model Parameters: ----------- t_array: float Array of time steps, (s) ws_array: float Array of wind speeds, (s) rotor_rpm_init: float, optional initial rotor speed, (rpm) init_pitch: float, optional initial blade pitch angle, (deg) make_plots: bool, optional True: generate plots, False: don't. ''' print('Running simulation for %s wind turbine.' % self.turbine.TurbineName) # Store turbine data for conveniente dt = t_array[1] - t_array[0] R = self.turbine.rotor_radius GBRatio = self.turbine.Ng # Declare output arrays bld_pitch = np.ones_like(t_array) * init_pitch rot_speed = np.ones_like(t_array) * rotor_rpm_init * rpm2RadSec # represent rot speed in rad / s gen_speed = np.ones_like(t_array) * rotor_rpm_init * GBRatio * rpm2RadSec # represent gen speed in rad/s aero_torque = np.ones_like(t_array) * 1000.0 gen_torque = np.ones_like(t_array) # * trq_cont(turbine_dict, gen_speed[0]) gen_power = np.ones_like(t_array) * 0.0 # Loop through time for i, t in enumerate(t_array): if i == 0: continue # Skip the first run ws = ws_array[i] # Load current Cq data tsr = rot_speed[i-1] * self.turbine.rotor_radius / ws cq = self.turbine.Cq.interp_surface([bld_pitch[i-1]],tsr) # Update the turbine state # -- 1DOF model: rotor speed and generator speed (scaled by Ng) aero_torque[i] = 0.5 * self.turbine.rho * (np.pi * R**2) * cq * R * ws**2 rot_speed[i] = rot_speed[i-1] + (dt/self.turbine.J)*(aero_torque[i] * self.turbine.GenEff/100 - self.turbine.Ng * gen_torque[i-1]) gen_speed[i] = rot_speed[i] * self.turbine.Ng # Call the controller gen_torque[i], bld_pitch[i] = self.controller_int.call_controller(t,dt,bld_pitch[i-1],gen_torque[i-1],gen_speed[i],self.turbine.GenEff/100,rot_speed[i],ws) # Calculate the power gen_power[i] = gen_speed[i] * gen_torque[i] # Save these values self.bld_pitch = bld_pitch self.rot_speed = rot_speed self.gen_speed = gen_speed self.aero_torque = aero_torque self.gen_torque = gen_torque self.gen_power = gen_power self.t_array = t_array self.ws_array = ws_array # Close shared library when finished self.controller_int.kill_discon() if make_plots: fig, axarr = plt.subplots(4,1,sharex=True,figsize=(6,10)) ax = axarr[0] ax.plot(self.t_array,self.ws_array) ax.set_ylabel('Wind Speed (m/s)') ax.grid() ax = axarr[1] ax.plot(self.t_array,self.rot_speed) ax.set_ylabel('Rot Speed (rad/s)') ax.grid() ax = axarr[2] ax.plot(self.t_array,self.gen_torque) ax.set_ylabel('Gen Torque (N)') ax.grid() ax = axarr[3] ax.plot(self.t_array,self.bld_pitch*rad2deg) ax.set_ylabel('Bld Pitch (deg)') ax.set_xlabel('Time (s)') ax.grid()
0
0
0
2d8a2ac3e6ed817e21e5fe3fa3058c2b10c86ad1
1,077
py
Python
plist_keys_reader.py
igorkotkovets/awesome-snippets
117962560dc65a337fcbe0ab9cd4435eff4a510b
[ "MIT" ]
2
2022-01-28T14:08:05.000Z
2022-02-13T20:16:40.000Z
plist_keys_reader.py
iharkatkavets/terminal-snippets
117962560dc65a337fcbe0ab9cd4435eff4a510b
[ "MIT" ]
1
2018-01-17T10:28:14.000Z
2018-01-17T10:28:14.000Z
plist_keys_reader.py
iharkatkavets/terminal-snippets
117962560dc65a337fcbe0ab9cd4435eff4a510b
[ "MIT" ]
1
2020-03-04T02:58:23.000Z
2020-03-04T02:58:23.000Z
#!/usr/bin/python3 import sys, getopt import plistlib from optparse import OptionParser from sys import version_info if __name__ == "__main__": main(sys.argv[1:])
26.268293
66
0.640669
#!/usr/bin/python3 import sys, getopt import plistlib from optparse import OptionParser from sys import version_info class Parameters(object): def __init__(self, inputFile): self.inputFile = inputFile class PropertiesReader(object): def readProperties(self, argv): usage = "usage: %prog -i <title>" parser = OptionParser(usage=usage) parser.add_option("-i", "--input", dest="varinput", help="Input File", metavar="STRING") (options, args) = parser.parse_args() return Parameters(options.varinput) class PlistReader(object): def readFile(self, parameters): inputPlistDict = plistlib.readPlist(parameters.inputFile) keysIn = map(lambda x: "\""+x+"\"", inputPlistDict.keys()) str = ",\n".join(keysIn) print str # for key, value in inputPlistDict.items(): # print key, def main(argv): parameters = PropertiesReader().readProperties(argv) PlistReader().readFile(parameters) if __name__ == "__main__": main(sys.argv[1:])
714
19
170
ae7806e928206a7aaae4db5306888a68022ddcae
2,418
py
Python
deep_privacy/experiments/pose_sensitivity_experiment.py
aaniin/DeepPrivacy
068d86ca112ada4b7d37f57c3b1be6e4ca44dad1
[ "MIT" ]
6
2019-10-17T13:11:13.000Z
2021-10-01T17:35:39.000Z
deep_privacy/experiments/pose_sensitivity_experiment.py
EugenioRJ/DeepPrivacy
3516f6f3bf2dcb6e7ed4d86195a7c1974077cdf8
[ "MIT" ]
4
2019-09-26T07:08:49.000Z
2019-10-06T12:13:51.000Z
deep_privacy/experiments/pose_sensitivity_experiment.py
EugenioRJ/DeepPrivacy
3516f6f3bf2dcb6e7ed4d86195a7c1974077cdf8
[ "MIT" ]
1
2020-10-10T18:55:49.000Z
2020-10-10T18:55:49.000Z
import torch import numpy as np from deep_privacy import torch_utils from deep_privacy.visualization import utils as vis_utils import os from deep_privacy.inference import infer from deep_privacy.data_tools.dataloaders import load_dataset_files, cut_bounding_box import matplotlib.pyplot as plt if __name__ == "__main__": generator, _, _, _, _ = infer.read_args() imsize = generator.current_imsize images, bounding_boxes, landmarks = load_dataset_files("data/fdf", imsize, load_fraction=True) batch_size = 128 savedir = os.path.join(".debug","test_examples", "pose_sensitivity_experiment") os.makedirs(savedir, exist_ok=True) num_iterations = 20 ims_to_save = [] percentages = [0] + list(np.linspace(-0.3, 0.3, num_iterations-1)) z = generator.generate_latent_variable(1, "cuda", torch.float32).zero_() for idx in range(-5, -1): orig = images[idx] orig_pose = landmarks[idx:idx+1] bbox = bounding_boxes[idx].clone() assert orig.dtype == np.uint8 to_save = orig.copy() to_save = np.tile(to_save, (2, 1, 1)) truncation_levels = np.linspace(0.00, 3, num_iterations) for i in range(num_iterations): im = orig.copy() orig_to_save = im.copy() p = percentages[i] pose = orig_pose.clone() rand = torch.rand_like(pose) - 0.5 rand = (rand / 0.5) * p pose += rand im = cut_bounding_box(im, bbox, generator.transition_value) keypoints = (pose*imsize).long() keypoints = infer.keypoint_to_numpy(keypoints) orig_to_save = vis_utils.draw_faces_with_keypoints( orig_to_save, None, [keypoints], radius=3) im = torch_utils.image_to_torch(im, cuda=True, normalize_img=True) im = generator(im, pose, z.clone()) im = torch_utils.image_to_numpy(im.squeeze(), to_uint8=True, denormalize=True) im = np.concatenate((orig_to_save.astype(np.uint8), im), axis=0) to_save = np.concatenate((to_save, im), axis=1) ims_to_save.append(to_save) savepath = os.path.join(savedir, f"result_image.jpg") ims_to_save = np.concatenate(ims_to_save, axis=0) plt.imsave(savepath, ims_to_save) print("Results saved to:", savedir)
36.089552
90
0.629446
import torch import numpy as np from deep_privacy import torch_utils from deep_privacy.visualization import utils as vis_utils import os from deep_privacy.inference import infer from deep_privacy.data_tools.dataloaders import load_dataset_files, cut_bounding_box import matplotlib.pyplot as plt if __name__ == "__main__": generator, _, _, _, _ = infer.read_args() imsize = generator.current_imsize images, bounding_boxes, landmarks = load_dataset_files("data/fdf", imsize, load_fraction=True) batch_size = 128 savedir = os.path.join(".debug","test_examples", "pose_sensitivity_experiment") os.makedirs(savedir, exist_ok=True) num_iterations = 20 ims_to_save = [] percentages = [0] + list(np.linspace(-0.3, 0.3, num_iterations-1)) z = generator.generate_latent_variable(1, "cuda", torch.float32).zero_() for idx in range(-5, -1): orig = images[idx] orig_pose = landmarks[idx:idx+1] bbox = bounding_boxes[idx].clone() assert orig.dtype == np.uint8 to_save = orig.copy() to_save = np.tile(to_save, (2, 1, 1)) truncation_levels = np.linspace(0.00, 3, num_iterations) for i in range(num_iterations): im = orig.copy() orig_to_save = im.copy() p = percentages[i] pose = orig_pose.clone() rand = torch.rand_like(pose) - 0.5 rand = (rand / 0.5) * p pose += rand im = cut_bounding_box(im, bbox, generator.transition_value) keypoints = (pose*imsize).long() keypoints = infer.keypoint_to_numpy(keypoints) orig_to_save = vis_utils.draw_faces_with_keypoints( orig_to_save, None, [keypoints], radius=3) im = torch_utils.image_to_torch(im, cuda=True, normalize_img=True) im = generator(im, pose, z.clone()) im = torch_utils.image_to_numpy(im.squeeze(), to_uint8=True, denormalize=True) im = np.concatenate((orig_to_save.astype(np.uint8), im), axis=0) to_save = np.concatenate((to_save, im), axis=1) ims_to_save.append(to_save) savepath = os.path.join(savedir, f"result_image.jpg") ims_to_save = np.concatenate(ims_to_save, axis=0) plt.imsave(savepath, ims_to_save) print("Results saved to:", savedir)
0
0
0
3ec42d21b7a0d85a7b993ffded41816c0e38ee99
1,368
py
Python
read.py
huangjunfeng2000/TestPython
3ddbd4185dc925783fb72ed21f12c240a0f057d2
[ "CNRI-Python-GPL-Compatible" ]
null
null
null
read.py
huangjunfeng2000/TestPython
3ddbd4185dc925783fb72ed21f12c240a0f057d2
[ "CNRI-Python-GPL-Compatible" ]
null
null
null
read.py
huangjunfeng2000/TestPython
3ddbd4185dc925783fb72ed21f12c240a0f057d2
[ "CNRI-Python-GPL-Compatible" ]
null
null
null
import os inputfile = "c:\ip.txt" inputfile='c:\column.bmp' outputfile = 'c:\ip_result.txt' outputfile2 = 'c:\ip_result2.txt' import sys if __name__ == '__main__': if (len(sys.argv)) != 2: print 'Input filepath' exit(1) f_input = sys.argv[1] print f_input travsedir(f_input)
22.064516
47
0.645468
import os inputfile = "c:\ip.txt" inputfile='c:\column.bmp' outputfile = 'c:\ip_result.txt' outputfile2 = 'c:\ip_result2.txt' def translatefile(filename): inputfile=filename outputfile=filename+".result" infile = open(inputfile, 'rb') outfile = open(outputfile, 'w') #outfile2 = open(outputfile2, 'w') fcount = os.path.getsize(inputfile) contype = 2 while fcount > 0: if fcount<1024: data=infile.read(fcount) fcount -= fcount else: data=infile.read(1024) fcount-=1024 #outfile.write(data) for cval in data: if contype == 1: strval=bin(ord(cval)) strval=strval[2:] strval.zfill(8) strval2=int(strval, 2) strval2=chr(strval2) else: strval=hex(ord(cval)) strval=strval[2:] strval.zfill(2) strval2=int(strval, 16) strval2=chr(strval2) outfile.write(strval) #outfile2.write(strval2) infile.close() outfile.close() #outfile2.close() def travsedir(path): import os files=os.listdir(path) for strfile in files: print strfile if (os.path.isfile(strfile)): root, extension = os.path.splitext(strfile) if (extension != ".result"): translatefile(strfile) import sys if __name__ == '__main__': if (len(sys.argv)) != 2: print 'Input filepath' exit(1) f_input = sys.argv[1] print f_input travsedir(f_input)
1,017
0
47
674b1427368743ff6c45aadf8197cc21014e8e23
5,244
py
Python
api/util.py
eark-project/access_dipcreator
b1f9034d309dfdb676cbba92c9c4722bf576aba2
[ "MIT" ]
null
null
null
api/util.py
eark-project/access_dipcreator
b1f9034d309dfdb676cbba92c9c4722bf576aba2
[ "MIT" ]
null
null
null
api/util.py
eark-project/access_dipcreator
b1f9034d309dfdb676cbba92c9c4722bf576aba2
[ "MIT" ]
null
null
null
import json import os from json import JSONDecodeError import magic import requests from PyPDF2 import PdfFileReader from django.http import Http404 from config.configuration import django_backend_service_api_url, verify_certificate from eatb.utils.fileutils import read_file_content, find_files from util.djangoutils import get_user_api_token
39.428571
110
0.648741
import json import os from json import JSONDecodeError import magic import requests from PyPDF2 import PdfFileReader from django.http import Http404 from config.configuration import django_backend_service_api_url, verify_certificate from eatb.utils.fileutils import read_file_content, find_files from util.djangoutils import get_user_api_token def get_representation_ids(working_directory): if not os.path.exists(working_directory): raise Http404("Working directory not found") metadata_file_path = os.path.join(working_directory, "metadata/metadata.json") if not os.path.exists(metadata_file_path): raise Http404("Basic metadata not found") try: md_content = read_file_content(metadata_file_path) md = json.loads(md_content) if "representations" not in md: raise ValueError("Insufficient metadata") representation_ids = [k for k, v in md["representations"].items()] return representation_ids except JSONDecodeError: raise ValueError('Error parsing metadata') def get_representation_ids_by_label(working_directory, representation_label): if not os.path.exists(working_directory): raise Http404("Working directory not found") metadata_file_path = os.path.join(working_directory, "metadata/metadata.json") if not os.path.exists(metadata_file_path): raise Http404("Basic metadata not found") try: md_content = read_file_content(metadata_file_path) md = json.loads(md_content) if "representations" not in md: raise ValueError("Insufficient metadata") representation_ids = [k for k, v in md["representations"].items() if "distribution_label" in v and v["distribution_label"] == representation_label] return representation_ids except JSONDecodeError: raise ValueError('Error parsing metadata') class DirectoryInfo(object): def __init__(self, root_directory): self.root_directory = root_directory def summary(self): report = {"mime_types": {}, "total_num_files": 0} contained_files = find_files(self.root_directory, "*") for contained_file in contained_files: report["total_num_files"] = report["total_num_files"] + 1 mime_type = magic.Magic(mime=True).from_file(contained_file) if mime_type not in report["mime_types"]: report["mime_types"][mime_type] = 1 else: report["mime_types"][mime_type] = report["mime_types"][mime_type] + 1 if mime_type == "application/pdf": pdf = PdfFileReader(open(contained_file, 'rb')) num_pdf_pages = pdf.getNumPages() report["num_pdf_pages"] = report["num_pdf_pages"] + num_pdf_pages return report @staticmethod def summary_to_hr(summary): report_hr = {} for k, v in summary.items(): key = k.replace("num", "number of").replace("_", " ") key = key[0].upper() + key[1:] report_hr[key] = v return report_hr def data_sources_info_from_processing_input(request, processing_input): data_sources_info = [] for data_source in processing_input.data_sources.all(): data_source_info = {'identifier': data_source.ip.uid, 'uid': data_source.ip.uid} query_url = "%s/datasets/%s/representations/info/" % ( django_backend_service_api_url, data_source.ip.uid) user_api_token = get_user_api_token(request.user) response = requests.get(query_url, headers={'Authorization': 'Token %s' % user_api_token}, verify=verify_certificate) if response.status_code == 200: try: data_source_info['info'] = json.loads(response.text) data_sources_info.append(data_source_info) except JSONDecodeError as err: raise ValueError('Error parsing response for source data request for process: %s, error: %s' % (data_source.source, err.__str__())) else: raise ValueError('Error retrieving source data for process id: %s' % data_source.source) return data_sources_info class DirectoryInfo(object): def __init__(self, root_directory): self.root_directory = root_directory def summary(self): report = {"mime_types": {}, "total_num_files": 0} contained_files = find_files(self.root_directory, "*") for contained_file in contained_files: report["total_num_files"] = report["total_num_files"] + 1 mime_type = magic.Magic(mime=True).from_file(contained_file) if mime_type not in report["mime_types"]: report["mime_types"][mime_type] = 1 else: report["mime_types"][mime_type] = report["mime_types"][mime_type] + 1 return report @staticmethod def summary_to_hr(summary): report_hr = {} for k, v in summary.items(): key = k.replace("num", "number of").replace("_", " ") key = key[0].upper() + key[1:] report_hr[key] = v return report_hr
4,566
212
115
14e1f182dcdee533731ed093e578fc202b4e4d61
21,625
py
Python
src/soles_stuff.py
HRI-EU/newbee_dataset
27f69c388974882b2f797507d4eaa7442f74fa8c
[ "MIT" ]
null
null
null
src/soles_stuff.py
HRI-EU/newbee_dataset
27f69c388974882b2f797507d4eaa7442f74fa8c
[ "MIT" ]
null
null
null
src/soles_stuff.py
HRI-EU/newbee_dataset
27f69c388974882b2f797507d4eaa7442f74fa8c
[ "MIT" ]
null
null
null
import os import matplotlib.pyplot as plt import matplotlib import pandas as pd import numpy as np import logging import sys from sklearn.metrics import mean_absolute_error import seaborn from .common import INSOLES_FILE_NAME, LABELS_FILE_NAME seaborn.set() matplotlib.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}'] plt.rc('text', usetex=True) TARGET_FRAME_RATE = 60 STEP_FORCE_THRESHOLD = 0.2 LIFT_FORCE_THRESHOLD = 0.17 logging.basicConfig(format='%(message)s', level=logging.DEBUG) #reprocess_all_soles_data() #optimize_thresholds()
49.036281
349
0.684717
import os import matplotlib.pyplot as plt import matplotlib import pandas as pd import numpy as np import logging import sys from sklearn.metrics import mean_absolute_error import seaborn from .common import INSOLES_FILE_NAME, LABELS_FILE_NAME seaborn.set() matplotlib.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}'] plt.rc('text', usetex=True) TARGET_FRAME_RATE = 60 STEP_FORCE_THRESHOLD = 0.2 LIFT_FORCE_THRESHOLD = 0.17 def get_step_indices_old(max_force, step_threshold=0.25, change_delta=0.05, min_duration_in_seconds=0.25): step_indices = [-1] lift_indices = [-1] last_change = -sys.maxsize min_duration = min_duration_in_seconds * TARGET_FRAME_RATE for idx, force in enumerate(max_force): if idx == 0: if force >= step_threshold: step_indices.append(idx) else: lift_indices.append(idx) elif force >= step_threshold + change_delta and lift_indices[-1] > step_indices[ -1] and idx - last_change >= min_duration: step_indices.append(idx) last_change = idx elif force < step_threshold - change_delta and lift_indices[-1] < step_indices[ -1] and idx - last_change >= min_duration: lift_indices.append(idx) last_change = idx step_indices = step_indices[1:] lift_indices = lift_indices[1:] return step_indices, lift_indices def get_step_indices(max_force, step_threshold, lift_threshold, min_duration_in_seconds=0.2): step_indices = [-1] lift_indices = [-1] last_change = -sys.maxsize min_duration = min_duration_in_seconds * TARGET_FRAME_RATE for idx, force in enumerate(max_force): if idx == 0: if force >= step_threshold: step_indices.append(idx) else: lift_indices.append(idx) elif force >= step_threshold and lift_indices[-1] > step_indices[ -1] and idx - last_change >= min_duration: step_indices.append(idx) last_change = idx elif force <= lift_threshold and lift_indices[-1] < step_indices[ -1] and idx - last_change >= min_duration: lift_indices.append(idx) last_change = idx step_indices = step_indices[1:] lift_indices = lift_indices[1:] return step_indices, lift_indices def get_step_lift_durations(data_frame, step_indices, lift_indices): assert abs(len(step_indices) - len(lift_indices)) <= 1 if step_indices[0] < lift_indices[0]: if len(lift_indices) == len(step_indices): step_duration = np.array(lift_indices) - np.array(step_indices) lift_duration = np.array(step_indices[1:] + [len(data_frame.index)]) - np.array(lift_indices) elif len(lift_indices) < len(step_indices): step_duration = np.array(lift_indices + [len(data_frame.index)]) - np.array(step_indices) lift_duration = np.array(step_indices[1:]) - np.array(lift_indices) else: assert False else: if len(lift_indices) == len(step_indices): step_duration = np.array(lift_indices[1:] + [len(data_frame.index)]) - np.array(step_indices) lift_duration = np.array(step_indices) - np.array(lift_indices) elif len(step_indices) < len(lift_indices): step_duration = np.array(lift_indices[1:]) - np.array(step_indices) lift_duration = np.array(step_indices + [len(data_frame.index)]) - np.array(lift_indices) else: assert False return step_duration, lift_duration def get_step_on_ground_column(step_indices, lift_indices, step_durations, lift_durations): step_on_ground_left = [] if step_indices[0] < lift_indices[0]: for idx in range(max(len(step_durations), len(lift_durations))): if idx < len(step_durations): step_on_ground_left += [True] * step_durations[idx] if idx < len(lift_durations): step_on_ground_left += [False] * lift_durations[idx] else: for idx in range(max(len(step_durations), len(lift_durations))): if idx < len(lift_durations): step_on_ground_left += [False] * lift_durations[idx] if idx < len(step_durations): step_on_ground_left += [True] * step_durations[idx] return step_on_ground_left def get_time_until_event_column(df, event_column): result = [] indices = df.index[df[event_column] == True] last_index = -1 for index in indices: event_time = df.iloc[index]['time'] candidate_times = df[(df.index <= index) & (df.index > last_index)]['time'].to_numpy() result += (event_time - candidate_times).tolist() last_index = index result += [-1] * (df.index[-1] - indices[-1]) return result def step_detection(data_frame, step_threshold, lift_threshold, old=False): if old: step_indices_left, lift_indices_left = get_step_indices_old(data_frame['Left_Max_Force'].to_numpy()) step_indices_right, lift_indices_right = get_step_indices_old(data_frame['Right_Max_Force'].to_numpy()) else: step_indices_left, lift_indices_left = get_step_indices(data_frame['Left_Max_Force'].to_numpy(), step_threshold, lift_threshold) step_indices_right, lift_indices_right = get_step_indices(data_frame['Right_Max_Force'].to_numpy(), step_threshold, lift_threshold) tmp = np.array([False] * len(data_frame.index), dtype=bool) tmp[step_indices_right] = True data_frame['insoles_RightFoot_is_step'] = tmp tmp = np.array([False] * len(data_frame.index), dtype=bool) tmp[step_indices_left] = True data_frame['insoles_LeftFoot_is_step'] = tmp tmp = np.array([False] * len(data_frame.index), dtype=bool) tmp[lift_indices_right] = True data_frame['insoles_RightFoot_is_lift'] = tmp tmp = np.array([False] * len(data_frame.index), dtype=bool) tmp[lift_indices_left] = True data_frame['insoles_LeftFoot_is_lifted'] = tmp step_duration_left, lift_duration_left = get_step_lift_durations(data_frame, step_indices_left, lift_indices_left) step_duration_right, lift_duration_right = get_step_lift_durations(data_frame, step_indices_right, lift_indices_right) step_on_ground_left = [] if step_indices_left[0] < lift_indices_left[0]: for idx in range(max(len(step_duration_left), len(lift_duration_left))): if idx < len(step_duration_left): step_on_ground_left += [True] * step_duration_left[idx] if idx < len(lift_duration_left): step_on_ground_left += [False] * lift_duration_left[idx] else: for idx in range(max(len(step_duration_left), len(lift_duration_left))): if idx < len(lift_duration_left): step_on_ground_left += [False] * lift_duration_left[idx] if idx < len(step_duration_left): step_on_ground_left += [True] * step_duration_left[idx] data_frame['insoles_LeftFoot_on_ground'] = get_step_on_ground_column(step_indices_left, lift_indices_left, step_duration_left, lift_duration_left) data_frame['insoles_RightFoot_on_ground'] = get_step_on_ground_column(step_indices_right, lift_indices_right, step_duration_right, lift_duration_right) data_frame['insoles_LeftFoot_time_to_step'] = np.array( get_time_until_event_column(data_frame, 'insoles_LeftFoot_is_step')).astype(np.float32) data_frame['insoles_LeftFoot_time_to_lift'] = np.array( get_time_until_event_column(data_frame, 'insoles_LeftFoot_is_lifted')).astype(np.float32) data_frame['insoles_RightFoot_time_to_step'] = np.array( get_time_until_event_column(data_frame, 'insoles_RightFoot_is_step')).astype(np.float32) data_frame['insoles_RightFoot_time_to_lift'] = np.array( get_time_until_event_column(data_frame, 'insoles_RightFoot_is_lifted')).astype(np.float32) logging.info("stream summary:\n%s", get_stats_summary(data_frame, TARGET_FRAME_RATE, step_duration_left, lift_duration_left, step_duration_right, lift_duration_right)) return data_frame def get_stats_summary(data_frame, sample_rate, step_durations_left, lift_durations_left, step_durations_right, lift_durations_right): n_right_steps = len(data_frame[data_frame['insoles_RightFoot_is_step']].index) n_left_steps = len(data_frame[data_frame['insoles_LeftFoot_is_step']].index) step_differnce = abs(n_left_steps - n_right_steps) duration = (data_frame.iloc[-1]['time'] - data_frame.iloc[0]['time']) / 1000. result = "duration %.2f\n" % duration result += "%d right_steps %d left_steps %d total steps %.2f steps/min\n" % (n_right_steps, n_left_steps, n_right_steps + n_left_steps, (n_right_steps + n_left_steps)/(duration/60)) if step_differnce > 1: result += "STEP DIFFERENCE %d !!!\n" % step_differnce step_durations_in_seconds_left = step_durations_left / sample_rate lift_durations_in_seconds_left = lift_durations_left / sample_rate step_durations_in_seconds_right = step_durations_right / sample_rate lift_durations_in_seconds_right = lift_durations_right / sample_rate result += "L step duration %.2fs+-%.2f med %.2fs lift duration %.2fs+-%.2f med %.2fs \n" % (np.mean(step_durations_in_seconds_left), np.std(step_durations_in_seconds_left), np.median(step_durations_in_seconds_left), np.mean(lift_durations_in_seconds_left), np.std(lift_durations_in_seconds_left), np.mean(lift_durations_in_seconds_left)) result += "R step duration %.2fs+-%.2f med %.2fs lift duration %.2fs+-%.2f med %.2fs \n" % (np.mean(step_durations_in_seconds_right), np.std(step_durations_in_seconds_right), np.median(step_durations_in_seconds_right), np.mean(lift_durations_in_seconds_right), np.std(lift_durations_in_seconds_right), np.median(lift_durations_in_seconds_right)) return result def visualize_detection(data_frame): max_index = 750 data_frame = data_frame[data_frame.index.isin(range(0, max_index, 1))] '''plt.figure() ax = data_frame['Right_Max_Force'].plot.hist(bins=30, alpha=0.5) ax.set_title("right")''' '''plt.figure() ax = data_frame['Left_Max_Force'].plot.hist(bins=30, alpha=0.5) ax.set_title("left")''' plt.plot(data_frame['time'], data_frame['Left_Max_Force']) #ax = data_frame.plot(x='time', y='Left_Max_Force') '''ax.scatter(data_frame[data_frame['insoles_LeftFoot_is_step_gt']].index, data_frame[data_frame['insoles_LeftFoot_is_step_gt']]['Left_Max_Force'], label="gt_step", marker='x', c='r') ax.scatter(data_frame[data_frame['insoles_LeftFoot_is_lifted_gt']].index, data_frame[data_frame['insoles_LeftFoot_is_lifted_gt']]['Left_Max_Force'], label="gt_lift", marker='x', c='g')''' plt.scatter(data_frame[data_frame['insoles_LeftFoot_is_step']].time, data_frame[data_frame['insoles_LeftFoot_is_step']]['Left_Max_Force'], label="step", c=seaborn.color_palette(n_colors=8)[1]) plt.scatter(data_frame[data_frame['insoles_LeftFoot_is_lifted']].time, data_frame[data_frame['insoles_LeftFoot_is_lifted']]['Left_Max_Force'], label="lift", c=seaborn.color_palette(n_colors=8)[2]) plt.hlines(STEP_FORCE_THRESHOLD, 0, int(max_index*16.66), label=r"$\alpha_{step}$", color=seaborn.color_palette(n_colors=8)[1], linestyle='--') plt.hlines(LIFT_FORCE_THRESHOLD, 0, int(max_index*16.66), label=r"$\alpha_{lift}$", color=seaborn.color_palette(n_colors=8)[2], linestyle='--') plt.title("Left Foot Step Detection") plt.ylabel("max sensor value") plt.xlabel("time (ms)") plt.legend(fancybox=True, loc='upper right') plt.savefig('/hri/storage/user/vlosing/step_detection.pdf', bbox_inches='tight') '''plt.figure() ax = data_frame['Right_Max_Force'].plot() ax.scatter(data_frame[data_frame['insoles_RightFoot_is_step']].index, data_frame[data_frame['insoles_RightFoot_is_step']]['Right_Max_Force'], label="step", c='r') ax.scatter(data_frame[data_frame['insoles_RightFoot_is_lifted']].index, data_frame[data_frame['insoles_RightFoot_is_lifted']]['Right_Max_Force'], label="lift", c='g') ax.set_title("right") plt.legend()''' '''plt.figure() ax = data_frame['Right_Max_Force'].plot(label='right') ax = data_frame['Left_Max_Force'].plot(label='left') ax.scatter(data_frame[data_frame['insoles_RightFoot_is_step']].index, data_frame[data_frame['insoles_RightFoot_is_step']]['Right_Max_Force'], label="right_step") ax.scatter(data_frame[data_frame['insoles_RightFoot_is_lifted']].index, data_frame[data_frame['insoles_RightFoot_is_lifted']]['Right_Max_Force'], label="right_lift") ax.scatter(data_frame[data_frame['insoles_LeftFoot_is_step']].index, data_frame[data_frame['insoles_LeftFoot_is_step']]['Left_Max_Force'], label="left_step") ax.scatter(data_frame[data_frame['insoles_LeftFoot_is_lifteded']].index, data_frame[data_frame['insoles_LeftFoot_is_lifteded']]['Left_Max_Force'], label="left_lift") ax.set_title("both") plt.legend()''' plt.show() def mae(gt_times, est_times): matched_times = [] matched_idx = 0 for gt_time in gt_times: min_dif = float("inf") while matched_idx < len(est_times) and abs(gt_time - est_times[matched_idx]) < min_dif: min_dif = abs(gt_time - est_times[matched_idx]) last_matched_idx = matched_idx matched_idx += 1 matched_times.append(est_times[last_matched_idx]) return mean_absolute_error(gt_times, matched_times) def get_mae_step_lift_times(data_frames): mae_steps = [] mae_lifts = [] for data_frame in data_frames: gt_step_time = data_frame[data_frame['insoles_LeftFoot_is_step_gt']]["time"].tolist() pred_step_time = data_frame[data_frame['insoles_LeftFoot_is_step']]["time"].tolist() mae_steps.append(mae(gt_step_time, pred_step_time)) pred_lift_time = data_frame[data_frame['insoles_LeftFoot_is_lifted']]["time"].tolist() gt_lift_time = data_frame[data_frame['insoles_LeftFoot_is_lifted_gt']]["time"].tolist() mae_lifts.append(mae(gt_lift_time, pred_lift_time)) return mae_steps, mae_lifts def prepare_data_frame(data_frame): gt_is_step = [] last_item = None for item in data_frame['walk_mode']: if item != last_item and item == "DOWN": gt_is_step.append(True) else: gt_is_step.append(False) last_item = item gt_is_lift = [] last_item = "None" for item in data_frame['walk_mode']: if item != last_item and item == "UP": gt_is_lift.append(True) else: gt_is_lift.append(False) last_item = item data_frame['insoles_LeftFoot_is_step_gt'] = gt_is_step data_frame['insoles_LeftFoot_is_lifted_gt'] = gt_is_lift return data_frame def minimize_step_diff(data_frames): thresholds = np.linspace(0.05, 1, num=20) errors = [] for i, s in enumerate(thresholds): for l in thresholds[:i]: step_diffs = [] for data_frame in data_frames: data_frame = step_detection(data_frame, s, l) data_frame = prepare_data_frame(data_frame) n_right_steps = len(data_frame[data_frame['insoles_RightFoot_is_step']].index) n_left_steps = len(data_frame[data_frame['insoles_LeftFoot_is_step']].index) step_diffs.append(abs(n_left_steps - n_right_steps)) errors.append([np.mean(step_diffs), s, l]) errors.sort(key=lambda x: x[0]) print(errors[:10]) def minimize_mae(data_frames): thresholds = np.linspace(0.05, 1, num=95) errors = [] for i, s in enumerate(thresholds): for l in thresholds[:i]: frames = [] for data_frame in data_frames: data_frame = step_detection(data_frame, s, l) data_frame = prepare_data_frame(data_frame) frames.append(data_frame) mae_steps, mae_lifts = get_mae_step_lift_times(frames) mae_step = np.mean(mae_steps) mae_lift = np.mean(mae_lifts) errors.append([mae_step + mae_lift, mae_step, mae_lift, s, l]) errors.sort(key=lambda x: x[0]) print(errors[:10]) def clip_pressure_columns(data_frame): columns = [ 'Left_Hallux', 'Left_Toes', 'Left_Met1', 'Left_Met3', 'Left_Met5', 'Left_Arch', 'Left_Heel_R', 'Left_Heel_L', 'Right_Hallux', 'Right_Toes', 'Right_Met1', 'Right_Met3', 'Right_Met5', 'Right_Arch', 'Right_Heel_L', 'Right_Heel_R', 'Left_Max_Force', 'Right_Max_Force'] for col in columns: data_frame[col] = np.clip(data_frame[col], 0, 1) return data_frame def reprocess_soles_data_for_recording(path): labels_path = os.path.join(path, LABELS_FILE_NAME) insoles_path = os.path.join(path, INSOLES_FILE_NAME) insoles_data_frame = pd.read_csv(insoles_path) insoles_data_frame = clip_pressure_columns(insoles_data_frame) labels_data_frame = pd.read_csv(labels_path) columns = [column for column in labels_data_frame.columns if "Unnamed" in column] labels_data_frame.drop(columns=columns, inplace=True) data_frame = pd.merge(labels_data_frame, insoles_data_frame, how='outer', on=["time", "participant_id", "task"], validate="one_to_one") print("old") step_detection(data_frame, STEP_FORCE_THRESHOLD, LIFT_FORCE_THRESHOLD, old=True) n_right_steps = len(data_frame[data_frame['insoles_RightFoot_is_step']].index) n_left_steps = len(data_frame[data_frame['insoles_LeftFoot_is_step']].index) step_differnce_old = abs(n_left_steps - n_right_steps) print("new") data_frame = step_detection(data_frame, STEP_FORCE_THRESHOLD, LIFT_FORCE_THRESHOLD, old=False) n_right_steps = len(data_frame[data_frame['insoles_RightFoot_is_step']].index) n_left_steps = len(data_frame[data_frame['insoles_LeftFoot_is_step']].index) step_differnce_new = abs(n_left_steps - n_right_steps) insoles_data_frame = data_frame[insoles_data_frame.columns] insoles_data_frame.to_csv(insoles_path, index=False) labels_data_frame = data_frame[labels_data_frame.columns] labels_data_frame.to_csv(labels_path, index=False) return step_differnce_old, step_differnce_new def optimize_thresholds_for_paths(paths): frames = [] for subject_path in paths: insoles_data_frame = pd.read_csv(os.path.join(subject_path, INSOLES_FILE_NAME)) insoles_data_frame = clip_pressure_columns(insoles_data_frame) labels_data_frame = pd.read_csv(os.path.join(subject_path, "labels_steps.csv")) columns = [column for column in labels_data_frame.columns if "Unnamed" in column] labels_data_frame.drop(columns=columns, inplace=True) data_frame = pd.merge(labels_data_frame, insoles_data_frame, how='outer', on=["time"], validate="one_to_one") #indices = data_frame[data_frame["walk_mode"] == "UP"].index #data_frame.drop(data_frame[(data_frame.index < min(indices) - 10) | (data_frame.index > max(indices) + 10)].index, inplace=True) #data_frame.drop(data_frame[data_frame.index > 1995].index, inplace=True) data_frame = prepare_data_frame(data_frame) data_frame = step_detection(data_frame, STEP_FORCE_THRESHOLD, LIFT_FORCE_THRESHOLD, old=False) visualize_detection(data_frame) #data_frame = prepare_data_frame(data_frame) visualize_detection(data_frame) frames.append(data_frame) mae_steps, mae_lifts = get_mae_step_lift_times(frames) print("mae_step %.4f +- %.4f mae_lift %.4f +- %.4f" % (np.mean(mae_steps), np.std(mae_steps), np.mean(mae_lifts), np.std(mae_lifts))) #minimize_step_diff(frames) #minimize_mae(frames) def reprocess_all_soles_data(): prefix = "/hri/rawstreams/user/RT-PHUME/NEWBEE_dataset/data_set/" paths = [os.path.join(prefix, "courseA"), os.path.join(prefix, "courseB"), os.path.join(prefix, "courseC")] step_diffs_old = [] step_diffs_new = [] for path in paths: for root, dir_list, file_list in os.walk(path): for dir in dir_list: print(root, dir) step_diff_old, step_diff_new = reprocess_soles_data_for_recording(os.path.join(root, dir)) step_diffs_old.append(step_diff_old) step_diffs_new.append(step_diff_new) print(np.mean(step_diffs_old), np.std(step_diffs_old), np.mean(step_diffs_new), np.std(step_diffs_new)) def optimize_thresholds(): prefix = "/hri/rawstreams/user/RT-PHUME/NEWBEE_dataset_tmp/data_set/" labeled_paths = [ os.path.join(prefix, "courseA/id01/"), os.path.join(prefix, "courseA/id05/"), os.path.join(prefix, "courseB/id05/"), os.path.join(prefix, "courseC/id13/"), os.path.join(prefix, "courseC/id25/"), ] optimize_thresholds_for_paths(labeled_paths) logging.basicConfig(format='%(message)s', level=logging.DEBUG) #reprocess_all_soles_data() #optimize_thresholds()
20,636
0
414
9a82db4b1a71ac5dfe628bcacbc69013f75068ef
9,055
py
Python
code/train/step3_concat_select_split.py
ptannor/Audio2Face
98b501791e74601a72466d191730904474b74f42
[ "MIT" ]
1
2022-02-08T11:01:17.000Z
2022-02-08T11:01:17.000Z
code/train/step3_concat_select_split.py
ptannor/Audio2Face
98b501791e74601a72466d191730904474b74f42
[ "MIT" ]
null
null
null
code/train/step3_concat_select_split.py
ptannor/Audio2Face
98b501791e74601a72466d191730904474b74f42
[ "MIT" ]
null
null
null
# Copyright 2021 The FACEGOOD Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import numpy as np import os project_dir = r'D:\audio2bs\shirley_1119' bs_name = np.load(os.path.join(project_dir,'shirley_1119_bs_name.npy')) dataSet_dir = os.path.join(project_dir,'dataSet16') # 参与训练的数据 # name_list = ['1_01','1_02','2_01','2_02','2_03','2_04'] #dataSet1 # name_list = ['1_01','1_02','2_01','2_02','2_03','2_04','3_15','3_16'] #dataSet2 # name_list = ['2_02','2_03','2_04','3_15','3_16'] #dataSet3:修改后的2_02和2_04 # name_list = ['2_02','2_03','2_04','3_15','3_16'] #dataSet4:修改后的2_02和2_04 # name_list = ['1_01','1_02','2_02','2_03','2_04'] #dataSet5:修改后的1_01、1_02、2_02和2_04 # name_list = ['1_01','1_02','2_02','2_03','2_04','3_15','3_16'] #dataSet6:修改后的1_01、1_02、2_02和2_04 # name_list = ['1_01','1_02','2_02','2_03','2_04'] #dataSet7:修改后的1_01、1_02、2_02和2_04;1_01、1_02张嘴等系数*1.3 # name_list = ['1_01','1_02','2_02','2_03','2_04','3_15','3_16'] #dataSet8:修改后的1_01、1_02、2_02和2_04;1_01、1_02张嘴等系数*1.3 # name_list = ['1_01','1_02','2_02','2_03','2_04'] #dataSet9:修改后的1_01、1_02、2_02和2_04;1_01、1_02张嘴等系数*1.3;删除单音节和词语一半的0帧 # name_list = ['1_01','1_02','2_02','2_03','2_04','3_15','3_16'] #dataSet10:修改后的1_01、1_02、2_02和2_04;1_01、1_02张嘴等系数*1.3;删除单音节和词语一半的0帧 # name_list = ['1_01','1_02','2_01','2_02','2_03','2_04'] #dataSet11:修改后的1_01、1_02、2_01、2_02和2_04 # name_list = ['1_01','1_02','2_01','2_02','2_03','2_04','3_15','3_16'] #dataSet12:修改后的1_01、1_02、2_01、2_02和2_04 # name_list = ['1_01','1_02','2_01','2_02','2_03','2_04'] #dataSet11:修改后的1_01、1_02、2_01、2_02和2_04;删除单音节和词语一半的0帧 # name_list = ['1_01','1_02','2_01','2_02','2_03','2_04','3_15','3_16'] #dataSet12:修改后的1_01、1_02、2_01、2_02和2_04;删除单音节和词语一半的0帧 name_list = ['1_01','1_02','2_01','2_02','2_03','2_04','2_05','3_15','3_16'] #dataSet16:all_付 data_path_list = [os.path.join(project_dir,'lpc','lpc_1114_' + i + '.npy') for i in name_list] label_path_list = [os.path.join(project_dir,'bs_value','bs_value_1114_' + i + '.npy') for i in name_list] data = np.zeros((1, 32, 64, 1)) label = np.zeros((1, 116)) for i in range(len(data_path_list)): data_temp = np.load(data_path_list[i]) label_temp = np.load(label_path_list[i]) if data_path_list[i][-8] == '1' or data_path_list[i][-8] == '2': label_temp_sum = label_temp.sum(axis=1) zero_index = np.where(label_temp_sum == 0)[0] half_zero_index = [zero_index[i] for i in range(0,len(zero_index),2)] select_index = [i for i in range(label_temp.shape[0]) if i not in half_zero_index] data_temp = data_temp[select_index] label_temp = label_temp[select_index] data = np.vstack((data,data_temp)) label = np.vstack((label,label_temp)) data = data[1:] label = label[1:] print(data.shape) print(label.shape) # label1 = np.zeros((label.shape[0],label.shape[1])) # bs_name_index = [0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 94, 93, 95, 96, 97, 98, 99, 100, 101, 102, 103, 105, 104, 106, 107, 108, 109, 110, 111, 112, 113, 114, 1, 115] # for i in range(len(bs_name_index)): # label1[:,i] = label[:,bs_name_index[i]] # label = label1 ############### select ############### # # bs的相关性计算 # import pandas as pd # df = pd.DataFrame(label,columns=bs_name) # corr = df.corr() #计算相关系数 # data = corr.values # print(data.shape) # bs_value_dict = {} # key:bs原始索引;value:与key的bs相关的min(bs_index) # for i in range(len(bs_name)): # bs_name_corr = corr[(corr[bs_name[i]]==1)].index.tolist() #与bs_name[i]极相关的bs_name。 0.99-0.995 33个;0.999 37个;0.9999 38个;1 41个 # if len(bs_name_corr)==0: # bs_value_dict[i] = i # else: # ndx = np.asarray([np.nonzero(bs_name == bs_name0)[0][0] for bs_name0 in bs_name_corr]) #返回索引 # bs_value_dict[i] = min(ndx) # print(bs_value_dict) # bs_index = list(set(list(bs_value_dict.values()))) # print('uncorr_bs_index: ',bs_index) # print('uncorr_bs_num: ',len(bs_index)) # # 筛选常值bs和变值bs # bs_max_value = np.amax(label, axis=0) #每个BS的最大值 # bs_min_value = np.amin(label, axis=0) #每个BS的最小值 # # print('bs_max_value: ',bs_max_value) # # print('bs_min_value: ',bs_min_value) # const_bs_index = np.where(bs_max_value-bs_min_value==0) #常数BS的索引 # const_bs_index = list(const_bs_index[0]) # print('const_bs_index: ',const_bs_index) # var_bs_index = [x for x in range(len(bs_name)) if x not in const_bs_index] #变值BS的索引 # print('var_bs_index: ',var_bs_index) # print('var_bs_index_len: ',len(var_bs_index)) # const_bs_value = label[0][const_bs_index] #值不变的BS其值 # print('const_bs_value: ',const_bs_value) # bs_name_1119_v1 # const_bs_index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 15, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33, 34, 35, 38, 45, 46, 47, 48, 49, 54, 55, 60, 61, 64, 69, 70, 71, 72, 82, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115] # var_bs_index = [9, 12, 13, 14, 17, 32, 36, 37, 39, 40, 41, 42, 43, 44, 50, 51, 52, 53, 56, 57, 58, 59, 62, 63, 65, 66, 67, 68, 73, 74, 75, 76, 77, 78, 79, 80, 81, 83] # const_bs_value = [0.,-0.,0.,-0.,0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,0.] # bs_name_1015_v1 # const_bs_index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 39, 46, 47, 48, 49, 50, 55, 56, 61, 62, 65, 70, 71, 72, 73, 83, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115] # var_bs_index = [10, 13, 14, 15, 18, 33, 38, 40, 41, 42, 43, 44, 45, 51, 52, 53, 54, 57, 58, 59, 60, 63, 64, 66, 67, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84] # const_bs_value = [0.,0.,-0.,0.,-0.,0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.] # bs_name_1119_v2 # const_bs_index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 15, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33, 34, 35, 38, 45, 46, 47, 48, 49, 54, 55, 60, 61, 64, 69, 70, 71, 72, 82, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115] # var_bs_index = [9, 12, 13, 14, 17, 32, 36, 37, 39, 40, 41, 42, 43, 44, 50, 51, 52, 53, 56, 57, 58, 59, 62, 63, 65, 66, 67, 68, 73, 74, 75, 76, 77, 78, 79, 80, 81, 83] # const_bs_value = [0.,-0.,0.,-0.,0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,0.] # bs_name_1015_v2 const_bs_index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 39, 46, 47, 48, 49, 50, 55, 56, 61, 62, 65, 70, 71, 72, 73, 83, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115] var_bs_index = [10, 13, 14, 15, 18, 33, 38, 40, 41, 42, 43, 44, 45, 51, 52, 53, 54, 57, 58, 59, 60, 63, 64, 66, 67, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84] const_bs_value = [0.,0.,-0.,0.,-0.,0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.] # 保存训练数据 train_data = data val_data = data[-1000:] train_label_var = label[:,var_bs_index] val_label_var = label[-1000:,var_bs_index] print(train_data.shape) print(val_data.shape) print(train_label_var.shape) print(val_label_var.shape) np.save(os.path.join(dataSet_dir,'train_data.npy'),train_data) np.save(os.path.join(dataSet_dir,'val_data.npy'),val_data) np.save(os.path.join(dataSet_dir,'train_label_var.npy'),train_label_var) np.save(os.path.join(dataSet_dir,'val_label_var.npy'),val_label_var)
60.771812
488
0.606405
# Copyright 2021 The FACEGOOD Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import numpy as np import os project_dir = r'D:\audio2bs\shirley_1119' bs_name = np.load(os.path.join(project_dir,'shirley_1119_bs_name.npy')) dataSet_dir = os.path.join(project_dir,'dataSet16') # 参与训练的数据 # name_list = ['1_01','1_02','2_01','2_02','2_03','2_04'] #dataSet1 # name_list = ['1_01','1_02','2_01','2_02','2_03','2_04','3_15','3_16'] #dataSet2 # name_list = ['2_02','2_03','2_04','3_15','3_16'] #dataSet3:修改后的2_02和2_04 # name_list = ['2_02','2_03','2_04','3_15','3_16'] #dataSet4:修改后的2_02和2_04 # name_list = ['1_01','1_02','2_02','2_03','2_04'] #dataSet5:修改后的1_01、1_02、2_02和2_04 # name_list = ['1_01','1_02','2_02','2_03','2_04','3_15','3_16'] #dataSet6:修改后的1_01、1_02、2_02和2_04 # name_list = ['1_01','1_02','2_02','2_03','2_04'] #dataSet7:修改后的1_01、1_02、2_02和2_04;1_01、1_02张嘴等系数*1.3 # name_list = ['1_01','1_02','2_02','2_03','2_04','3_15','3_16'] #dataSet8:修改后的1_01、1_02、2_02和2_04;1_01、1_02张嘴等系数*1.3 # name_list = ['1_01','1_02','2_02','2_03','2_04'] #dataSet9:修改后的1_01、1_02、2_02和2_04;1_01、1_02张嘴等系数*1.3;删除单音节和词语一半的0帧 # name_list = ['1_01','1_02','2_02','2_03','2_04','3_15','3_16'] #dataSet10:修改后的1_01、1_02、2_02和2_04;1_01、1_02张嘴等系数*1.3;删除单音节和词语一半的0帧 # name_list = ['1_01','1_02','2_01','2_02','2_03','2_04'] #dataSet11:修改后的1_01、1_02、2_01、2_02和2_04 # name_list = ['1_01','1_02','2_01','2_02','2_03','2_04','3_15','3_16'] #dataSet12:修改后的1_01、1_02、2_01、2_02和2_04 # name_list = ['1_01','1_02','2_01','2_02','2_03','2_04'] #dataSet11:修改后的1_01、1_02、2_01、2_02和2_04;删除单音节和词语一半的0帧 # name_list = ['1_01','1_02','2_01','2_02','2_03','2_04','3_15','3_16'] #dataSet12:修改后的1_01、1_02、2_01、2_02和2_04;删除单音节和词语一半的0帧 name_list = ['1_01','1_02','2_01','2_02','2_03','2_04','2_05','3_15','3_16'] #dataSet16:all_付 data_path_list = [os.path.join(project_dir,'lpc','lpc_1114_' + i + '.npy') for i in name_list] label_path_list = [os.path.join(project_dir,'bs_value','bs_value_1114_' + i + '.npy') for i in name_list] data = np.zeros((1, 32, 64, 1)) label = np.zeros((1, 116)) for i in range(len(data_path_list)): data_temp = np.load(data_path_list[i]) label_temp = np.load(label_path_list[i]) if data_path_list[i][-8] == '1' or data_path_list[i][-8] == '2': label_temp_sum = label_temp.sum(axis=1) zero_index = np.where(label_temp_sum == 0)[0] half_zero_index = [zero_index[i] for i in range(0,len(zero_index),2)] select_index = [i for i in range(label_temp.shape[0]) if i not in half_zero_index] data_temp = data_temp[select_index] label_temp = label_temp[select_index] data = np.vstack((data,data_temp)) label = np.vstack((label,label_temp)) data = data[1:] label = label[1:] print(data.shape) print(label.shape) # label1 = np.zeros((label.shape[0],label.shape[1])) # bs_name_index = [0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 94, 93, 95, 96, 97, 98, 99, 100, 101, 102, 103, 105, 104, 106, 107, 108, 109, 110, 111, 112, 113, 114, 1, 115] # for i in range(len(bs_name_index)): # label1[:,i] = label[:,bs_name_index[i]] # label = label1 ############### select ############### # # bs的相关性计算 # import pandas as pd # df = pd.DataFrame(label,columns=bs_name) # corr = df.corr() #计算相关系数 # data = corr.values # print(data.shape) # bs_value_dict = {} # key:bs原始索引;value:与key的bs相关的min(bs_index) # for i in range(len(bs_name)): # bs_name_corr = corr[(corr[bs_name[i]]==1)].index.tolist() #与bs_name[i]极相关的bs_name。 0.99-0.995 33个;0.999 37个;0.9999 38个;1 41个 # if len(bs_name_corr)==0: # bs_value_dict[i] = i # else: # ndx = np.asarray([np.nonzero(bs_name == bs_name0)[0][0] for bs_name0 in bs_name_corr]) #返回索引 # bs_value_dict[i] = min(ndx) # print(bs_value_dict) # bs_index = list(set(list(bs_value_dict.values()))) # print('uncorr_bs_index: ',bs_index) # print('uncorr_bs_num: ',len(bs_index)) # # 筛选常值bs和变值bs # bs_max_value = np.amax(label, axis=0) #每个BS的最大值 # bs_min_value = np.amin(label, axis=0) #每个BS的最小值 # # print('bs_max_value: ',bs_max_value) # # print('bs_min_value: ',bs_min_value) # const_bs_index = np.where(bs_max_value-bs_min_value==0) #常数BS的索引 # const_bs_index = list(const_bs_index[0]) # print('const_bs_index: ',const_bs_index) # var_bs_index = [x for x in range(len(bs_name)) if x not in const_bs_index] #变值BS的索引 # print('var_bs_index: ',var_bs_index) # print('var_bs_index_len: ',len(var_bs_index)) # const_bs_value = label[0][const_bs_index] #值不变的BS其值 # print('const_bs_value: ',const_bs_value) # bs_name_1119_v1 # const_bs_index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 15, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33, 34, 35, 38, 45, 46, 47, 48, 49, 54, 55, 60, 61, 64, 69, 70, 71, 72, 82, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115] # var_bs_index = [9, 12, 13, 14, 17, 32, 36, 37, 39, 40, 41, 42, 43, 44, 50, 51, 52, 53, 56, 57, 58, 59, 62, 63, 65, 66, 67, 68, 73, 74, 75, 76, 77, 78, 79, 80, 81, 83] # const_bs_value = [0.,-0.,0.,-0.,0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,0.] # bs_name_1015_v1 # const_bs_index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 39, 46, 47, 48, 49, 50, 55, 56, 61, 62, 65, 70, 71, 72, 73, 83, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115] # var_bs_index = [10, 13, 14, 15, 18, 33, 38, 40, 41, 42, 43, 44, 45, 51, 52, 53, 54, 57, 58, 59, 60, 63, 64, 66, 67, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84] # const_bs_value = [0.,0.,-0.,0.,-0.,0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.] # bs_name_1119_v2 # const_bs_index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 15, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33, 34, 35, 38, 45, 46, 47, 48, 49, 54, 55, 60, 61, 64, 69, 70, 71, 72, 82, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115] # var_bs_index = [9, 12, 13, 14, 17, 32, 36, 37, 39, 40, 41, 42, 43, 44, 50, 51, 52, 53, 56, 57, 58, 59, 62, 63, 65, 66, 67, 68, 73, 74, 75, 76, 77, 78, 79, 80, 81, 83] # const_bs_value = [0.,-0.,0.,-0.,0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,0.] # bs_name_1015_v2 const_bs_index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 39, 46, 47, 48, 49, 50, 55, 56, 61, 62, 65, 70, 71, 72, 73, 83, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115] var_bs_index = [10, 13, 14, 15, 18, 33, 38, 40, 41, 42, 43, 44, 45, 51, 52, 53, 54, 57, 58, 59, 60, 63, 64, 66, 67, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84] const_bs_value = [0.,0.,-0.,0.,-0.,0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.] # 保存训练数据 train_data = data val_data = data[-1000:] train_label_var = label[:,var_bs_index] val_label_var = label[-1000:,var_bs_index] print(train_data.shape) print(val_data.shape) print(train_label_var.shape) print(val_label_var.shape) np.save(os.path.join(dataSet_dir,'train_data.npy'),train_data) np.save(os.path.join(dataSet_dir,'val_data.npy'),val_data) np.save(os.path.join(dataSet_dir,'train_label_var.npy'),train_label_var) np.save(os.path.join(dataSet_dir,'val_label_var.npy'),val_label_var)
0
0
0
813dc76915f7be023d1aaee161bea4b032cb7216
625
py
Python
PYTHON/python-datastructures/algorithms/algorithms/tree/same_tree.py
Web-Dev-Collaborative/DS-ALGO-OFFICIAL
6d7195d33c28a0fe22f12231efffb39f4bf05c97
[ "Apache-2.0" ]
11
2021-02-18T04:53:44.000Z
2022-01-16T10:57:39.000Z
PYTHON/python-datastructures/algorithms/algorithms/tree/same_tree.py
Web-Dev-Collaborative/DS-ALGO-OFFICIAL
6d7195d33c28a0fe22f12231efffb39f4bf05c97
[ "Apache-2.0" ]
162
2021-03-09T01:52:11.000Z
2022-03-12T01:09:07.000Z
PYTHON/python-datastructures/algorithms/algorithms/tree/same_tree.py
Web-Dev-Collaborative/DS-ALGO-OFFICIAL
6d7195d33c28a0fe22f12231efffb39f4bf05c97
[ "Apache-2.0" ]
8
2021-02-18T05:12:34.000Z
2022-03-06T19:02:14.000Z
""" Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value. """ # Time Complexity O(min(N,M)) # where N and M are the number of nodes for the trees. # Space Complexity O(min(height1, height2)) # levels of recursion is the mininum height between the two trees.
27.173913
78
0.7072
""" Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value. """ def is_same_tree(p, q): if p is None and q is None: return True if p is not None and q is not None and p.val == q.val: return is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right) return False # Time Complexity O(min(N,M)) # where N and M are the number of nodes for the trees. # Space Complexity O(min(height1, height2)) # levels of recursion is the mininum height between the two trees.
209
0
23
13fa11efd109514337d86b90e8118c53e07b013a
3,777
py
Python
src/server/server.py
CarlosJones/ADS-IDAC-SimPy
8fc1b3bf7c305e0d3cde5e626231d15ee7880f1c
[ "Apache-2.0" ]
null
null
null
src/server/server.py
CarlosJones/ADS-IDAC-SimPy
8fc1b3bf7c305e0d3cde5e626231d15ee7880f1c
[ "Apache-2.0" ]
null
null
null
src/server/server.py
CarlosJones/ADS-IDAC-SimPy
8fc1b3bf7c305e0d3cde5e626231d15ee7880f1c
[ "Apache-2.0" ]
null
null
null
from flask import Flask, render_template, jsonify, send_file import random, json, base64, os # import my_utils as utils import opt_db # 获取server.py当前路径,以及父路径、祖父路径 current_dir = os.path.dirname(__file__) parent_dir = os.path.dirname(current_dir) # 获得current_dir所在的目录, grandparent_dir = os.path.dirname(parent_dir) print("current_dir: ", current_dir) # print("parent_dir: ", parent_dir) # print("grandparent_dir: ", grandparent_dir) app = Flask( __name__, static_folder = parent_dir + "/client/static", template_folder = parent_dir + "/client/templates" ) app.jinja_env.auto_reload = True app.config['TEMPLATES_AUTO_RELOAD'] = True data0 = [ {'name': 'root', 'value': 10086,'children':[ {'name': 'A', 'value': 1, 'children': [{'name': 'C', 'value': 3}, {'name': 'D', 'value': 4}]}, {'name': 'B', 'value': 2, 'children': [{'name': 'E', 'value': 5}, {'name': 'F', 'value': 6}]} ]}] # dataIndex = [data0, data1, data2, data3] map_data0 = [{"lon": 122.226654,"lat": 31.210672}] map_data1 = [{"lon": 122.226654,"lat": 31.210672}, {"lon": 122.226654,"lat": 31.410672}] map_data2 = [{"lon": 122.226654,"lat": 31.210672}, {"lon": 122.226654,"lat": 31.410672}, {"lon": 122.426654,"lat": 31.210672}] map_data = [map_data0, map_data1, map_data2] # 根路由,首页页面 @app.route("/") # 英语版本的首页页面 @app.route("/en_version") # 网站入口 @app.route("/index") @app.route("/demo") # 初始加载的树数据,可删除之 @app.route("/tree") # 获取最新的仿真树data @app.route("/tree/first") # 获取最新的仿真树data @app.route("/tree/lastest") # 从数据库中查询指定TREEID的data并返回 @app.route("/tree/<treeid>") @app.route("/map") # 从数据库中查询指定VMID的data并返回 @app.route("/vm/<vmid>") @app.route("/img/<imageid>") @app.route("/sangji") if __name__ == "__main__": app.run(debug=True)
27.772059
126
0.664549
from flask import Flask, render_template, jsonify, send_file import random, json, base64, os # import my_utils as utils import opt_db # 获取server.py当前路径,以及父路径、祖父路径 current_dir = os.path.dirname(__file__) parent_dir = os.path.dirname(current_dir) # 获得current_dir所在的目录, grandparent_dir = os.path.dirname(parent_dir) print("current_dir: ", current_dir) # print("parent_dir: ", parent_dir) # print("grandparent_dir: ", grandparent_dir) app = Flask( __name__, static_folder = parent_dir + "/client/static", template_folder = parent_dir + "/client/templates" ) app.jinja_env.auto_reload = True app.config['TEMPLATES_AUTO_RELOAD'] = True data0 = [ {'name': 'root', 'value': 10086,'children':[ {'name': 'A', 'value': 1, 'children': [{'name': 'C', 'value': 3}, {'name': 'D', 'value': 4}]}, {'name': 'B', 'value': 2, 'children': [{'name': 'E', 'value': 5}, {'name': 'F', 'value': 6}]} ]}] # dataIndex = [data0, data1, data2, data3] def get_data(): # i = random.randint(0, 3) # return dataIndex[i] return data0 map_data0 = [{"lon": 122.226654,"lat": 31.210672}] map_data1 = [{"lon": 122.226654,"lat": 31.210672}, {"lon": 122.226654,"lat": 31.410672}] map_data2 = [{"lon": 122.226654,"lat": 31.210672}, {"lon": 122.226654,"lat": 31.410672}, {"lon": 122.426654,"lat": 31.210672}] map_data = [map_data0, map_data1, map_data2] def get_map_data(): i = random.randint(0, 2) return map_data[i] # 根路由,首页页面 @app.route("/") def index(): return render_template("view.html") # 英语版本的首页页面 @app.route("/en_version") def index_en(): return render_template("view-en.html") # 网站入口 @app.route("/index") def site_index(): return render_template("index.html") @app.route("/demo") def site_demo(): return render_template("demonstrate.html") # 初始加载的树数据,可删除之 @app.route("/tree") def get_tree(): return(jsonify({"data": get_data()})) # 获取最新的仿真树data @app.route("/tree/first") def get_first_tree(): data = opt_db.select_first_tree() return(jsonify({"TREEID": data[0], "TREEData": json.loads(data[1])})) # return opt_db.select_lastest_tree()[1] # 获取最新的仿真树data @app.route("/tree/lastest") def get_lastest_tree(): data = opt_db.select_lastest_tree() return(jsonify({"TREEID": data[0], "TREEData": json.loads(data[1])})) # return opt_db.select_lastest_tree()[1] # 从数据库中查询指定TREEID的data并返回 @app.route("/tree/<treeid>") def get_tree_by_id(treeid): data = opt_db.select_from_simtree(treeid)[1] # 此时是JSON格式的字符串 return data @app.route("/map") def get_map(): return(jsonify({"data": get_map_data()})) # 从数据库中查询指定VMID的data并返回 @app.route("/vm/<vmid>") def get_vm_by_id(vmid): simData = opt_db.select_from_simvm(vmid)[1] # 此时是JSON格式的字符串 if opt_db.select_from_dyntree(vmid) is not None: treeData = opt_db.select_from_dyntree(vmid)[1] simDic = json.loads(simData) treeDic = json.loads(treeData) dataDic = dict(simDic,**treeDic) data = json.dumps(dataDic) else: data = simData return data @app.route("/img/<imageid>") def img_index(imageid): # 方式1: 前端采用DOM操作img属性,采用http请求,后端从文件目录返回图片 # filename = grandparent_dir + "/res/VOImg/{}.png".format(imageid) # return send_file(filename, mimetype='image/png') # 方式2: 前端采用Ajax方式时,后端返回base64编码的字符串 # 1. 从本地加载一条数据 # with open("C:/Users/Bruce Lee/Documents/workspace/ADS-IDAC-SimPy/res/VOImg/{}.png".format(imageid), 'rb') as f: # b64 = base64.b64encode(f.read()) # return b64 # 2. 从数据库加载已经Base64编码的图片数据 # select_from_voimg返回结果格式为: data = (imgID, VMID, data) return opt_db.select_from_voimg(imageid)[2] @app.route("/sangji") def sangji(): return render_template("sangji.html") if __name__ == "__main__": app.run(debug=True)
1,895
0
308
6e362ef91948f6aafa98254180ef5e8f6a7e19f9
6,942
py
Python
pyconnectome/tests/tests_utils/test_filetools.py
neurospin/pyconnectome
971dfaf58895b61f4610934bd5434fb5a7062bfe
[ "CECILL-B" ]
5
2017-06-29T20:01:00.000Z
2019-12-18T13:41:45.000Z
pyconnectome/tests/tests_utils/test_filetools.py
neurospin/pyconnectome
971dfaf58895b61f4610934bd5434fb5a7062bfe
[ "CECILL-B" ]
16
2017-07-11T15:49:33.000Z
2018-11-16T09:04:03.000Z
pyconnectome/tests/tests_utils/test_filetools.py
neurospin/pyconnectome
971dfaf58895b61f4610934bd5434fb5a7062bfe
[ "CECILL-B" ]
10
2017-04-28T11:04:36.000Z
2020-02-11T10:47:07.000Z
########################################################################## # NSAp - Copyright (C) CEA, 2016 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html # for details. ########################################################################## # System import import unittest import sys # COMPATIBILITY: since python 3.3 mock is included in unittest module python_version = sys.version_info if python_version[:2] <= (3, 3): import mock from mock import patch mock_builtin = "__builtin__" else: import unittest.mock as mock from unittest.mock import patch mock_builtin = "builtins" # Package import from pyconnectome.utils.filetools import fslreorient2std, apply_mask class Fslreorient2std(unittest.TestCase): """ Test the FSL reorient the image to standard: 'pyconnectome.utils.filetools.fslreorient2std' """ def setUp(self): """ Run before each test - the mock_popen will be available and in the right state in every test<something> function. """ # Mocking popen self.popen_patcher = patch("pyconnectome.wrapper.subprocess.Popen") self.mock_popen = self.popen_patcher.start() mock_process = mock.Mock() attrs = { "communicate.return_value": ("mock_OK", "mock_NONE"), "returncode": 0 } mock_process.configure_mock(**attrs) self.mock_popen.return_value = mock_process # Mocking set environ self.env_patcher = patch( "pyconnectome.wrapper.FSLWrapper._fsl_version_check") self.mock_env = self.env_patcher.start() self.mock_env.return_value = {} # Define function parameters self.kwargs = { "input_image": "/my/path/mock_input_image", "output_image": "/my/path/mock_output_image", "save_trf": True, "fslconfig": "/my/path/mock_shfile", } def tearDown(self): """ Run after each test. """ self.popen_patcher.stop() self.env_patcher.stop() @mock.patch("pyconnectome.utils.filetools.os.path.isfile") def test_badfileerror_raise(self, mock_isfile): """Bad input file -> raise valueError. """ # Set the mocked functions returned values mock_isfile.side_effect = [False] # Test execution self.assertRaises(ValueError, fslreorient2std, **self.kwargs) @mock.patch("{0}.open".format(mock_builtin)) @mock.patch("numpy.savetxt") @mock.patch("pyconnectome.utils.filetools.flirt2aff") @mock.patch("pyconnectome.utils.filetools.glob.glob") @mock.patch("pyconnectome.utils.filetools.os.path.isfile") def test_normal_execution(self, mock_isfile, mock_glob, mock_aff, mock_savetxt, mock_open): """ Test the normal behaviour of the function. """ # Set the mocked function returned values. mock_isfile.side_effect = [True] mock_glob.return_value = ["/my/path/mock_output"] mock_context_manager = mock.Mock() mock_open.return_value = mock_context_manager mock_file = mock.Mock() mock_file.read.return_value = "WRONG" mock_enter = mock.Mock() mock_enter.return_value = mock_file mock_exit = mock.Mock() setattr(mock_context_manager, "__enter__", mock_enter) setattr(mock_context_manager, "__exit__", mock_exit) mock_aff.flirt2aff.return_value = "" # Test execution fslreorient2std(**self.kwargs) self.assertEqual([ mock.call(["which", "fslreorient2std"], env={}, stderr=-1, stdout=-1), mock.call(["fslreorient2std", self.kwargs["input_image"], self.kwargs["output_image"] + ".nii.gz"], cwd=None, env={}, stderr=-1, stdout=-1), mock.call(["which", "fslreorient2std"], env={}, stderr=-1, stdout=-1), mock.call(["fslreorient2std", self.kwargs["input_image"]], cwd=None, env={}, stderr=-1, stdout=-1)], self.mock_popen.call_args_list) self.assertEqual(len(self.mock_env.call_args_list), 1) class FslApplyMask(unittest.TestCase): """ Test the FSL apply mask: 'pyconnectome.utils.filetools.apply_mask' """ def setUp(self): """ Run before each test - the mock_popen will be available and in the right state in every test<something> function. """ # Mocking popen self.popen_patcher = patch("pyconnectome.wrapper.subprocess.Popen") self.mock_popen = self.popen_patcher.start() mock_process = mock.Mock() attrs = { "communicate.return_value": ("mock_OK", "mock_NONE"), "returncode": 0 } mock_process.configure_mock(**attrs) self.mock_popen.return_value = mock_process # Mocking set environ self.env_patcher = patch( "pyconnectome.wrapper.FSLWrapper._fsl_version_check") self.mock_env = self.env_patcher.start() self.mock_env.return_value = {} # Define function parameters self.kwargs = { "input_file": "/my/path/mock_input_file", "mask_file": "/my/path/mock_mask_file", "output_fileroot": "/my/path/mock_output_fileroot", "fslconfig": "/my/path/mock_shfile", } def tearDown(self): """ Run after each test. """ self.popen_patcher.stop() self.env_patcher.stop() def test_badfileerror_raise(self): """Bad input file -> raise valueError. """ # Test execution self.assertRaises(ValueError, apply_mask, **self.kwargs) @mock.patch("pyconnectome.utils.filetools.glob.glob") @mock.patch("pyconnectome.utils.filetools.os.path.isfile") def test_normal_execution(self, mock_isfile, mock_glob): """ Test the normal behaviour of the function. """ # Set the mocked function returned values. mock_isfile.side_effect = [True, True] mock_glob.return_value = ["/my/path/mock_output"] # Test execution apply_mask(**self.kwargs) self.assertEqual([ mock.call(["which", "fslmaths"], env={}, stderr=-1, stdout=-1), mock.call(["fslmaths", self.kwargs["input_file"], "-mas", self.kwargs["mask_file"], self.kwargs["output_fileroot"]], cwd=None, env={}, stderr=-1, stdout=-1)], self.mock_popen.call_args_list) self.assertEqual(len(self.mock_env.call_args_list), 1) if __name__ == "__main__": unittest.main()
36.536842
78
0.597378
########################################################################## # NSAp - Copyright (C) CEA, 2016 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html # for details. ########################################################################## # System import import unittest import sys # COMPATIBILITY: since python 3.3 mock is included in unittest module python_version = sys.version_info if python_version[:2] <= (3, 3): import mock from mock import patch mock_builtin = "__builtin__" else: import unittest.mock as mock from unittest.mock import patch mock_builtin = "builtins" # Package import from pyconnectome.utils.filetools import fslreorient2std, apply_mask class Fslreorient2std(unittest.TestCase): """ Test the FSL reorient the image to standard: 'pyconnectome.utils.filetools.fslreorient2std' """ def setUp(self): """ Run before each test - the mock_popen will be available and in the right state in every test<something> function. """ # Mocking popen self.popen_patcher = patch("pyconnectome.wrapper.subprocess.Popen") self.mock_popen = self.popen_patcher.start() mock_process = mock.Mock() attrs = { "communicate.return_value": ("mock_OK", "mock_NONE"), "returncode": 0 } mock_process.configure_mock(**attrs) self.mock_popen.return_value = mock_process # Mocking set environ self.env_patcher = patch( "pyconnectome.wrapper.FSLWrapper._fsl_version_check") self.mock_env = self.env_patcher.start() self.mock_env.return_value = {} # Define function parameters self.kwargs = { "input_image": "/my/path/mock_input_image", "output_image": "/my/path/mock_output_image", "save_trf": True, "fslconfig": "/my/path/mock_shfile", } def tearDown(self): """ Run after each test. """ self.popen_patcher.stop() self.env_patcher.stop() @mock.patch("pyconnectome.utils.filetools.os.path.isfile") def test_badfileerror_raise(self, mock_isfile): """Bad input file -> raise valueError. """ # Set the mocked functions returned values mock_isfile.side_effect = [False] # Test execution self.assertRaises(ValueError, fslreorient2std, **self.kwargs) @mock.patch("{0}.open".format(mock_builtin)) @mock.patch("numpy.savetxt") @mock.patch("pyconnectome.utils.filetools.flirt2aff") @mock.patch("pyconnectome.utils.filetools.glob.glob") @mock.patch("pyconnectome.utils.filetools.os.path.isfile") def test_normal_execution(self, mock_isfile, mock_glob, mock_aff, mock_savetxt, mock_open): """ Test the normal behaviour of the function. """ # Set the mocked function returned values. mock_isfile.side_effect = [True] mock_glob.return_value = ["/my/path/mock_output"] mock_context_manager = mock.Mock() mock_open.return_value = mock_context_manager mock_file = mock.Mock() mock_file.read.return_value = "WRONG" mock_enter = mock.Mock() mock_enter.return_value = mock_file mock_exit = mock.Mock() setattr(mock_context_manager, "__enter__", mock_enter) setattr(mock_context_manager, "__exit__", mock_exit) mock_aff.flirt2aff.return_value = "" # Test execution fslreorient2std(**self.kwargs) self.assertEqual([ mock.call(["which", "fslreorient2std"], env={}, stderr=-1, stdout=-1), mock.call(["fslreorient2std", self.kwargs["input_image"], self.kwargs["output_image"] + ".nii.gz"], cwd=None, env={}, stderr=-1, stdout=-1), mock.call(["which", "fslreorient2std"], env={}, stderr=-1, stdout=-1), mock.call(["fslreorient2std", self.kwargs["input_image"]], cwd=None, env={}, stderr=-1, stdout=-1)], self.mock_popen.call_args_list) self.assertEqual(len(self.mock_env.call_args_list), 1) class FslApplyMask(unittest.TestCase): """ Test the FSL apply mask: 'pyconnectome.utils.filetools.apply_mask' """ def setUp(self): """ Run before each test - the mock_popen will be available and in the right state in every test<something> function. """ # Mocking popen self.popen_patcher = patch("pyconnectome.wrapper.subprocess.Popen") self.mock_popen = self.popen_patcher.start() mock_process = mock.Mock() attrs = { "communicate.return_value": ("mock_OK", "mock_NONE"), "returncode": 0 } mock_process.configure_mock(**attrs) self.mock_popen.return_value = mock_process # Mocking set environ self.env_patcher = patch( "pyconnectome.wrapper.FSLWrapper._fsl_version_check") self.mock_env = self.env_patcher.start() self.mock_env.return_value = {} # Define function parameters self.kwargs = { "input_file": "/my/path/mock_input_file", "mask_file": "/my/path/mock_mask_file", "output_fileroot": "/my/path/mock_output_fileroot", "fslconfig": "/my/path/mock_shfile", } def tearDown(self): """ Run after each test. """ self.popen_patcher.stop() self.env_patcher.stop() def test_badfileerror_raise(self): """Bad input file -> raise valueError. """ # Test execution self.assertRaises(ValueError, apply_mask, **self.kwargs) @mock.patch("pyconnectome.utils.filetools.glob.glob") @mock.patch("pyconnectome.utils.filetools.os.path.isfile") def test_normal_execution(self, mock_isfile, mock_glob): """ Test the normal behaviour of the function. """ # Set the mocked function returned values. mock_isfile.side_effect = [True, True] mock_glob.return_value = ["/my/path/mock_output"] # Test execution apply_mask(**self.kwargs) self.assertEqual([ mock.call(["which", "fslmaths"], env={}, stderr=-1, stdout=-1), mock.call(["fslmaths", self.kwargs["input_file"], "-mas", self.kwargs["mask_file"], self.kwargs["output_fileroot"]], cwd=None, env={}, stderr=-1, stdout=-1)], self.mock_popen.call_args_list) self.assertEqual(len(self.mock_env.call_args_list), 1) if __name__ == "__main__": unittest.main()
0
0
0
68e509d660f474b4770cd3f8cfadd6abdc34ecad
1,208
py
Python
src/main.py
arslee07/OpenTextAI
4b11e721a0e3d32e488a17d524564c3f08973bf2
[ "MIT" ]
3
2020-09-27T14:52:48.000Z
2020-10-15T06:42:54.000Z
src/main.py
arslee07/OpenTextAI
4b11e721a0e3d32e488a17d524564c3f08973bf2
[ "MIT" ]
1
2021-08-20T06:29:55.000Z
2021-08-22T10:37:34.000Z
src/main.py
arslee07/OpenTextAI
4b11e721a0e3d32e488a17d524564c3f08973bf2
[ "MIT" ]
4
2020-08-29T13:26:30.000Z
2020-10-12T12:18:07.000Z
import json from os.path import abspath, dirname import discord import os from discord.ext import commands from discord.ext.commands import Bot from cogs.Utils import Utils with open(dirname(abspath(__file__)) + '/data/locales.json') as f: locales = json.load(f) with open(dirname(abspath(__file__)) + '/data/config.json') as f: config = json.load(f) bot = Bot(command_prefix=config['default_prefix'], help_command=None) filepath = dirname(abspath(__file__)) @bot.event @bot.event bot.run(config['token'])
26.26087
114
0.688742
import json from os.path import abspath, dirname import discord import os from discord.ext import commands from discord.ext.commands import Bot from cogs.Utils import Utils with open(dirname(abspath(__file__)) + '/data/locales.json') as f: locales = json.load(f) with open(dirname(abspath(__file__)) + '/data/config.json') as f: config = json.load(f) bot = Bot(command_prefix=config['default_prefix'], help_command=None) filepath = dirname(abspath(__file__)) @bot.event async def on_ready(): for filename in os.listdir(filepath + '/cogs/'): if filename.endswith('.py'): bot.load_extension('cogs.{0}'.format(filename[:-3])) print('Ready!') @bot.event async def on_guild_join(guild): embed = discord.Embed(color=0x6cdbe0, title='**OpenTextAI**', description=locales['ru_RU']['etc']['on_join_message']) embed.set_thumbnail( url='https://cdn.discordapp.com/avatars/748543469001244813/45d8aa6c9e33329de6a78519cbef4b4a.png?size=256') for channel in guild.text_channels: if channel.permissions_for(guild.me).send_messages: await channel.send(embed=embed) break bot.run(config['token'])
636
0
44
f5c164ec8baafb11a24a62a24eefd66a42153c4a
3,214
py
Python
modules/multi_feature_embedding.py
Aria-K-Alethia/X-NLP
c5244ba3315c08d91d8747f186f0491eb79eb1d2
[ "MIT" ]
2
2020-12-17T07:42:29.000Z
2022-03-07T01:11:54.000Z
modules/multi_feature_embedding.py
Aria-K-Alethia/X-NLP
c5244ba3315c08d91d8747f186f0491eb79eb1d2
[ "MIT" ]
null
null
null
modules/multi_feature_embedding.py
Aria-K-Alethia/X-NLP
c5244ba3315c08d91d8747f186f0491eb79eb1d2
[ "MIT" ]
1
2022-03-30T05:37:25.000Z
2022-03-30T05:37:25.000Z
''' Copyright (c) 2019 Aria-K-Alethia@github.com Description: embedding class supporting multiple features and customized merge method Licence: MIT THE USER OF THIS CODE AGREES TO ASSUME ALL LIABILITY FOR THE USE OF THIS CODE. Any use of this code should display all the info above. ''' import torch import torch.nn as nn from embedding import Embedding from mlp import MLP class MultiFeatureEmbedding(nn.Module): """ overview: for nlp, support multiple feature and customized merge methods params: vocab_sizes: vocab size for each feature embedding_dims: embedding dim for each feature merge_methods: merge method for each feature currently support 'cat', 'sum' out_method: support 'none', 'linear', 'mlp' out_dim: output dimension """ def forward(self, x): ''' overview: forward method params: x: [#batch, #len, #n_feature] ''' # get embedding for each feature outs = [] for emb, f in enumerate(zip(self.emb_list, x.split(1, -1))): outs.append(emb(f.squeeze(-1))) # merge # cat cat = [emb for index, emb in enumerate(outs)\ if self.merge_methods[index] == 'cat'] out = torch.cat(cat, -1) # sum sum_ = [emb for index, emb in enumerate(outs)\ if self.merge_methods[index] == 'sum'] [out.add_(item) for item in sum_] if self.output_method != 'none': out = self.out_module(out) return out @property @property @property @property @property @property @property @property
27.470085
80
0.680149
''' Copyright (c) 2019 Aria-K-Alethia@github.com Description: embedding class supporting multiple features and customized merge method Licence: MIT THE USER OF THIS CODE AGREES TO ASSUME ALL LIABILITY FOR THE USE OF THIS CODE. Any use of this code should display all the info above. ''' import torch import torch.nn as nn from embedding import Embedding from mlp import MLP class MultiFeatureEmbedding(nn.Module): """ overview: for nlp, support multiple feature and customized merge methods params: vocab_sizes: vocab size for each feature embedding_dims: embedding dim for each feature merge_methods: merge method for each feature currently support 'cat', 'sum' out_method: support 'none', 'linear', 'mlp' out_dim: output dimension """ def __init__(self, vocab_sizes, embedding_dims, merge_methods, padding_indices, fix_embedding, out_method = 'none', out_dim = None): super(MultiFeatureEmbedding, self).__init__() self._vocab_sizes = vocab_sizes self._embedding_dims = embedding_dims self._n_feature = len(vocab_sizes) self._merge_methods = merge_methods self._padding_indices = padding_indices self._fix_embedding = fix_embedding self.emb_list = nn.ModuleList(Embedding( vocab_size, embedding_dim, padding_idx, fix_embedding) for vocab_size, embedding_dim, padding_idx in zip(vocab_sizes, embedding_dims, padding_indices)) self._out_method = out_method self._emb_out_dim = sum(dim for index, dim in enumerate(embedding_dims) if merge_methods[index] == 'cat') if out_method == 'none': self._out_dim = self._emb_out_dim elif out_method == 'linear': self._out_dim = out_dim self.out_module = nn.Linear(self._emb_out_dim, self._out_dim) else: self._out_dim = out_dim self.out_module = MLP(self._emb_out_dim, [int(self._emb_out_dim / 2), self._out_dim], ['prelu', 'prelu']) def forward(self, x): ''' overview: forward method params: x: [#batch, #len, #n_feature] ''' # get embedding for each feature outs = [] for emb, f in enumerate(zip(self.emb_list, x.split(1, -1))): outs.append(emb(f.squeeze(-1))) # merge # cat cat = [emb for index, emb in enumerate(outs)\ if self.merge_methods[index] == 'cat'] out = torch.cat(cat, -1) # sum sum_ = [emb for index, emb in enumerate(outs)\ if self.merge_methods[index] == 'sum'] [out.add_(item) for item in sum_] if self.output_method != 'none': out = self.out_module(out) return out @property def vocab_sizes(self): return self._vocab_sizes @property def embedding_dims(self): return self._embedding_dims @property def n_feature(self): return self._n_feature @property def merge_methods(self): return self._merge_methods @property def fix_embedding(self): return self._fix_embedding @property def output_method(self): return self._out_method @property def embedding_output_dim(self): return self._emb_out_dim @property def output_dim(self): return self._out_dim
1,437
0
216
f9aa762366cd530a26a5be423b551c2a03c3d8ba
2,590
py
Python
musicsite/musicapp/migrations/0001_initial.py
andylwilson/Timbrespoon
02a6c60866e8f55e787b6a701a3af38d9c4d61b3
[ "Apache-2.0" ]
null
null
null
musicsite/musicapp/migrations/0001_initial.py
andylwilson/Timbrespoon
02a6c60866e8f55e787b6a701a3af38d9c4d61b3
[ "Apache-2.0" ]
null
null
null
musicsite/musicapp/migrations/0001_initial.py
andylwilson/Timbrespoon
02a6c60866e8f55e787b6a701a3af38d9c4d61b3
[ "Apache-2.0" ]
null
null
null
# Generated by Django 2.2 on 2019-06-06 09:02 from django.conf import settings from django.db import migrations, models import django.db.models.deletion
37
114
0.550193
# Generated by Django 2.2 on 2019-06-06 09:02 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Album', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('albumname', models.CharField(max_length=255)), ('artist', models.CharField(max_length=255)), ('issueyear', models.SmallIntegerField()), ('tracks', models.SmallIntegerField()), ], options={ 'verbose_name_plural': 'albums', 'db_table': 'album', }, ), migrations.CreateModel( name='Genre', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('genrename', models.CharField(max_length=255)), ('genredescription', models.TextField(blank=True, null=True)), ], options={ 'verbose_name_plural': 'genres', 'db_table': 'genre', }, ), migrations.CreateModel( name='Review', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('reviewtitle', models.CharField(max_length=255)), ('reviewdate', models.DateField()), ('rating', models.SmallIntegerField()), ('reviewtext', models.TextField()), ('album', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='musicapp.Album')), ('user', models.ManyToManyField(to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name_plural': 'reviews', 'db_table': 'review', }, ), migrations.AddField( model_name='album', name='genre', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='musicapp.Genre'), ), migrations.AddField( model_name='album', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL), ), ]
0
2,412
23
156684c33cf3fe578d5c2aa36b68dfc7423d63ed
2,982
py
Python
spectralcluster/refinement.py
dschlessman/SpectralCluster
2a34ce68c44fdef63a35fd9b07742a53f3768301
[ "Apache-2.0" ]
3
2020-07-27T18:11:26.000Z
2021-08-04T10:18:07.000Z
spectralcluster/refinement.py
dschlessman/SpectralCluster
2a34ce68c44fdef63a35fd9b07742a53f3768301
[ "Apache-2.0" ]
null
null
null
spectralcluster/refinement.py
dschlessman/SpectralCluster
2a34ce68c44fdef63a35fd9b07742a53f3768301
[ "Apache-2.0" ]
2
2020-02-16T07:52:13.000Z
2021-08-04T10:18:51.000Z
from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc from scipy.ndimage import gaussian_filter import numpy as np class CropDiagonal(AffinityRefinementOperation): """Crop the diagonal. Replace diagonal element by the max value of row. We do this because the diagonal will bias Gaussian blur and normalization. """ class GaussianBlur(AffinityRefinementOperation): """Apply Gaussian blur.""" class RowWiseThreshold(AffinityRefinementOperation): """Apply row wise thresholding.""" class Symmetrize(AffinityRefinementOperation): """The Symmetrization operation.""" class Diffuse(AffinityRefinementOperation): """The diffusion operation.""" class RowWiseNormalize(AffinityRefinementOperation): """The row wise max normalization operation."""
27.869159
78
0.607646
from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc from scipy.ndimage import gaussian_filter import numpy as np class AffinityRefinementOperation(metaclass=abc.ABCMeta): def check_input(self, X): """Check the input to the refine() method. Args: X: the input to the refine() method Raises: TypeError: if X has wrong type ValueError: if X has wrong shape, etc. """ if not isinstance(X, np.ndarray): raise TypeError("X must be a numpy array") shape = X.shape if len(shape) != 2: raise ValueError("X must be 2-dimensional") if shape[0] != shape[1]: raise ValueError("X must be a square matrix") @abc.abstractmethod def refine(self, X): """Perform the refinement operation. Args: X: the affinity matrix, of size (n_samples, n_samples) Returns: a matrix of the same size as X """ pass class CropDiagonal(AffinityRefinementOperation): """Crop the diagonal. Replace diagonal element by the max value of row. We do this because the diagonal will bias Gaussian blur and normalization. """ def refine(self, X): self.check_input(X) Y = np.copy(X) np.fill_diagonal(Y, 0.0) for r in range(Y.shape[0]): Y[r, r] = Y[r, :].max() return Y class GaussianBlur(AffinityRefinementOperation): """Apply Gaussian blur.""" def __init__(self, sigma=1): self.sigma = sigma def refine(self, X): self.check_input(X) return gaussian_filter(X, sigma=self.sigma) class RowWiseThreshold(AffinityRefinementOperation): """Apply row wise thresholding.""" def __init__(self, p_percentile=0.95, thresholding_soft_multiplier=0.01): self.p_percentile = p_percentile self.multiplier = thresholding_soft_multiplier def refine(self, X): self.check_input(X) Y = np.copy(X) for r in range(Y.shape[0]): row_max = Y[r, :].max() for c in range(Y.shape[1]): if Y[r, c] < row_max * self.p_percentile: Y[r, c] *= self.multiplier return Y class Symmetrize(AffinityRefinementOperation): """The Symmetrization operation.""" def refine(self, X): self.check_input(X) return np.maximum(X, np.transpose(X)) class Diffuse(AffinityRefinementOperation): """The diffusion operation.""" def refine(self, X): self.check_input(X) return np.matmul(X, np.transpose(X)) class RowWiseNormalize(AffinityRefinementOperation): """The row wise max normalization operation.""" def refine(self, X): self.check_input(X) Y = np.copy(X) for r in range(Y.shape[0]): row_max = Y[r, :].max() Y[r, :] /= row_max return Y
1,032
862
233
fde7595530c64dd530fab0b12d9fd8dffb1e6135
80,930
py
Python
eeg_analyses/EEG.py
dvanmoorselaar/DvM
b097f6d2532a6a1285ae63585a7ce0c966a05039
[ "MIT" ]
7
2018-03-22T10:44:55.000Z
2021-08-25T01:18:17.000Z
eeg_analyses/EEG.py
dvanmoorselaar/DvM
b097f6d2532a6a1285ae63585a7ce0c966a05039
[ "MIT" ]
3
2018-03-19T14:24:08.000Z
2019-02-20T19:11:08.000Z
eeg_analyses/EEG.py
dvanmoorselaar/DvM
b097f6d2532a6a1285ae63585a7ce0c966a05039
[ "MIT" ]
7
2018-04-04T14:55:43.000Z
2021-11-15T15:40:15.000Z
""" analyze EEG data Created by Dirk van Moorselaar on 10-03-2015. Copyright (c) 2015 DvM. All rights reserved. """ import mne import os import logging import itertools import pickle import copy import glob import sys import time import itertools import numpy as np import scipy as sp import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from matplotlib import cm from scipy.stats import zscore from typing import Optional, Generic, Union, Tuple, Any from termios import tcflush, TCIFLUSH from eeg_analyses.EYE import * from math import sqrt from IPython import embed from support.FolderStructure import * from scipy.stats.stats import pearsonr from mne.viz.epochs import plot_epochs_image from mne.filter import filter_data from mne.preprocessing import ICA from mne.preprocessing import create_eog_epochs, create_ecg_epochs from math import ceil, floor from autoreject import Ransac, AutoReject class RawBDF(mne.io.edf.edf.RawEDF, FolderStructure): ''' Child originating from MNE built-in RawEDF, such that new methods can be added to this built in class ''' def report_raw(self, report, events, event_id): ''' ''' # report raw report.add_raw(self, title='raw EEG', psd=True ) # and events events = events[np.in1d(events[:,2], event_id)] report.add_events(events, title = 'detected events', sfreq = self.info['sfreq']) return report def replaceChannel(self, sj, session, replace): ''' Replace bad electrodes by electrodes that were used during recording as a replacement Arguments - - - - - raw (object): raw mne eeg object sj (int): subject_nr session (int): eeg session number replace (dict): dictionary containing to be replaced electrodes per subject and session Returns - - - - self(object): raw object with bad electrodes replaced ''' sj = str(sj) session = 'session_{}'.format(session) if sj in replace.keys(): if session in replace[sj].keys(): to_replace = replace[sj][session].keys() for e in to_replace: self._data[self.ch_names.index(e), :] = self._data[ self.ch_names.index(replace[sj][session][e]), :] # print('Electrode {0} replaced by # {1}'.format(e,replace[sj][session][e])) def reReference(self, ref_channels=['EXG5', 'EXG6'], vEOG=['EXG1', 'EXG2'], hEOG=['EXG3', 'EXG4'], changevoltage=True, to_remove = ['EXG7','EXG8']): ''' Rereference raw data to reference channels. By default data is rereferenced to the mastoids. Also EOG data is rerefenced. Subtraction of VEOG and HEOG results in a VEOG and an HEOG channel. After rereferencing redundant channels are removed. Functions assumes that there are 2 vEOG and 2 hEOG channels. Arguments - - - - - self(object): RawBDF object ref_channels (list): list with channels for rerefencing vEOG (list): list with vEOG channels hEOG (list): list with hEOG channels changevoltage (bool): remove(bool): Specify whether channels need to be removed Returns - - - - self (object): Rereferenced raw eeg data ''' # change data format from Volts to microVolts if changevoltage: self._data[:-1, :] *= 1e6 print('Volts changed to microvolts') logging.info('Volts changed to microvolts') # rereference all EEG channels to reference channels self.set_eeg_reference(ref_channels=ref_channels) to_remove += ref_channels print('EEG data was rereferenced to channels {}'.format(ref_channels)) logging.info( 'EEG data was rereferenced to channels {}'.format(ref_channels)) # select eog channels eog = self.copy().pick_types(eeg=False, eog=True) # # rerefence EOG data (vertical and horizontal) # idx_v = [eog.ch_names.index(vert) for vert in vEOG] # idx_h = [eog.ch_names.index(hor) for hor in hEOG] # if len(idx_v) == 2: # eog._data[idx_v[0]] -= eog._data[idx_v[1]] # if len(idx_h) == 2: # eog._data[idx_h[0]] -= eog._data[idx_h[1]] # print( # 'EOG data (VEOG, HEOG) rereferenced with subtraction and renamed EOG channels') # logging.info( # 'EOG data (VEOG, HEOG) rereferenced with subtraction and renamed EOG channels') # # add rereferenced vEOG and hEOG data to self # ch_mapping = {vEOG[0]: 'VEOG', hEOG[0]: 'HEOG'} # eog.rename_channels(ch_mapping) # eog.drop_channels([vEOG[1], hEOG[1]]) # #self.add_channels([eog]) # drop ref chans self.drop_channels(to_remove) print('Reference channels and empty channels removed') logging.info('Reference channels and empty channels removed') def setMontage(self, montage='biosemi64', ch_remove = []): ''' Uses mne function to set the specified montage. Also changes channel labels from A, B etc naming scheme to standard naming conventions and removes specified channels. At the same time changes the name of EOG electrodes (assumes an EXG naming scheme) Arguments - - - - - raw (object): raw mne eeg object montage (str): used montage during recording ch_remove (list): channels that you want to exclude from analysis (e.g heart rate) Returns - - - - self(object): raw object with changed channel names following biosemi 64 naming scheme (10 - 20 system) ''' # drop channels and get montage self.drop_channels(ch_remove) # create mapping dictionary idx = 0 ch_mapping = {} if self.ch_names[0] == 'A1': for hemi in ['A', 'B']: for electr in range(1, 33): ch_mapping.update( {'{}{}'.format(hemi, electr): montage.ch_names[idx]}) idx += 1 self.rename_channels(ch_mapping) self.set_montage(montage=montage) print('Channels renamed to 10-20 system, and montage added') logging.info('Channels renamed to 10-20 system, and montage added') def eventSelection(self, trigger, binary=0, consecutive=False, min_duration=0.003): ''' Returns array of events necessary for epoching. Arguments - - - - - raw (object): raw mne eeg object binary (int): is subtracted from stim channel to control for spoke triggers (e.g. subtracts 3840) Returns - - - - events(array): numpy array with trigger events (first column contains the event time in samples and the third column contains the event id) ''' self._data[-1, :] -= binary # Make universal events = mne.find_events(self, stim_channel=None, consecutive=consecutive, min_duration=min_duration) # Check for consecutive if not consecutive: spoke_idx = [] for i in range(events[:-1,2].size): if events[i,2] == events[i + 1,2] and events[i,2] in trigger: spoke_idx.append(i) events = np.delete(events,spoke_idx,0) logging.info('{} spoke events removed from event file'.format(len(spoke_idx))) return events def matchBeh(self, sj, session, events, event_id, trigger_header = 'trigger', headers = []): ''' Alligns bdf file with csv file with experimental variables Arguments - - - - - raw (object): raw mne eeg object sj (int): sj number session(int): session number events(array): event file from eventSelection (last column contains trigger values) trigger(list|array): trigger values used for epoching headers (list): relevant column names from behavior file Returns - - - - beh (object): panda object with behavioral data (triggers are alligned) missing (araray): array of missing trials (can be used when selecting eyetracking data) ''' # read in data file beh_file = self.FolderTracker(extension=[ 'beh', 'raw'], filename='subject-{}_session_{}.csv'.format(sj, session)) # get triggers logged in beh file beh = pd.read_csv(beh_file) beh = beh[headers] if 'practice' in headers: beh = beh[beh['practice'] == 'no'] beh = beh.drop(['practice'], axis=1) beh_triggers = beh[trigger_header].values # get triggers bdf file if type(event_id) == dict: event_id = [event_id[key] for key in event_id.keys()] idx_trigger = [idx for idx, tr in enumerate(events[:,2]) if tr in event_id] bdf_triggers = events[idx_trigger,2] # log number of unique triggers unique = np.unique(bdf_triggers) logging.info('{} detected unique triggers (min = {}, max = {})'. format(unique.size, unique.min(), unique.max())) # make sure trigger info between beh and bdf data matches missing_trials = [] nr_miss = beh_triggers.size - bdf_triggers.size logging.info('{} trials will be removed from beh file'.format(nr_miss)) # check whether trial info is present in beh file if nr_miss > 0 and 'nr_trials' not in beh.columns: raise ValueError('Behavior file does not contain a column with trial info named nr_trials. Please adjust') while nr_miss > 0: stop = True # continue to remove beh trials until data files are lined up for i, tr in enumerate(bdf_triggers): if tr != beh_triggers[i]: # remove trigger from beh_file miss = beh['nr_trials'].iloc[i] #print miss missing_trials.append(miss) logging.info('Removed trial {} from beh file,because no matching trigger exists in bdf file'.format(miss)) beh.drop(beh.index[i], inplace=True) beh_triggers = np.delete(beh_triggers, i, axis = 0) nr_miss -= 1 stop = False break # check whether there are missing trials at end of beh file if beh_triggers.size > bdf_triggers.size and stop: # drop the last items from the beh file missing_trials = np.hstack((missing_trials, beh['nr_trials'].iloc[-nr_miss:].values)) beh.drop(beh.index[-nr_miss:], inplace=True) logging.info('Removed last {} trials because no matches detected'.format(nr_miss)) nr_miss = 0 # keep track of missing trials to allign eye tracking data (if available) missing = np.array(missing_trials) # log number of matches between beh and bdf logging.info('{} matches between beh and epoched data out of {}'. format(sum(beh[trigger_header].values == bdf_triggers), bdf_triggers.size)) return beh, missing class Epochs(mne.Epochs, FolderStructure): ''' Child originating from MNE built-in Epochs, such that new methods can be added to this built in class ''' def align_behavior(self, events: np.array, trigger_header: str = 'trigger', headers: list = [], bdf_remove: np.array = None): """ Aligns bdf file with csv file with experimental variables. In case there are more behavioral trials than eeg trials (e.g., because trigger was not properly sent/detected), trials are removed from the raw behavioral data such that both datasets are aligned. Information about this process can be found in individual preprocessing log files. Args: events (np.array): event info as returned by RAW.event_selection trigger_header (str, optional): Column in raw behavior that contains trigger values used for epoching. Defaults to 'trigger'. headers (list, optional): List of headers that should be linked to eeg data. Defaults to []. bdf_remove (np.array, optional): Indices of trigger events that need to be removed. Only specify when to many trials are recorded. Raises: ValueError: In case behavior and eeg data do not align (i.e., contain different trial numbers). If there are more behavior trials than epochs, raises an error in case there is no column 'nr_trials', which prevents informed alignment of eeg and behavior. Also raises an error if there are too many epochs and automatic allignment fails Returns: beh (pd.DataFrame): Behavior data after aligning to eeg data (index is reset) missing (np.array): array with trials that are removed from beh because no matching trigger was detected. Is used when aligning eyetracker data (where it is assumed that eyetracking data and raw behavior contain the same number of trials) """ print('Linking behavior to eeg data') report_str = '' # read in data file beh_file = self.FolderTracker(extension=[ 'beh', 'raw'], filename='subject-{}_session_{}.csv'.format(self.sj, self.session)) # get triggers logged in beh file beh = pd.read_csv(beh_file) beh = beh[headers] if 'practice' in headers: print('{} practice trials removed from behavior'.format(beh[beh.practice == 'yes'].shape[0])) #logging.info('{} practice trials removed from behavior'.format(beh[beh.practice == 'yes'].shape[0])) beh = beh[beh.practice == 'no'] beh = beh.drop(['practice'], axis=1) beh_triggers = beh[trigger_header].values # get eeg triggers in epoched order () bdf_triggers = events[self.selection, 2] if bdf_remove is not None: self.drop(bdf_remove) report_str += '{} bdf triggers removed as specified by the user \n'.format(bdf_remove.size) #logging.info('{} bdf triggers and epochs removed as specified by the user'.format(bdf_remove.size)) bdf_triggers = np.delete(bdf_triggers, bdf_remove) # log number of unique triggers #unique = np.unique(bdf_triggers) #logging.info('{} detected unique triggers (min = {}, max = {})'. # format(unique.size, unique.min(), unique.max())) # make sure trigger info between beh and bdf data matches missing_trials = [] nr_miss = beh_triggers.size - bdf_triggers.size #logging.info(f'{nr_miss} trials will be removed from beh file') if nr_miss > 0: report_str += f'Behavior has {nr_miss} more trials than detected events. The following trial numbers \ will be removed in attempt to fix this: \n' # check whether trial info is present in beh file if nr_miss > 0 and 'nr_trials' not in beh.columns: raise ValueError('Behavior file does not contain a column with trial info named nr_trials. Please adjust') elif nr_miss < 0: report_str += 'EEG events are removed in an attempt to align the data. Please inspect your data carefully! \n' while nr_miss < 0: # continue to remove bdf triggers until data files are lined up for i, tr in enumerate(beh_triggers): if tr != bdf_triggers[i]: # remove trigger from eeg_file bdf_triggers = np.delete(bdf_triggers, i, axis = 0) nr_miss += 1 # check file sizes if sum(beh_triggers == bdf_triggers) < bdf_triggers.size: raise ValueError('Behavior and eeg cannot be linked as too many eeg triggers received. Please pass indices of trials to be removed \ to subject_info dict with key bdf_remove') while nr_miss > 0: stop = True # continue to remove beh trials until data files are lined up for i, tr in enumerate(bdf_triggers): if tr != beh_triggers[i]: # remove trigger from beh_file miss = beh['nr_trials'].iloc[i] missing_trials.append(i) report_str += f'{miss}, ' #logging.info(f'Removed trial {miss} from beh file,because no matching trigger exists in bdf file') beh.drop(beh.index[i], inplace=True) beh_triggers = np.delete(beh_triggers, i, axis = 0) nr_miss -= 1 stop = False break # check whether there are missing trials at end of beh file if beh_triggers.size > bdf_triggers.size and stop: # drop the last items from the beh file missing_trials = np.hstack((missing_trials, beh['nr_trials'].iloc[-nr_miss:].values)) beh.drop(beh.index[-nr_miss:], inplace=True) #logging.info('Removed last {} trials because no matches detected'.format(nr_miss)) report_str += f'\n Removed final {nr_miss} trials from behavior to allign data. Please inspect your data carefully!' nr_miss = 0 # keep track of missing trials to allign eye tracking data (if available) missing = np.array(missing_trials) beh.reset_index(inplace = True) # add behavior to epochs object self.metadata = beh # log number of matches between beh and bdf #logging.info('{} matches between beh and epoched data out of {}'. # format(sum(beh[trigger_header].values == bdf_triggers), bdf_triggers.size)) report_str += '\n {} matches between beh and epoched data out of {}'.format(sum(beh[trigger_header].values == bdf_triggers), bdf_triggers.size) return missing, report_str def autoRepair(self): ''' ''' # select eeg channels picks = mne.pick_types(self.info, meg=False, eeg=True, stim=False, eog=False, include=[], exclude=[]) # initiate parameters p and k n_interpolates = np.array([1, 4, 32]) consensus_percs = np.linspace(0, 1.0, 11) ar = AutoReject(n_interpolates, consensus_percs, picks=picks, thresh_method='random_search', random_state=42) self, reject_log = ar.fit_transform(self, return_log=True) def apply_ransac(self): ''' Implements RAndom SAmple Consensus (RANSAC) method to detect bad channels. Returns - - - - self.info['bads']: list with all bad channels detected by the RANSAC algorithm ''' # select channels to display picks = mne.pick_types(self.info, eeg=True, exclude='bads') # use Ransac, interpolating bads and append bad channels to self.info['bads'] ransac = Ransac(verbose=False, picks=picks, n_jobs=1) epochs_clean = ransac.fit_transform(self) print('The following electrodes are selected as bad by Ransac:') print('\n'.join(ransac.bad_chs_)) return ransac.bad_chs_ def selectBadChannels(self, run_ransac = True, channel_plots=True, inspect=True, n_epochs=10, n_channels=32, RT = None): ''' ''' logging.info('Start selection of bad channels') #matplotlib.style.use('classic') # select channels to display picks = mne.pick_types(self.info, eeg=True, exclude='bads') # plot epoched data if channel_plots: for ch in picks: # plot evoked responses across channels try: # handle bug in mne for plotting undefined x, y coordinates plot_epochs_image(self.copy().crop(self.tmin + self.flt_pad,self.tmax - self.flt_pad), ch, show=False, overlay_times = RT) plt.savefig(self.FolderTracker(extension=[ 'preprocessing', 'subject-{}'.format(self.sj), self.session, 'channel_erps'], filename='{}.pdf'.format(self.ch_names[ch]))) plt.close() except: plt.savefig(self.FolderTracker(extension=[ 'preprocessing', 'subject-{}'.format(self.sj), self.session,'channel_erps'], filename='{}.pdf'.format(self.ch_names[ch]))) plt.close() self.plot_psd(picks = [ch], show = False) plt.savefig(self.FolderTracker(extension=[ 'preprocessing', 'subject-{}'.format(self.sj), self.session,'channel_erps'], filename='_psd_{}'.format(self.ch_names[ch]))) plt.close() # plot power spectra topoplot to detect any clear bad electrodes self.plot_psd_topomap(bands=[(0, 4, 'Delta'), (4, 8, 'Theta'), (8, 12, 'Alpha'), ( 12, 30, 'Beta'), (30, 45, 'Gamma'), (45, 100, 'High')], show=False) plt.savefig(self.FolderTracker(extension=[ 'preprocessing', 'subject-{}'.format(self.sj), self.session], filename='psd_topomap.pdf')) plt.close() if run_ransac: self.applyRansac() if inspect: # display raw eeg with 50mV range self.plot(block=True, n_epochs=n_epochs, n_channels=n_channels, picks=picks, scalings=dict(eeg=50)) if self.info['bads'] != []: with open(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(self.sj), self.session], filename='marked_bads.txt'), 'wb') as handle: pickle.dump(self.info['bads'], handle) else: try: with open(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(self.sj), self.session], filename='marked_bads.txt'), 'rb') as handle: self.info['bads'] = pickle.load(handle) print('The following channals were read in as bads from a txt file: {}'.format( self.info['bads'])) except: print('No bad channels selected') logging.info('{} channels marked as bad: {}'.format( len(self.info['bads']), self.info['bads'])) def automatic_artifact_detection(self, z_thresh=4, band_pass=[110, 140], plot=True, inspect=True): """ Detect artifacts> modification of FieldTrip's automatic artifact detection procedure (https://www.fieldtriptoolbox.org/tutorial/automatic_artifact_rejection/). Artifacts are detected in three steps: 1. Filtering the data within specified frequency range 2. Z-transforming the filtered data across channels and normalize it over channels 3. Threshold the accumulated z-score Counter to fieldtrip the z_threshold is ajusted based on the noise level within the data Note: all data included for filter padding is now taken into consideration to calculate z values Afer running this function, Epochs contains information about epeochs marked as bad (self.marked_epochs) Arguments: Keyword Arguments: z_thresh {float|int} -- Value that is added to difference between median and min value of accumulated z-score to obtain z-threshold band_pass {list} -- Low and High frequency cutoff for band_pass filter plot {bool} -- If True save detection plots (overview of z scores across epochs, raw signal of channel with highest z score, z distributions, raw signal of all electrodes) inspect {bool} -- If True gives the opportunity to overwrite selected components """ embed() # select data for artifact rejection sfreq = self.info['sfreq'] self_copy = self.copy() self_copy.pick_types(eeg=True, exclude='bads') #filter data and apply Hilbert self_copy.filter(band_pass[0], band_pass[1], fir_design='firwin', pad='reflect_limited') #self_copy.filter(band_pass[0], band_pass[1], method='iir', iir_params=dict(order=6, ftype='butter')) self_copy.apply_hilbert(envelope=True) # get the data and apply box smoothing data = self_copy.get_data() nr_epochs = data.shape[0] for i in range(data.shape[0]): data[i] = self.boxSmoothing(data[i]) # get the data and z_score over electrodes data = data.swapaxes(0,1).reshape(data.shape[1],-1) z_score = zscore(data, axis = 1) # check whether axis is correct!!!!!!!!!!! # normalize z_score z_score = z_score.sum(axis = 0)/sqrt(data.shape[0]) #z_score = filter_data(z_score, self.info['sfreq'], None, 4, pad='reflect_limited') # adjust threshold (data driven) z_thresh += np.median(z_score) + abs(z_score.min() - np.median(z_score)) # transform back into epochs z_score = z_score.reshape(nr_epochs, -1) # control for filter padding if self.flt_pad > 0: idx_ep = self.time_as_index([self.tmin + self.flt_pad, self.tmax - self.flt_pad]) z_score = z_score[:, slice(*idx_ep)] # mark bad epochs bad_epochs = [] cnt = 0 for ep, X in enumerate(z_score): noise_smp = np.where(X > z_thresh)[0] if noise_smp.size > 0: bad_epochs.append(ep) if inspect: print('This interactive window selectively shows epochs marked as bad. You can overwrite automatic artifact detection by clicking on selected epochs') bad_eegs = self[bad_epochs] idx_bads = bad_eegs.selection # display bad eegs with 50mV range bad_eegs.plot( n_epochs=5, n_channels=data.shape[1], scalings=dict(eeg = 50)) plt.show() plt.close() missing = np.array([list(idx_bads).index(idx) for idx in idx_bads if idx not in bad_eegs.selection],dtype = int) logging.info('Manually ignored {} epochs out of {} automatically selected({}%)'.format( missing.size, len(bad_epochs),100 * round(missing.size / float(len(bad_epochs)), 2))) bad_epochs = np.delete(bad_epochs, missing) if plot: plt.figure(figsize=(10, 10)) with sns.axes_style('dark'): plt.subplot(111, xlabel='samples', ylabel='z_value', xlim=(0, z_score.size), ylim=(-20, 40)) plt.plot(np.arange(0, z_score.size), z_score.flatten(), color='b') plt.plot(np.arange(0, z_score.size), np.ma.masked_less(z_score.flatten(), z_thresh), color='r') plt.axhline(z_thresh, color='r', ls='--') plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='automatic_artdetect.pdf')) plt.close() # drop bad epochs and save list of dropped epochs self.drop_beh = bad_epochs np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='noise_epochs.txt'), bad_epochs) print('{} epochs dropped ({}%)'.format(len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))) logging.info('{} epochs dropped ({}%)'.format( len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))) self.drop(np.array(bad_epochs), reason='art detection ecg') logging.info('{} epochs left after artifact detection'.format(len(self))) np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(self.sj), self.session], filename='automatic_artdetect.txt'), ['Artifact detection z threshold set to {}. \n{} epochs dropped ({}%)'. format(round(z_thresh, 1), len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))], fmt='%.100s') return z_thresh def artifactDetectionOLD(self, z_cutoff=4, band_pass=[110, 140], min_dur = 0.05, min_nr_art = 1, run = True, plot=True, inspect=True): """ Detect artifacts based on FieldTrip's automatic artifact detection. Artifacts are detected in three steps: 1. Filtering the data (6th order butterworth filter) 2. Z-transforming the filtered data and normalize it over channels 3. Threshold the accumulated z-score False-positive transient peaks are prevented by low-pass filtering the resulting z-score time series at 4 Hz. Afer running this function, Epochs contains information about epeochs marked as bad (self.marked_epochs) Arguments: Keyword Arguments: z_cuttoff {int} -- Value that is added to difference between median nd min value of accumulated z-score to obtain z-threshold band_pass {list} -- Low and High frequency cutoff for band_pass filter min_dur {float} -- minimum duration of detected artefects to be considered an artefact min_nr_art {int} -- minimum number of artefacts that may be present in an epoch (irrespective of min_dur) run {bool} -- specifies whether analysis is run a new or whether bad epochs are read in from memory plot {bool} -- If True save detection plots (overview of z scores across epochs, raw signal of channel with highest z score, z distributions, raw signal of all electrodes) inspect {bool} -- If True gives the opportunity to overwrite selected components time {tuple} -- Time window used for decoding tr_header {str} -- Name of column that contains training labels te_header {[type]} -- Name of column that contains testing labels """ # select channels for artifact detection picks = mne.pick_types(self.info, eeg=True, exclude='bads') nr_channels = picks.size sfreq = self.info['sfreq'] # control for filter padding if self.flt_pad > 0: idx_ep = self.time_as_index([self.tmin + self.flt_pad, self.tmax - self.flt_pad]) timings = self.times[idx_ep[0]:idx_ep[1]] ep_data = [] # STEP 1: filter each epoch data, apply hilbert transform and boxsmooth # the resulting data before removing filter padds if run: print('Started artifact detection') logging.info('Started artifact detection') for epoch, X in enumerate(self): # CHECK IF THIS IS CORRECT ORDER IN FIELDTRIP CODE / ALSO CHANGE # FILTER TO MNE 0.14 STANDARD X = filter_data(X[picks, :], sfreq, band_pass[0], band_pass[ 1], method='iir', iir_params=dict(order=6, ftype='butter')) X = np.abs(sp.signal.hilbert(X)) X = self.boxSmoothing(X) X = X[:, idx_ep[0]:idx_ep[1]] ep_data.append(X) # STEP 2: Z-transform data epoch = np.hstack(ep_data) avg_data = epoch.mean(axis=1).reshape(-1, 1) std_data = epoch.std(axis=1).reshape(-1, 1) z_data = [(ep - avg_data) / std_data for ep in ep_data] # STEP 3 threshold z-score per epoch z_accumel = np.hstack(z_data).sum(axis=0) / sqrt(nr_channels) z_accumel_ep = [np.array(z.sum(axis=0) / sqrt(nr_channels)) for z in z_data] z_thresh = np.median( z_accumel) + abs(z_accumel.min() - np.median(z_accumel)) + z_cutoff # split noise epochs based on start and end time # and select bad epochs based on specified criteria bad_epochs = [] for ep, X in enumerate(z_accumel_ep): noise_smp = np.where((X > z_thresh) == True)[0] noise_smp = np.split(noise_smp, np.where(np.diff(noise_smp) != 1)[0]+1) time_inf = [timings[smp[-1]] - timings[smp[0]] for smp in noise_smp if smp.size > 0] if len(time_inf) > 0: if max(time_inf) > min_dur or len(time_inf) > min_nr_art: bad_epochs.append(ep) if plot: plt.figure(figsize=(10, 10)) with sns.axes_style('dark'): plt.subplot(111, xlabel='samples', ylabel='z_value', xlim=(0, z_accumel.size), ylim=(-20, 40)) plt.plot(np.arange(0, z_accumel.size), z_accumel, color='b') plt.plot(np.arange(0, z_accumel.size), np.ma.masked_less(z_accumel, z_thresh), color='r') plt.axhline(z_thresh, color='r', ls='--') plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='automatic_artdetect.pdf')) plt.close() bad_epochs = np.array(bad_epochs) else: logging.info('Bad epochs read in from file') bad_epochs = np.loadtxt(self.FolderTracker(extension=[ 'preprocessing', 'subject-{}'.format(self.sj), self.session], filename='noise_epochs.txt')) if inspect: print('You can now overwrite automatic artifact detection by clicking on epochs selected as bad') bad_eegs = self[bad_epochs] idx_bads = bad_eegs.selection # display bad eegs with 50mV range bad_eegs.plot( n_epochs=5, n_channels=picks.size, picks=picks, scalings=dict(eeg = 50)) plt.show() plt.close() missing = np.array([list(idx_bads).index(idx) for idx in idx_bads if idx not in bad_eegs.selection], dtype = int) logging.info('Manually ignored {} epochs out of {} automatically selected({}%)'.format( missing.size, bad_epochs.size,100 * round(missing.size / float(bad_epochs.size), 2))) bad_epochs = np.delete(bad_epochs, missing) # drop bad epochs and save list of dropped epochs np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='noise_epochs.txt'), bad_epochs) print('{} epochs dropped ({}%)'.format(len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))) logging.info('{} epochs dropped ({}%)'.format( len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))) self.drop(np.array(bad_epochs), reason='art detection ecg') logging.info('{} epochs left after artifact detection'.format(len(self))) if run: np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(self.sj), self.session], filename='automatic_artdetect.txt'), ['Artifact detection z threshold set to {}. \n{} epochs dropped ({}%)'. format(round(z_thresh, 1), len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))], fmt='%.100s') def boxSmoothing(self, data, box_car=0.2): ''' doc string boxSmoothing ''' pad = int(round(box_car * self.info['sfreq'])) if pad % 2 == 0: # the kernel should have an odd number of samples pad += 1 kernel = np.ones(pad) / pad pad = int(ceil(pad / 2)) pre_pad = int(min([pad, floor(data.shape[1]) / 2.0])) edge_left = data[:, :pre_pad].mean(axis=1) edge_right = data[:, -pre_pad:].mean(axis=1) data = np.concatenate((np.tile(edge_left.reshape(data.shape[0], 1), pre_pad), data, np.tile( edge_right.reshape(data.shape[0], 1), pre_pad)), axis=1) data_smooth = sp.signal.convolve2d( data, kernel.reshape(1, kernel.shape[0]), 'same') data = data_smooth[:, pad:(data_smooth.shape[1] - pad)] return data def detectEye(self, missing, events, nr_events, time_window, threshold=20, windowsize=100, windowstep=10, channel='HEOG', tracker_shift = 0, start_event = '', extension = 'asc', eye_freq = 500, screen_res = (1680, 1050), viewing_dist = 60, screen_h = 29): ''' Marking epochs containing step-like activity that is greater than a given threshold Arguments - - - - - self(object): Epochs object missing events (array): nr_events (int): time_window (tuple): start and end time in seconds threshold (int): range of amplitude in microVolt windowsize (int): total moving window width in ms. So each window's width is half this value windowsstep (int): moving window step in ms channel (str): name of HEOG channel tracker_shift (float): specifies difference in ms between onset trigger and event in eyetracker data start_event (str): marking onset of trial in eyetracker data extension (str): type of eyetracker file (now supports .asc/ .tsv) eye_freq (int): sampling rate of the eyetracker Returns - - - - ''' self.eye_bins = True sac_epochs = [] # CODE FOR HEOG DATA idx_ch = self.ch_names.index(channel) idx_s, idx_e = tuple([np.argmin(abs(self.times - t)) for t in time_window]) windowstep /= 1000 / self.info['sfreq'] windowsize /= 1000 / self.info['sfreq'] for i in range(len(self)): up_down = 0 for j in np.arange(idx_s, idx_e - windowstep, windowstep): w1 = np.mean(self._data[i, idx_ch, int( j):int(j + windowsize / 2) - 1]) w2 = np.mean(self._data[i, idx_ch, int( j + windowsize / 2):int(j + windowsize) - 1]) if abs(w1 - w2) > threshold: up_down += 1 if up_down == 2: sac_epochs.append(i) break logging.info('Detected {0} epochs ({1:.2f}%) with a saccade based on HEOG'.format( len(sac_epochs), len(sac_epochs) / float(len(self)) * 100)) # CODE FOR EYETRACKER DATA EO = EYE(sfreq = eye_freq, viewing_dist = viewing_dist, screen_res = screen_res, screen_h = screen_h) # do binning based on eye-tracking data (if eyetracker data exists) eye_bins, window_bins, trial_nrs = EO.eyeBinEEG(self.sj, int(self.session), int((self.tmin + self.flt_pad + tracker_shift)*1000), int((self.tmax - self.flt_pad + tracker_shift)*1000), drift_correct = (-200,0), start_event = start_event, extension = extension) if eye_bins.size > 0: logging.info('Window method detected {} epochs exceeding 0.5 threshold'.format(window_bins.size)) # remove trials that could not be linked to eeg trigger if missing.size > 0: eye_bins = np.delete(eye_bins, missing) dropped = trial_nrs[missing] logging.info('{} trials removed from eye data to align to eeg. Correspond to trial_nr {} in beh'.format(missing.size, dropped)) # remove trials that have been deleted from eeg eye_bins = np.delete(eye_bins, self.drop_beh) # log eyetracker info unique_bins = np.array(np.unique(eye_bins), dtype = np.float64) for eye_bin in np.unique(unique_bins[~np.isnan(unique_bins)]): logging.info('{0:.1f}% of trials exceed {1} degree of visual angle'.format(sum(eye_bins> eye_bin) / eye_bins.size*100, eye_bin)) # save array of deviation bins np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='eye_bins.txt'), eye_bins) # # correct for missing data (if eye recording is stopped during experiment) # if eye_bins.size > 0 and eye_bins.size < self.nr_events: # # create array of nan values for all epochs (UGLY CODING!!!) # temp = np.empty(self.nr_events) * np.nan # temp[trial_nrs - 1] = eye_bins # eye_bins = temp # temp = (np.empty(self.nr_events) * np.nan) # temp[trial_nrs - 1] = trial_nrs # trial_nrs = temp # elif eye_bins.size == 0: # eye_bins = np.empty(self.nr_events + missing.size) * np.nan # trial_nrs = np.arange(self.nr_events + missing.size) + 1 def applyICA(self, raw, ica_fit, method='extended-infomax', decim=None, fit_params = None, inspect = True): ''' Arguments - - - - - self(object): Epochs object raw (object): n_components (): method (str): decim (): Returns - - - - self ''' # make sure that bad electrodes and 'good' epochs match between both data sets ica_fit.info['bads'] = self.info['bads'] if str(type(ica_fit))[-3] == 's': print('fitting data on epochs object') to_drop = [i for i, v in enumerate(ica_fit.selection) if v not in self.selection] ica_fit.drop(to_drop) # initiate ica logging.info('Started ICA') picks = mne.pick_types(self.info, eeg=True, exclude='bads') ica = ICA(n_components=picks.size, method=method, fit_params = fit_params) # ica is fitted on epoched data ica.fit(ica_fit, picks=picks, decim=decim) # plot the components ica.plot_components(colorbar=True, picks=range(picks.size), show=False) plt.savefig(self.FolderTracker(extension=[ 'preprocessing', 'subject-{}'.format(self.sj), self.session], filename='components.pdf')) plt.close() # advanced artifact detection eog_epochs = create_eog_epochs(raw, baseline=(None, None)) eog_inds_a, scores = ica.find_bads_eog(eog_epochs) ica.plot_scores(scores, exclude=eog_inds_a, show=False) plt.savefig(self.FolderTracker(extension=[ 'preprocessing', 'subject-{}'.format(self.sj), self.session], filename='ica_scores.pdf')) plt.close() # diagnostic plotting ica.plot_sources(self, show_scrollbars=False, show=False) if inspect: plt.show() else: plt.savefig(self.FolderTracker(extension=[ 'preprocessing', 'subject-{}'.format(self.sj), self.session], filename='sources.pdf')) plt.close() # double check selected component with user input time.sleep(5) tcflush(sys.stdin, TCIFLUSH) print('You are preprocessing subject {}, session {}'.format(self.sj, self.session)) conf = input( 'Advanced detection selected component(s) {}. Do you agree (y/n)'.format(eog_inds_a)) if conf == 'y': eog_inds = eog_inds_a else: eog_inds = [] nr_comp = input( 'How many components do you want to select (<10)?') for i in range(int(nr_comp)): eog_inds.append( int(input('What is component nr {}?'.format(i + 1)))) for i, cmpt in enumerate(eog_inds): ica.plot_properties(self, picks=cmpt, psd_args={ 'fmax': 35.}, image_args={'sigma': 1.}, show=False) plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='property{}.pdf'.format(cmpt))) plt.close() ica.plot_overlay(raw, exclude=eog_inds, picks=[self.ch_names.index(e) for e in [ 'Fp1', 'Fpz', 'Fp2', 'AF7', 'AF3', 'AFz', 'AF4', 'AF8']], show = False) plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='ica-frontal.pdf')) plt.close() ica.plot_overlay(raw, exclude=eog_inds, picks=[self.ch_names.index(e) for e in [ 'PO7', 'PO8', 'PO3', 'PO4', 'O1', 'O2', 'POz', 'Oz','Iz']], show = False) plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='ica-posterior.pdf')) plt.close() # remove selected component ica.apply(self, exclude=eog_inds) logging.info( 'The following components were removed from raw eeg with ica: {}'.format(eog_inds)) def link_behavior(self, beh: pd.DataFrame, combine_sessions: bool = True): """ Saves linked eeg and behavior data. Preprocessed eeg is saved in the folder processed and behavior is saved in a processed subfolder of beh. Args: beh (pd.DataFrame): behavioral dataframe containing parameters of interest combine_sessions (bool, optional):If experiment contains seperate sessions, these are combined into a single datafile that is saved alongside the individual sessions. Defaults to True. """ # update beh dict after removing noise trials beh.drop(self.drop_beh, axis = 'index', inplace = True) # also include eye binned data if hasattr(self, 'eye_bins'): eye_bins = np.loadtxt(self.FolderTracker(extension=[ 'preprocessing', 'subject-{}'.format(self.sj), self.session], filename='eye_bins.txt')) else: eye_bins = np.nan beh['eye_bins'] = pd.Series(eye_bins) # save behavior as pickle beh_dict = beh.to_dict(orient = 'list') with open(self.FolderTracker(extension=['beh', 'processed'], filename='subject-{}_ses-{}.pickle'.format(self.sj, self.session)), 'wb') as handle: pickle.dump(beh_dict, handle) # save eeg self.save(self.FolderTracker(extension=[ 'processed'], filename='subject-{}_ses-{}-epo.fif'.format(self.sj, self.session)), split_size='2GB', overwrite = True) # update preprocessing information logging.info('Nr clean trials is {0}'.format(beh.shape[0])) if 'condition' in beh.index: cnd = beh['condition'].values min_cnd, cnd = min([sum(cnd == c) for c in np.unique(cnd)]), np.unique(cnd)[ np.argmin([sum(cnd == c) for c in np.unique(cnd)])] logging.info( 'Minimum condition ({}) number after cleaning is {}'.format(cnd, min_cnd)) else: logging.info('no condition found in beh file') logging.info('EEG data linked to behavior file') # check whether individual sessions need to be combined if combine_sessions and int(self.session) != 1: # combine eeg and beh files of seperate sessions all_beh = [] all_eeg = [] nr_events = [] for i in range(int(self.session)): with open(self.FolderTracker(extension=['beh', 'processed'], filename='subject-{}_ses-{}.pickle'.format(self.sj, i + 1)), 'rb') as handle: all_beh.append(pickle.load(handle)) all_eeg.append(mne.read_epochs(self.FolderTracker(extension=[ 'processed'], filename='subject-{}_ses-{}-epo.fif'.format(self.sj, i + 1)))) # do actual combining for key in beh_dict.keys(): beh_dict.update( {key: np.hstack([beh[key] for beh in all_beh])}) with open(self.FolderTracker(extension=['beh', 'processed'], filename='subject-{}_all.pickle'.format(self.sj)), 'wb') as handle: pickle.dump(beh_dict, handle) all_eeg = mne.concatenate_epochs(all_eeg) all_eeg.save(self.FolderTracker(extension=[ 'processed'], filename='subject-{}_all-epo.fif'.format(self.sj)), split_size='2GB', overwrite = True) logging.info('EEG sessions combined') class ArtefactReject(object): """ Multiple (automatic artefact rejection procedures) Work in progress """ @blockPrinting def apply_hilbert(self, epochs: mne.Epochs, lower_band: int = 110, upper_band: int = 140) -> np.array: """ Takes an mne epochs object as input and returns the eeg data after Hilbert transform Args: epochs (mne.Epochs): mne epochs object before muscle artefact detection lower_band (int, optional): Lower limit of the bandpass filter. Defaults to 110. upper_band (int, optional): Upper limit of the bandpass filter. Defaults to 140. Returns: X (np.array): eeg data after applying hilbert transform within the given frequency band """ # exclude channels that are marked as overall bad epochs_ = epochs.copy() epochs_.pick_types(eeg=True, exclude='bads') # filter data and apply Hilbert epochs_.filter(lower_band, upper_band, fir_design='firwin', pad='reflect_limited') epochs_.apply_hilbert(envelope=True) # get data X = epochs_.get_data() del epochs_ return X def filt_pad(self, X: np.array, pad_length: int) -> np.array: """ performs padding (using local mean method) on the data, i.e., adds samples before and after the data TODO: MOVE to signal processing folder (see https://github.com/fieldtrip/fieldtrip/blob/master/preproc/ft_preproc_padding.m)) Args: X (np.array): 2-dimensional array [nr_elec X nr_time] pad_length (int): number of samples that will be padded Returns: X (np.array): 2-dimensional array with padded data [nr_elec X nr_time] """ # set number of pad samples pre_pad = int(min([pad_length, floor(X.shape[1]) / 2.0])) # get local mean on both sides edge_left = X[:, :pre_pad].mean(axis=1) edge_right = X[:, -pre_pad:].mean(axis=1) # pad data X = np.concatenate((np.tile(edge_left.reshape(X.shape[0], 1), pre_pad), X, np.tile( edge_right.reshape(X.shape[0], 1), pre_pad)), axis=1) return X def box_smoothing(self, X: np.array, sfreq: float, boxcar: float = 0.2) -> np.array: """ performs boxcar smoothing with specified length. Modified version of ft_preproc_smooth as implemented in the FieldTrip toolbox (https://www.fieldtriptoolbox.org) Args: X (np.array): 3-dimensional array [nr_epoch X nr_elec X nr_time] sfreq (float): sampling frequency boxcar (float, optional): parameter that determines the length of the filter kernel. Defaults to 0.2 (optimal accrding to fieldtrip documentation). Returns: np.array: [description] """ # create smoothing kernel pad = int(round(boxcar * sfreq)) # make sure that kernel has an odd number of samples if pad % 2 == 0: pad += 1 kernel = np.ones(pad) / pad # padding and smoothing functions expect 2-d input (nr_elec X nr_time) pad_length = int(ceil(pad / 2)) for i, x in enumerate(X): # pad the data x = self.filt_pad(x, pad_length = pad_length) # smooth the data x_smooth = sp.signal.convolve2d( x, kernel.reshape(1, kernel.shape[0]), 'same') X[i] = x_smooth[:, pad_length:(x_smooth.shape[1] - pad_length)] return X def z_score_data(self, X: np.array, z_thresh: int = 4, mask: np.array = None, filter_z: tuple = (False, 512)) -> Tuple[np.array, np.array, float]: """ Z scores input data over the second dimension (i.e., electrodes). The z threshold, which is used to mark artefact segments, is then calculated using a data driven approach, where the upper limit of the 'bandwith' of obtained z scores is added to the provided default threshold. Also returns z scored data per electrode which can be used during iterative automatic cleaning procedure. Args: X (np.array): 3-dimensional array of [trial repeats by electrodes by time points]. z_thresh (int, optional): starting z value cut off. Defaults to 4. mask (np.array, optional): a boolean array that masks out time points such that they are excluded during z scoring. Note these datapoints are still returned in Z_n and elecs_z (see below). filter_z (tuple, optional): prevents false-positive transient peaks by low-pass filtering the resulting z-score time series at 4 Hz. Note: Should never be used without filter padding the data. Second argument in the tuple specifies the sampling frequency. Defaults to False, i.e., no filtering. Returns: Z_n (np.array): 2-dimensional array of normalized z scores across electrodes[trial repeats by time points]. elecs_z (np.array): 3-dimensional array of z scores data per sample [trial repeats by electrodes by time points]. z_thresh (float): z_score theshold used to mark segments of muscle artefacts """ # set params nr_epoch, nr_elec, nr_time = X.shape # get the data and z_score over electrodes X = X.swapaxes(0,1).reshape(nr_elec,-1) X_z = zscore(X, axis = 1) if mask is not None: mask = np.tile(mask, nr_epoch) X_z[:, mask] = zscore(X[:,mask], axis = 1) # reshape to get get epoched data in terms of z scores elecs_z = X_z.reshape(nr_elec, nr_epoch,-1).swapaxes(0,1) # normalize z_score Z_n = X_z.sum(axis = 0)/sqrt(nr_elec) if mask is not None: Z_n[mask] = X_z[:,mask].sum(axis = 0)/sqrt(nr_elec) if filter_z[0]: Z_n = filter_data(Z_n, filter_z[1], None, 4, pad='reflect_limited') # adjust threshold (data driven) if mask is None: mask = np.ones(Z_n.size, dtype = bool) z_thresh += np.median(Z_n[mask]) + abs(Z_n[mask].min() - np.median(Z_n[mask])) # transform back into epochs Z_n = Z_n.reshape(nr_epoch, -1) return Z_n, elecs_z, z_thresh def mark_bads(self, Z: np.array, z_thresh: float, times: np.array) -> list: """ Marks which epochs contain samples that exceed the data driven z threshold (as set by z_score_data). Outputs a list with marked epochs. Per marked epoch alongside the index, a slice of the artefact, the start and end point and the duration of the artefact are saved Args: Z (np.array): 2-dimensional array of normalized z scores across electrodes [trial repeats by time points] z_thresh (float): z_score theshold used to mark segments of muscle artefacts times (np.array): sample time points Returns: noise_events (list): indices of marked epochs. Per epoch time information of each artefact is logged [idx, (artefact slice, start_time, end_time, duration)] """ # start with empty list noise_events = [] # loop over each epoch for ep, x in enumerate(Z): # mask noise samples noise_mask = abs(x) > z_thresh # get start and end point of continuous noise segments starts = np.argwhere((~noise_mask[:-1] & noise_mask[1:])) if noise_mask[0]: starts = np.insert(starts, 0, 0) ends = np.argwhere((noise_mask[:-1] & ~noise_mask[1:])) + 1 # update noise_events if starts.size > 0: starts = np.hstack(starts) if ends.size == 0: ends = np.array([times.size-1]) else: ends = np.hstack(ends) ep_noise = [ep] + [(slice(s, e), times[s],times[e], abs(times[e] - times[s])) for s,e in zip(starts, ends)] noise_events.append(ep_noise) return noise_events def automatic_artifact_detection(self, z_thresh=4, band_pass=[110, 140], plot=True, inspect=True): """ Detect artifacts> modification of FieldTrip's automatic artifact detection procedure (https://www.fieldtriptoolbox.org/tutorial/automatic_artifact_rejection/). Artifacts are detected in three steps: 1. Filtering the data within specified frequency range 2. Z-transforming the filtered data across channels and normalize it over channels 3. Threshold the accumulated z-score Counter to fieldtrip the z_threshold is ajusted based on the noise level within the data Note: all data included for filter padding is now taken into consideration to calculate z values Afer running this function, Epochs contains information about epeochs marked as bad (self.marked_epochs) Arguments: Keyword Arguments: z_thresh {float|int} -- Value that is added to difference between median and min value of accumulated z-score to obtain z-threshold band_pass {list} -- Low and High frequency cutoff for band_pass filter plot {bool} -- If True save detection plots (overview of z scores across epochs, raw signal of channel with highest z score, z distributions, raw signal of all electrodes) inspect {bool} -- If True gives the opportunity to overwrite selected components """ # select data for artifact rejection sfreq = self.info['sfreq'] self_copy = self.copy() self_copy.pick_types(eeg=True, exclude='bads') #filter data and apply Hilbert self_copy.filter(band_pass[0], band_pass[1], fir_design='firwin', pad='reflect_limited') #self_copy.filter(band_pass[0], band_pass[1], method='iir', iir_params=dict(order=6, ftype='butter')) self_copy.apply_hilbert(envelope=True) # get the data and apply box smoothing data = self_copy.get_data() nr_epochs = data.shape[0] for i in range(data.shape[0]): data[i] = self.boxSmoothing(data[i]) # get the data and z_score over electrodes data = data.swapaxes(0,1).reshape(data.shape[1],-1) z_score = zscore(data, axis = 1) # check whether axis is correct!!!!!!!!!!! # z score per electrode and time point (adjust number of electrodes) elecs_z = z_score.reshape(nr_epochs, 64, -1) # normalize z_score z_score = z_score.sum(axis = 0)/sqrt(data.shape[0]) #z_score = filter_data(z_score, self.info['sfreq'], None, 4, pad='reflect_limited') # adjust threshold (data driven) z_thresh += np.median(z_score) + abs(z_score.min() - np.median(z_score)) # transform back into epochs z_score = z_score.reshape(nr_epochs, -1) # control for filter padding if self.flt_pad > 0: idx_ep = self.time_as_index([self.tmin + self.flt_pad, self.tmax - self.flt_pad]) z_score = z_score[:, slice(*idx_ep)] elecs_z # mark bad epochs bad_epochs = [] noise_events = [] cnt = 0 for ep, X in enumerate(z_score): # get start, endpoint and duration in ms per continuous artefact noise_mask = X > z_thresh starts = np.argwhere((~noise_mask[:-1] & noise_mask[1:])) ends = np.argwhere((noise_mask[:-1] & ~noise_mask[1:])) + 1 ep_noise = [(slice(s[0], e[0]), self.times[s][0],self.times[e][0], abs(self.times[e][0] - self.times[s][0])) for s,e in zip(starts, ends)] noise_events.append(ep_noise) noise_smp = np.where(X > z_thresh)[0] if noise_smp.size > 0: bad_epochs.append(ep) if inspect: print('This interactive window selectively shows epochs marked as bad. You can overwrite automatic artifact detection by clicking on selected epochs') bad_eegs = self[bad_epochs] idx_bads = bad_eegs.selection # display bad eegs with 50mV range bad_eegs.plot( n_epochs=5, n_channels=data.shape[1], scalings=dict(eeg = 50)) plt.show() plt.close() missing = np.array([list(idx_bads).index(idx) for idx in idx_bads if idx not in bad_eegs.selection],dtype = int) logging.info('Manually ignored {} epochs out of {} automatically selected({}%)'.format( missing.size, len(bad_epochs),100 * round(missing.size / float(len(bad_epochs)), 2))) bad_epochs = np.delete(bad_epochs, missing) if plot: plt.figure(figsize=(10, 10)) with sns.axes_style('dark'): plt.subplot(111, xlabel='samples', ylabel='z_value', xlim=(0, z_score.size), ylim=(-20, 40)) plt.plot(np.arange(0, z_score.size), z_score.flatten(), color='b') plt.plot(np.arange(0, z_score.size), np.ma.masked_less(z_score.flatten(), z_thresh), color='r') plt.axhline(z_thresh, color='r', ls='--') plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='automatic_artdetect.pdf')) plt.close() # drop bad epochs and save list of dropped epochs self.drop_beh = bad_epochs np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='noise_epochs.txt'), bad_epochs) print('{} epochs dropped ({}%)'.format(len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))) logging.info('{} epochs dropped ({}%)'.format( len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))) self.drop(np.array(bad_epochs), reason='art detection ecg') logging.info('{} epochs left after artifact detection'.format(len(self))) np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(self.sj), self.session], filename='automatic_artdetect.txt'), ['Artifact detection z threshold set to {}. \n{} epochs dropped ({}%)'. format(round(z_thresh, 1), len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))], fmt='%.100s') return z_thresh if __name__ == '__main__': print('Please run preprocessing via a project script')
45.111483
259
0.594934
""" analyze EEG data Created by Dirk van Moorselaar on 10-03-2015. Copyright (c) 2015 DvM. All rights reserved. """ import mne import os import logging import itertools import pickle import copy import glob import sys import time import itertools import numpy as np import scipy as sp import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from matplotlib import cm from scipy.stats import zscore from typing import Optional, Generic, Union, Tuple, Any from termios import tcflush, TCIFLUSH from eeg_analyses.EYE import * from math import sqrt from IPython import embed from support.FolderStructure import * from scipy.stats.stats import pearsonr from mne.viz.epochs import plot_epochs_image from mne.filter import filter_data from mne.preprocessing import ICA from mne.preprocessing import create_eog_epochs, create_ecg_epochs from math import ceil, floor from autoreject import Ransac, AutoReject def blockPrinting(func): def func_wrapper(*args, **kwargs): # block all printing to the console sys.stdout = open(os.devnull, 'w') # call the method in question value = func(*args, **kwargs) # enable all printing to the console sys.stdout = sys.__stdout__ # pass the return value of the method back return value return func_wrapper class RawBDF(mne.io.edf.edf.RawEDF, FolderStructure): ''' Child originating from MNE built-in RawEDF, such that new methods can be added to this built in class ''' def __init__(self, input_fname, eog=None, stim_channel=-1, exclude=(), preload=True, verbose=None): super(RawBDF, self).__init__(input_fname=input_fname, eog=eog, stim_channel=stim_channel, preload=preload, verbose=verbose) def report_raw(self, report, events, event_id): ''' ''' # report raw report.add_raw(self, title='raw EEG', psd=True ) # and events events = events[np.in1d(events[:,2], event_id)] report.add_events(events, title = 'detected events', sfreq = self.info['sfreq']) return report def replaceChannel(self, sj, session, replace): ''' Replace bad electrodes by electrodes that were used during recording as a replacement Arguments - - - - - raw (object): raw mne eeg object sj (int): subject_nr session (int): eeg session number replace (dict): dictionary containing to be replaced electrodes per subject and session Returns - - - - self(object): raw object with bad electrodes replaced ''' sj = str(sj) session = 'session_{}'.format(session) if sj in replace.keys(): if session in replace[sj].keys(): to_replace = replace[sj][session].keys() for e in to_replace: self._data[self.ch_names.index(e), :] = self._data[ self.ch_names.index(replace[sj][session][e]), :] # print('Electrode {0} replaced by # {1}'.format(e,replace[sj][session][e])) def reReference(self, ref_channels=['EXG5', 'EXG6'], vEOG=['EXG1', 'EXG2'], hEOG=['EXG3', 'EXG4'], changevoltage=True, to_remove = ['EXG7','EXG8']): ''' Rereference raw data to reference channels. By default data is rereferenced to the mastoids. Also EOG data is rerefenced. Subtraction of VEOG and HEOG results in a VEOG and an HEOG channel. After rereferencing redundant channels are removed. Functions assumes that there are 2 vEOG and 2 hEOG channels. Arguments - - - - - self(object): RawBDF object ref_channels (list): list with channels for rerefencing vEOG (list): list with vEOG channels hEOG (list): list with hEOG channels changevoltage (bool): remove(bool): Specify whether channels need to be removed Returns - - - - self (object): Rereferenced raw eeg data ''' # change data format from Volts to microVolts if changevoltage: self._data[:-1, :] *= 1e6 print('Volts changed to microvolts') logging.info('Volts changed to microvolts') # rereference all EEG channels to reference channels self.set_eeg_reference(ref_channels=ref_channels) to_remove += ref_channels print('EEG data was rereferenced to channels {}'.format(ref_channels)) logging.info( 'EEG data was rereferenced to channels {}'.format(ref_channels)) # select eog channels eog = self.copy().pick_types(eeg=False, eog=True) # # rerefence EOG data (vertical and horizontal) # idx_v = [eog.ch_names.index(vert) for vert in vEOG] # idx_h = [eog.ch_names.index(hor) for hor in hEOG] # if len(idx_v) == 2: # eog._data[idx_v[0]] -= eog._data[idx_v[1]] # if len(idx_h) == 2: # eog._data[idx_h[0]] -= eog._data[idx_h[1]] # print( # 'EOG data (VEOG, HEOG) rereferenced with subtraction and renamed EOG channels') # logging.info( # 'EOG data (VEOG, HEOG) rereferenced with subtraction and renamed EOG channels') # # add rereferenced vEOG and hEOG data to self # ch_mapping = {vEOG[0]: 'VEOG', hEOG[0]: 'HEOG'} # eog.rename_channels(ch_mapping) # eog.drop_channels([vEOG[1], hEOG[1]]) # #self.add_channels([eog]) # drop ref chans self.drop_channels(to_remove) print('Reference channels and empty channels removed') logging.info('Reference channels and empty channels removed') def setMontage(self, montage='biosemi64', ch_remove = []): ''' Uses mne function to set the specified montage. Also changes channel labels from A, B etc naming scheme to standard naming conventions and removes specified channels. At the same time changes the name of EOG electrodes (assumes an EXG naming scheme) Arguments - - - - - raw (object): raw mne eeg object montage (str): used montage during recording ch_remove (list): channels that you want to exclude from analysis (e.g heart rate) Returns - - - - self(object): raw object with changed channel names following biosemi 64 naming scheme (10 - 20 system) ''' # drop channels and get montage self.drop_channels(ch_remove) # create mapping dictionary idx = 0 ch_mapping = {} if self.ch_names[0] == 'A1': for hemi in ['A', 'B']: for electr in range(1, 33): ch_mapping.update( {'{}{}'.format(hemi, electr): montage.ch_names[idx]}) idx += 1 self.rename_channels(ch_mapping) self.set_montage(montage=montage) print('Channels renamed to 10-20 system, and montage added') logging.info('Channels renamed to 10-20 system, and montage added') def eventSelection(self, trigger, binary=0, consecutive=False, min_duration=0.003): ''' Returns array of events necessary for epoching. Arguments - - - - - raw (object): raw mne eeg object binary (int): is subtracted from stim channel to control for spoke triggers (e.g. subtracts 3840) Returns - - - - events(array): numpy array with trigger events (first column contains the event time in samples and the third column contains the event id) ''' self._data[-1, :] -= binary # Make universal events = mne.find_events(self, stim_channel=None, consecutive=consecutive, min_duration=min_duration) # Check for consecutive if not consecutive: spoke_idx = [] for i in range(events[:-1,2].size): if events[i,2] == events[i + 1,2] and events[i,2] in trigger: spoke_idx.append(i) events = np.delete(events,spoke_idx,0) logging.info('{} spoke events removed from event file'.format(len(spoke_idx))) return events def matchBeh(self, sj, session, events, event_id, trigger_header = 'trigger', headers = []): ''' Alligns bdf file with csv file with experimental variables Arguments - - - - - raw (object): raw mne eeg object sj (int): sj number session(int): session number events(array): event file from eventSelection (last column contains trigger values) trigger(list|array): trigger values used for epoching headers (list): relevant column names from behavior file Returns - - - - beh (object): panda object with behavioral data (triggers are alligned) missing (araray): array of missing trials (can be used when selecting eyetracking data) ''' # read in data file beh_file = self.FolderTracker(extension=[ 'beh', 'raw'], filename='subject-{}_session_{}.csv'.format(sj, session)) # get triggers logged in beh file beh = pd.read_csv(beh_file) beh = beh[headers] if 'practice' in headers: beh = beh[beh['practice'] == 'no'] beh = beh.drop(['practice'], axis=1) beh_triggers = beh[trigger_header].values # get triggers bdf file if type(event_id) == dict: event_id = [event_id[key] for key in event_id.keys()] idx_trigger = [idx for idx, tr in enumerate(events[:,2]) if tr in event_id] bdf_triggers = events[idx_trigger,2] # log number of unique triggers unique = np.unique(bdf_triggers) logging.info('{} detected unique triggers (min = {}, max = {})'. format(unique.size, unique.min(), unique.max())) # make sure trigger info between beh and bdf data matches missing_trials = [] nr_miss = beh_triggers.size - bdf_triggers.size logging.info('{} trials will be removed from beh file'.format(nr_miss)) # check whether trial info is present in beh file if nr_miss > 0 and 'nr_trials' not in beh.columns: raise ValueError('Behavior file does not contain a column with trial info named nr_trials. Please adjust') while nr_miss > 0: stop = True # continue to remove beh trials until data files are lined up for i, tr in enumerate(bdf_triggers): if tr != beh_triggers[i]: # remove trigger from beh_file miss = beh['nr_trials'].iloc[i] #print miss missing_trials.append(miss) logging.info('Removed trial {} from beh file,because no matching trigger exists in bdf file'.format(miss)) beh.drop(beh.index[i], inplace=True) beh_triggers = np.delete(beh_triggers, i, axis = 0) nr_miss -= 1 stop = False break # check whether there are missing trials at end of beh file if beh_triggers.size > bdf_triggers.size and stop: # drop the last items from the beh file missing_trials = np.hstack((missing_trials, beh['nr_trials'].iloc[-nr_miss:].values)) beh.drop(beh.index[-nr_miss:], inplace=True) logging.info('Removed last {} trials because no matches detected'.format(nr_miss)) nr_miss = 0 # keep track of missing trials to allign eye tracking data (if available) missing = np.array(missing_trials) # log number of matches between beh and bdf logging.info('{} matches between beh and epoched data out of {}'. format(sum(beh[trigger_header].values == bdf_triggers), bdf_triggers.size)) return beh, missing class Epochs(mne.Epochs, FolderStructure): ''' Child originating from MNE built-in Epochs, such that new methods can be added to this built in class ''' def __init__(self, sj, session, raw, events, event_id, tmin, tmax, flt_pad=True, baseline=(None, None), picks=None, preload=True, reject=None, flat=None, proj=False, decim=1, reject_tmin=None, reject_tmax=None, detrend=None, on_missing='error', reject_by_annotation=False, verbose=None, z_thresh = 4): # check whether a preprocessed folder for the current subject exists, # if not make onen self.sj = sj self.session = str(session) self.flt_pad = flt_pad tmin, tmax = tmin - flt_pad, tmax + flt_pad super(Epochs, self).__init__(raw=raw, events=events, event_id=event_id, tmin=tmin, tmax=tmax, baseline=baseline, picks=picks, preload=preload, reject=reject, flat=flat, proj=proj, decim=decim, reject_tmin=reject_tmin, reject_tmax=reject_tmax, detrend=detrend, on_missing=on_missing, reject_by_annotation=reject_by_annotation, verbose=verbose) # save number of detected events self.nr_events = len(self) self.drop_beh = [] logging.info('{} epochs created'.format(len(self))) def report_epochs(self, report, title, missing = None): if missing is not None: report.add_html(missing, title = 'missing trials in beh') report.add_epochs(self, title=title) return report def align_behavior(self, events: np.array, trigger_header: str = 'trigger', headers: list = [], bdf_remove: np.array = None): """ Aligns bdf file with csv file with experimental variables. In case there are more behavioral trials than eeg trials (e.g., because trigger was not properly sent/detected), trials are removed from the raw behavioral data such that both datasets are aligned. Information about this process can be found in individual preprocessing log files. Args: events (np.array): event info as returned by RAW.event_selection trigger_header (str, optional): Column in raw behavior that contains trigger values used for epoching. Defaults to 'trigger'. headers (list, optional): List of headers that should be linked to eeg data. Defaults to []. bdf_remove (np.array, optional): Indices of trigger events that need to be removed. Only specify when to many trials are recorded. Raises: ValueError: In case behavior and eeg data do not align (i.e., contain different trial numbers). If there are more behavior trials than epochs, raises an error in case there is no column 'nr_trials', which prevents informed alignment of eeg and behavior. Also raises an error if there are too many epochs and automatic allignment fails Returns: beh (pd.DataFrame): Behavior data after aligning to eeg data (index is reset) missing (np.array): array with trials that are removed from beh because no matching trigger was detected. Is used when aligning eyetracker data (where it is assumed that eyetracking data and raw behavior contain the same number of trials) """ print('Linking behavior to eeg data') report_str = '' # read in data file beh_file = self.FolderTracker(extension=[ 'beh', 'raw'], filename='subject-{}_session_{}.csv'.format(self.sj, self.session)) # get triggers logged in beh file beh = pd.read_csv(beh_file) beh = beh[headers] if 'practice' in headers: print('{} practice trials removed from behavior'.format(beh[beh.practice == 'yes'].shape[0])) #logging.info('{} practice trials removed from behavior'.format(beh[beh.practice == 'yes'].shape[0])) beh = beh[beh.practice == 'no'] beh = beh.drop(['practice'], axis=1) beh_triggers = beh[trigger_header].values # get eeg triggers in epoched order () bdf_triggers = events[self.selection, 2] if bdf_remove is not None: self.drop(bdf_remove) report_str += '{} bdf triggers removed as specified by the user \n'.format(bdf_remove.size) #logging.info('{} bdf triggers and epochs removed as specified by the user'.format(bdf_remove.size)) bdf_triggers = np.delete(bdf_triggers, bdf_remove) # log number of unique triggers #unique = np.unique(bdf_triggers) #logging.info('{} detected unique triggers (min = {}, max = {})'. # format(unique.size, unique.min(), unique.max())) # make sure trigger info between beh and bdf data matches missing_trials = [] nr_miss = beh_triggers.size - bdf_triggers.size #logging.info(f'{nr_miss} trials will be removed from beh file') if nr_miss > 0: report_str += f'Behavior has {nr_miss} more trials than detected events. The following trial numbers \ will be removed in attempt to fix this: \n' # check whether trial info is present in beh file if nr_miss > 0 and 'nr_trials' not in beh.columns: raise ValueError('Behavior file does not contain a column with trial info named nr_trials. Please adjust') elif nr_miss < 0: report_str += 'EEG events are removed in an attempt to align the data. Please inspect your data carefully! \n' while nr_miss < 0: # continue to remove bdf triggers until data files are lined up for i, tr in enumerate(beh_triggers): if tr != bdf_triggers[i]: # remove trigger from eeg_file bdf_triggers = np.delete(bdf_triggers, i, axis = 0) nr_miss += 1 # check file sizes if sum(beh_triggers == bdf_triggers) < bdf_triggers.size: raise ValueError('Behavior and eeg cannot be linked as too many eeg triggers received. Please pass indices of trials to be removed \ to subject_info dict with key bdf_remove') while nr_miss > 0: stop = True # continue to remove beh trials until data files are lined up for i, tr in enumerate(bdf_triggers): if tr != beh_triggers[i]: # remove trigger from beh_file miss = beh['nr_trials'].iloc[i] missing_trials.append(i) report_str += f'{miss}, ' #logging.info(f'Removed trial {miss} from beh file,because no matching trigger exists in bdf file') beh.drop(beh.index[i], inplace=True) beh_triggers = np.delete(beh_triggers, i, axis = 0) nr_miss -= 1 stop = False break # check whether there are missing trials at end of beh file if beh_triggers.size > bdf_triggers.size and stop: # drop the last items from the beh file missing_trials = np.hstack((missing_trials, beh['nr_trials'].iloc[-nr_miss:].values)) beh.drop(beh.index[-nr_miss:], inplace=True) #logging.info('Removed last {} trials because no matches detected'.format(nr_miss)) report_str += f'\n Removed final {nr_miss} trials from behavior to allign data. Please inspect your data carefully!' nr_miss = 0 # keep track of missing trials to allign eye tracking data (if available) missing = np.array(missing_trials) beh.reset_index(inplace = True) # add behavior to epochs object self.metadata = beh # log number of matches between beh and bdf #logging.info('{} matches between beh and epoched data out of {}'. # format(sum(beh[trigger_header].values == bdf_triggers), bdf_triggers.size)) report_str += '\n {} matches between beh and epoched data out of {}'.format(sum(beh[trigger_header].values == bdf_triggers), bdf_triggers.size) return missing, report_str def autoRepair(self): ''' ''' # select eeg channels picks = mne.pick_types(self.info, meg=False, eeg=True, stim=False, eog=False, include=[], exclude=[]) # initiate parameters p and k n_interpolates = np.array([1, 4, 32]) consensus_percs = np.linspace(0, 1.0, 11) ar = AutoReject(n_interpolates, consensus_percs, picks=picks, thresh_method='random_search', random_state=42) self, reject_log = ar.fit_transform(self, return_log=True) def select_bad_channels(self, report): # step 1: run ransac bad_chs = self.apply_ransac() # step 2: create report self.report_ransac(bad_chs, report) # step 3: manual inspection def report_ransac(self, bad_chs, report): figs = [] for ch in bad_chs: figs += self.plot_image(picks = ch) report.add_figure(figs, title = 'Bad channels selected by Ransac') def apply_ransac(self): ''' Implements RAndom SAmple Consensus (RANSAC) method to detect bad channels. Returns - - - - self.info['bads']: list with all bad channels detected by the RANSAC algorithm ''' # select channels to display picks = mne.pick_types(self.info, eeg=True, exclude='bads') # use Ransac, interpolating bads and append bad channels to self.info['bads'] ransac = Ransac(verbose=False, picks=picks, n_jobs=1) epochs_clean = ransac.fit_transform(self) print('The following electrodes are selected as bad by Ransac:') print('\n'.join(ransac.bad_chs_)) return ransac.bad_chs_ def selectBadChannels(self, run_ransac = True, channel_plots=True, inspect=True, n_epochs=10, n_channels=32, RT = None): ''' ''' logging.info('Start selection of bad channels') #matplotlib.style.use('classic') # select channels to display picks = mne.pick_types(self.info, eeg=True, exclude='bads') # plot epoched data if channel_plots: for ch in picks: # plot evoked responses across channels try: # handle bug in mne for plotting undefined x, y coordinates plot_epochs_image(self.copy().crop(self.tmin + self.flt_pad,self.tmax - self.flt_pad), ch, show=False, overlay_times = RT) plt.savefig(self.FolderTracker(extension=[ 'preprocessing', 'subject-{}'.format(self.sj), self.session, 'channel_erps'], filename='{}.pdf'.format(self.ch_names[ch]))) plt.close() except: plt.savefig(self.FolderTracker(extension=[ 'preprocessing', 'subject-{}'.format(self.sj), self.session,'channel_erps'], filename='{}.pdf'.format(self.ch_names[ch]))) plt.close() self.plot_psd(picks = [ch], show = False) plt.savefig(self.FolderTracker(extension=[ 'preprocessing', 'subject-{}'.format(self.sj), self.session,'channel_erps'], filename='_psd_{}'.format(self.ch_names[ch]))) plt.close() # plot power spectra topoplot to detect any clear bad electrodes self.plot_psd_topomap(bands=[(0, 4, 'Delta'), (4, 8, 'Theta'), (8, 12, 'Alpha'), ( 12, 30, 'Beta'), (30, 45, 'Gamma'), (45, 100, 'High')], show=False) plt.savefig(self.FolderTracker(extension=[ 'preprocessing', 'subject-{}'.format(self.sj), self.session], filename='psd_topomap.pdf')) plt.close() if run_ransac: self.applyRansac() if inspect: # display raw eeg with 50mV range self.plot(block=True, n_epochs=n_epochs, n_channels=n_channels, picks=picks, scalings=dict(eeg=50)) if self.info['bads'] != []: with open(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(self.sj), self.session], filename='marked_bads.txt'), 'wb') as handle: pickle.dump(self.info['bads'], handle) else: try: with open(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(self.sj), self.session], filename='marked_bads.txt'), 'rb') as handle: self.info['bads'] = pickle.load(handle) print('The following channals were read in as bads from a txt file: {}'.format( self.info['bads'])) except: print('No bad channels selected') logging.info('{} channels marked as bad: {}'.format( len(self.info['bads']), self.info['bads'])) def automatic_artifact_detection(self, z_thresh=4, band_pass=[110, 140], plot=True, inspect=True): """ Detect artifacts> modification of FieldTrip's automatic artifact detection procedure (https://www.fieldtriptoolbox.org/tutorial/automatic_artifact_rejection/). Artifacts are detected in three steps: 1. Filtering the data within specified frequency range 2. Z-transforming the filtered data across channels and normalize it over channels 3. Threshold the accumulated z-score Counter to fieldtrip the z_threshold is ajusted based on the noise level within the data Note: all data included for filter padding is now taken into consideration to calculate z values Afer running this function, Epochs contains information about epeochs marked as bad (self.marked_epochs) Arguments: Keyword Arguments: z_thresh {float|int} -- Value that is added to difference between median and min value of accumulated z-score to obtain z-threshold band_pass {list} -- Low and High frequency cutoff for band_pass filter plot {bool} -- If True save detection plots (overview of z scores across epochs, raw signal of channel with highest z score, z distributions, raw signal of all electrodes) inspect {bool} -- If True gives the opportunity to overwrite selected components """ embed() # select data for artifact rejection sfreq = self.info['sfreq'] self_copy = self.copy() self_copy.pick_types(eeg=True, exclude='bads') #filter data and apply Hilbert self_copy.filter(band_pass[0], band_pass[1], fir_design='firwin', pad='reflect_limited') #self_copy.filter(band_pass[0], band_pass[1], method='iir', iir_params=dict(order=6, ftype='butter')) self_copy.apply_hilbert(envelope=True) # get the data and apply box smoothing data = self_copy.get_data() nr_epochs = data.shape[0] for i in range(data.shape[0]): data[i] = self.boxSmoothing(data[i]) # get the data and z_score over electrodes data = data.swapaxes(0,1).reshape(data.shape[1],-1) z_score = zscore(data, axis = 1) # check whether axis is correct!!!!!!!!!!! # normalize z_score z_score = z_score.sum(axis = 0)/sqrt(data.shape[0]) #z_score = filter_data(z_score, self.info['sfreq'], None, 4, pad='reflect_limited') # adjust threshold (data driven) z_thresh += np.median(z_score) + abs(z_score.min() - np.median(z_score)) # transform back into epochs z_score = z_score.reshape(nr_epochs, -1) # control for filter padding if self.flt_pad > 0: idx_ep = self.time_as_index([self.tmin + self.flt_pad, self.tmax - self.flt_pad]) z_score = z_score[:, slice(*idx_ep)] # mark bad epochs bad_epochs = [] cnt = 0 for ep, X in enumerate(z_score): noise_smp = np.where(X > z_thresh)[0] if noise_smp.size > 0: bad_epochs.append(ep) if inspect: print('This interactive window selectively shows epochs marked as bad. You can overwrite automatic artifact detection by clicking on selected epochs') bad_eegs = self[bad_epochs] idx_bads = bad_eegs.selection # display bad eegs with 50mV range bad_eegs.plot( n_epochs=5, n_channels=data.shape[1], scalings=dict(eeg = 50)) plt.show() plt.close() missing = np.array([list(idx_bads).index(idx) for idx in idx_bads if idx not in bad_eegs.selection],dtype = int) logging.info('Manually ignored {} epochs out of {} automatically selected({}%)'.format( missing.size, len(bad_epochs),100 * round(missing.size / float(len(bad_epochs)), 2))) bad_epochs = np.delete(bad_epochs, missing) if plot: plt.figure(figsize=(10, 10)) with sns.axes_style('dark'): plt.subplot(111, xlabel='samples', ylabel='z_value', xlim=(0, z_score.size), ylim=(-20, 40)) plt.plot(np.arange(0, z_score.size), z_score.flatten(), color='b') plt.plot(np.arange(0, z_score.size), np.ma.masked_less(z_score.flatten(), z_thresh), color='r') plt.axhline(z_thresh, color='r', ls='--') plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='automatic_artdetect.pdf')) plt.close() # drop bad epochs and save list of dropped epochs self.drop_beh = bad_epochs np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='noise_epochs.txt'), bad_epochs) print('{} epochs dropped ({}%)'.format(len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))) logging.info('{} epochs dropped ({}%)'.format( len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))) self.drop(np.array(bad_epochs), reason='art detection ecg') logging.info('{} epochs left after artifact detection'.format(len(self))) np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(self.sj), self.session], filename='automatic_artdetect.txt'), ['Artifact detection z threshold set to {}. \n{} epochs dropped ({}%)'. format(round(z_thresh, 1), len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))], fmt='%.100s') return z_thresh def artifactDetectionOLD(self, z_cutoff=4, band_pass=[110, 140], min_dur = 0.05, min_nr_art = 1, run = True, plot=True, inspect=True): """ Detect artifacts based on FieldTrip's automatic artifact detection. Artifacts are detected in three steps: 1. Filtering the data (6th order butterworth filter) 2. Z-transforming the filtered data and normalize it over channels 3. Threshold the accumulated z-score False-positive transient peaks are prevented by low-pass filtering the resulting z-score time series at 4 Hz. Afer running this function, Epochs contains information about epeochs marked as bad (self.marked_epochs) Arguments: Keyword Arguments: z_cuttoff {int} -- Value that is added to difference between median nd min value of accumulated z-score to obtain z-threshold band_pass {list} -- Low and High frequency cutoff for band_pass filter min_dur {float} -- minimum duration of detected artefects to be considered an artefact min_nr_art {int} -- minimum number of artefacts that may be present in an epoch (irrespective of min_dur) run {bool} -- specifies whether analysis is run a new or whether bad epochs are read in from memory plot {bool} -- If True save detection plots (overview of z scores across epochs, raw signal of channel with highest z score, z distributions, raw signal of all electrodes) inspect {bool} -- If True gives the opportunity to overwrite selected components time {tuple} -- Time window used for decoding tr_header {str} -- Name of column that contains training labels te_header {[type]} -- Name of column that contains testing labels """ # select channels for artifact detection picks = mne.pick_types(self.info, eeg=True, exclude='bads') nr_channels = picks.size sfreq = self.info['sfreq'] # control for filter padding if self.flt_pad > 0: idx_ep = self.time_as_index([self.tmin + self.flt_pad, self.tmax - self.flt_pad]) timings = self.times[idx_ep[0]:idx_ep[1]] ep_data = [] # STEP 1: filter each epoch data, apply hilbert transform and boxsmooth # the resulting data before removing filter padds if run: print('Started artifact detection') logging.info('Started artifact detection') for epoch, X in enumerate(self): # CHECK IF THIS IS CORRECT ORDER IN FIELDTRIP CODE / ALSO CHANGE # FILTER TO MNE 0.14 STANDARD X = filter_data(X[picks, :], sfreq, band_pass[0], band_pass[ 1], method='iir', iir_params=dict(order=6, ftype='butter')) X = np.abs(sp.signal.hilbert(X)) X = self.boxSmoothing(X) X = X[:, idx_ep[0]:idx_ep[1]] ep_data.append(X) # STEP 2: Z-transform data epoch = np.hstack(ep_data) avg_data = epoch.mean(axis=1).reshape(-1, 1) std_data = epoch.std(axis=1).reshape(-1, 1) z_data = [(ep - avg_data) / std_data for ep in ep_data] # STEP 3 threshold z-score per epoch z_accumel = np.hstack(z_data).sum(axis=0) / sqrt(nr_channels) z_accumel_ep = [np.array(z.sum(axis=0) / sqrt(nr_channels)) for z in z_data] z_thresh = np.median( z_accumel) + abs(z_accumel.min() - np.median(z_accumel)) + z_cutoff # split noise epochs based on start and end time # and select bad epochs based on specified criteria bad_epochs = [] for ep, X in enumerate(z_accumel_ep): noise_smp = np.where((X > z_thresh) == True)[0] noise_smp = np.split(noise_smp, np.where(np.diff(noise_smp) != 1)[0]+1) time_inf = [timings[smp[-1]] - timings[smp[0]] for smp in noise_smp if smp.size > 0] if len(time_inf) > 0: if max(time_inf) > min_dur or len(time_inf) > min_nr_art: bad_epochs.append(ep) if plot: plt.figure(figsize=(10, 10)) with sns.axes_style('dark'): plt.subplot(111, xlabel='samples', ylabel='z_value', xlim=(0, z_accumel.size), ylim=(-20, 40)) plt.plot(np.arange(0, z_accumel.size), z_accumel, color='b') plt.plot(np.arange(0, z_accumel.size), np.ma.masked_less(z_accumel, z_thresh), color='r') plt.axhline(z_thresh, color='r', ls='--') plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='automatic_artdetect.pdf')) plt.close() bad_epochs = np.array(bad_epochs) else: logging.info('Bad epochs read in from file') bad_epochs = np.loadtxt(self.FolderTracker(extension=[ 'preprocessing', 'subject-{}'.format(self.sj), self.session], filename='noise_epochs.txt')) if inspect: print('You can now overwrite automatic artifact detection by clicking on epochs selected as bad') bad_eegs = self[bad_epochs] idx_bads = bad_eegs.selection # display bad eegs with 50mV range bad_eegs.plot( n_epochs=5, n_channels=picks.size, picks=picks, scalings=dict(eeg = 50)) plt.show() plt.close() missing = np.array([list(idx_bads).index(idx) for idx in idx_bads if idx not in bad_eegs.selection], dtype = int) logging.info('Manually ignored {} epochs out of {} automatically selected({}%)'.format( missing.size, bad_epochs.size,100 * round(missing.size / float(bad_epochs.size), 2))) bad_epochs = np.delete(bad_epochs, missing) # drop bad epochs and save list of dropped epochs np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='noise_epochs.txt'), bad_epochs) print('{} epochs dropped ({}%)'.format(len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))) logging.info('{} epochs dropped ({}%)'.format( len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))) self.drop(np.array(bad_epochs), reason='art detection ecg') logging.info('{} epochs left after artifact detection'.format(len(self))) if run: np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(self.sj), self.session], filename='automatic_artdetect.txt'), ['Artifact detection z threshold set to {}. \n{} epochs dropped ({}%)'. format(round(z_thresh, 1), len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))], fmt='%.100s') def boxSmoothing(self, data, box_car=0.2): ''' doc string boxSmoothing ''' pad = int(round(box_car * self.info['sfreq'])) if pad % 2 == 0: # the kernel should have an odd number of samples pad += 1 kernel = np.ones(pad) / pad pad = int(ceil(pad / 2)) pre_pad = int(min([pad, floor(data.shape[1]) / 2.0])) edge_left = data[:, :pre_pad].mean(axis=1) edge_right = data[:, -pre_pad:].mean(axis=1) data = np.concatenate((np.tile(edge_left.reshape(data.shape[0], 1), pre_pad), data, np.tile( edge_right.reshape(data.shape[0], 1), pre_pad)), axis=1) data_smooth = sp.signal.convolve2d( data, kernel.reshape(1, kernel.shape[0]), 'same') data = data_smooth[:, pad:(data_smooth.shape[1] - pad)] return data def link_eye(self, eye_info, missing, vEOG, hEOG): # select eog channels eog = self.copy().pick_types(eeg=False, eog=True) # # rerefence EOG data (vertical and horizontal) idx_v = [eog.ch_names.index(vert) for vert in vEOG] idx_h = [eog.ch_names.index(hor) for hor in hEOG] if len(idx_v) == 2: eog._data[idx_v[0]] -= eog._data[idx_v[1]] if len(idx_h) == 2: eog._data[idx_h[0]] -= eog._data[idx_h[1]] print( 'EOG data (VEOG, HEOG) rereferenced with subtraction and renamed EOG channels') logging.info( 'EOG data (VEOG, HEOG) rereferenced with subtraction and renamed EOG channels') # # add rereferenced vEOG and hEOG data to self ch_mapping = {vEOG[0]: 'VEOG', hEOG[0]: 'HEOG'} eog.rename_channels(ch_mapping) eog.drop_channels([vEOG[1], hEOG[1]]) self.add_channels([eog]) # CODE FOR EYETRACKER DATA EO = EYE(sfreq = eye_info['sfreq'], viewing_dist = eye_info['viewing_dist'], screen_res = eye_info['screen_res'], screen_h = eye_info['screen_h']) # do binning based on eye-tracking data (if eyetracker data exists) eye_bins, window_bins, trial_nrs = EO.eyeBinEEG(self.sj, int(self.session), int((self.tmin + self.flt_pad + eye_info['tracker_shift'])*1000), int((self.tmax - self.flt_pad + eye_info['tracker_shift'])*1000), drift_correct = (-200,0), start_event = eye_info['start_event'], extension = eye_info['tracker_ext']) if missing.size > 0: eye_bins = np.delete(eye_bins, missing) self.metadata['eye_bins'] = eye_bins def detectEye(self, missing, events, nr_events, time_window, threshold=20, windowsize=100, windowstep=10, channel='HEOG', tracker_shift = 0, start_event = '', extension = 'asc', eye_freq = 500, screen_res = (1680, 1050), viewing_dist = 60, screen_h = 29): ''' Marking epochs containing step-like activity that is greater than a given threshold Arguments - - - - - self(object): Epochs object missing events (array): nr_events (int): time_window (tuple): start and end time in seconds threshold (int): range of amplitude in microVolt windowsize (int): total moving window width in ms. So each window's width is half this value windowsstep (int): moving window step in ms channel (str): name of HEOG channel tracker_shift (float): specifies difference in ms between onset trigger and event in eyetracker data start_event (str): marking onset of trial in eyetracker data extension (str): type of eyetracker file (now supports .asc/ .tsv) eye_freq (int): sampling rate of the eyetracker Returns - - - - ''' self.eye_bins = True sac_epochs = [] # CODE FOR HEOG DATA idx_ch = self.ch_names.index(channel) idx_s, idx_e = tuple([np.argmin(abs(self.times - t)) for t in time_window]) windowstep /= 1000 / self.info['sfreq'] windowsize /= 1000 / self.info['sfreq'] for i in range(len(self)): up_down = 0 for j in np.arange(idx_s, idx_e - windowstep, windowstep): w1 = np.mean(self._data[i, idx_ch, int( j):int(j + windowsize / 2) - 1]) w2 = np.mean(self._data[i, idx_ch, int( j + windowsize / 2):int(j + windowsize) - 1]) if abs(w1 - w2) > threshold: up_down += 1 if up_down == 2: sac_epochs.append(i) break logging.info('Detected {0} epochs ({1:.2f}%) with a saccade based on HEOG'.format( len(sac_epochs), len(sac_epochs) / float(len(self)) * 100)) # CODE FOR EYETRACKER DATA EO = EYE(sfreq = eye_freq, viewing_dist = viewing_dist, screen_res = screen_res, screen_h = screen_h) # do binning based on eye-tracking data (if eyetracker data exists) eye_bins, window_bins, trial_nrs = EO.eyeBinEEG(self.sj, int(self.session), int((self.tmin + self.flt_pad + tracker_shift)*1000), int((self.tmax - self.flt_pad + tracker_shift)*1000), drift_correct = (-200,0), start_event = start_event, extension = extension) if eye_bins.size > 0: logging.info('Window method detected {} epochs exceeding 0.5 threshold'.format(window_bins.size)) # remove trials that could not be linked to eeg trigger if missing.size > 0: eye_bins = np.delete(eye_bins, missing) dropped = trial_nrs[missing] logging.info('{} trials removed from eye data to align to eeg. Correspond to trial_nr {} in beh'.format(missing.size, dropped)) # remove trials that have been deleted from eeg eye_bins = np.delete(eye_bins, self.drop_beh) # log eyetracker info unique_bins = np.array(np.unique(eye_bins), dtype = np.float64) for eye_bin in np.unique(unique_bins[~np.isnan(unique_bins)]): logging.info('{0:.1f}% of trials exceed {1} degree of visual angle'.format(sum(eye_bins> eye_bin) / eye_bins.size*100, eye_bin)) # save array of deviation bins np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='eye_bins.txt'), eye_bins) # # correct for missing data (if eye recording is stopped during experiment) # if eye_bins.size > 0 and eye_bins.size < self.nr_events: # # create array of nan values for all epochs (UGLY CODING!!!) # temp = np.empty(self.nr_events) * np.nan # temp[trial_nrs - 1] = eye_bins # eye_bins = temp # temp = (np.empty(self.nr_events) * np.nan) # temp[trial_nrs - 1] = trial_nrs # trial_nrs = temp # elif eye_bins.size == 0: # eye_bins = np.empty(self.nr_events + missing.size) * np.nan # trial_nrs = np.arange(self.nr_events + missing.size) + 1 def applyICA(self, raw, ica_fit, method='extended-infomax', decim=None, fit_params = None, inspect = True): ''' Arguments - - - - - self(object): Epochs object raw (object): n_components (): method (str): decim (): Returns - - - - self ''' # make sure that bad electrodes and 'good' epochs match between both data sets ica_fit.info['bads'] = self.info['bads'] if str(type(ica_fit))[-3] == 's': print('fitting data on epochs object') to_drop = [i for i, v in enumerate(ica_fit.selection) if v not in self.selection] ica_fit.drop(to_drop) # initiate ica logging.info('Started ICA') picks = mne.pick_types(self.info, eeg=True, exclude='bads') ica = ICA(n_components=picks.size, method=method, fit_params = fit_params) # ica is fitted on epoched data ica.fit(ica_fit, picks=picks, decim=decim) # plot the components ica.plot_components(colorbar=True, picks=range(picks.size), show=False) plt.savefig(self.FolderTracker(extension=[ 'preprocessing', 'subject-{}'.format(self.sj), self.session], filename='components.pdf')) plt.close() # advanced artifact detection eog_epochs = create_eog_epochs(raw, baseline=(None, None)) eog_inds_a, scores = ica.find_bads_eog(eog_epochs) ica.plot_scores(scores, exclude=eog_inds_a, show=False) plt.savefig(self.FolderTracker(extension=[ 'preprocessing', 'subject-{}'.format(self.sj), self.session], filename='ica_scores.pdf')) plt.close() # diagnostic plotting ica.plot_sources(self, show_scrollbars=False, show=False) if inspect: plt.show() else: plt.savefig(self.FolderTracker(extension=[ 'preprocessing', 'subject-{}'.format(self.sj), self.session], filename='sources.pdf')) plt.close() # double check selected component with user input time.sleep(5) tcflush(sys.stdin, TCIFLUSH) print('You are preprocessing subject {}, session {}'.format(self.sj, self.session)) conf = input( 'Advanced detection selected component(s) {}. Do you agree (y/n)'.format(eog_inds_a)) if conf == 'y': eog_inds = eog_inds_a else: eog_inds = [] nr_comp = input( 'How many components do you want to select (<10)?') for i in range(int(nr_comp)): eog_inds.append( int(input('What is component nr {}?'.format(i + 1)))) for i, cmpt in enumerate(eog_inds): ica.plot_properties(self, picks=cmpt, psd_args={ 'fmax': 35.}, image_args={'sigma': 1.}, show=False) plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='property{}.pdf'.format(cmpt))) plt.close() ica.plot_overlay(raw, exclude=eog_inds, picks=[self.ch_names.index(e) for e in [ 'Fp1', 'Fpz', 'Fp2', 'AF7', 'AF3', 'AFz', 'AF4', 'AF8']], show = False) plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='ica-frontal.pdf')) plt.close() ica.plot_overlay(raw, exclude=eog_inds, picks=[self.ch_names.index(e) for e in [ 'PO7', 'PO8', 'PO3', 'PO4', 'O1', 'O2', 'POz', 'Oz','Iz']], show = False) plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='ica-posterior.pdf')) plt.close() # remove selected component ica.apply(self, exclude=eog_inds) logging.info( 'The following components were removed from raw eeg with ica: {}'.format(eog_inds)) def save_preprocessed(self, preproc_name, combine_sessions: bool = True): # save eeg self.save(self.FolderTracker(extension=[ 'processed'], filename=f'subject-{self.sj}_ses-{self.session}_{preproc_name}-epo.fif'), split_size='2GB', overwrite = True) # check whether individual sessions need to be combined if combine_sessions and int(self.session) != 1: all_eeg = [] for i in range(int(self.session)): session = i + 1 all_eeg.append(mne.read_epochs(self.FolderTracker(extension=[ 'processed'], filename=f'subject-{self.sj}_ses-{session}_{preproc_name}-epo.fif'))) all_eeg = mne.concatenate_epochs(all_eeg) all_eeg.save(self.FolderTracker(extension=[ 'processed'], filename=f'subject-{self.sj}_all_{preproc_name}-epo.fif'), split_size='2GB', overwrite = True) def link_behavior(self, beh: pd.DataFrame, combine_sessions: bool = True): """ Saves linked eeg and behavior data. Preprocessed eeg is saved in the folder processed and behavior is saved in a processed subfolder of beh. Args: beh (pd.DataFrame): behavioral dataframe containing parameters of interest combine_sessions (bool, optional):If experiment contains seperate sessions, these are combined into a single datafile that is saved alongside the individual sessions. Defaults to True. """ # update beh dict after removing noise trials beh.drop(self.drop_beh, axis = 'index', inplace = True) # also include eye binned data if hasattr(self, 'eye_bins'): eye_bins = np.loadtxt(self.FolderTracker(extension=[ 'preprocessing', 'subject-{}'.format(self.sj), self.session], filename='eye_bins.txt')) else: eye_bins = np.nan beh['eye_bins'] = pd.Series(eye_bins) # save behavior as pickle beh_dict = beh.to_dict(orient = 'list') with open(self.FolderTracker(extension=['beh', 'processed'], filename='subject-{}_ses-{}.pickle'.format(self.sj, self.session)), 'wb') as handle: pickle.dump(beh_dict, handle) # save eeg self.save(self.FolderTracker(extension=[ 'processed'], filename='subject-{}_ses-{}-epo.fif'.format(self.sj, self.session)), split_size='2GB', overwrite = True) # update preprocessing information logging.info('Nr clean trials is {0}'.format(beh.shape[0])) if 'condition' in beh.index: cnd = beh['condition'].values min_cnd, cnd = min([sum(cnd == c) for c in np.unique(cnd)]), np.unique(cnd)[ np.argmin([sum(cnd == c) for c in np.unique(cnd)])] logging.info( 'Minimum condition ({}) number after cleaning is {}'.format(cnd, min_cnd)) else: logging.info('no condition found in beh file') logging.info('EEG data linked to behavior file') # check whether individual sessions need to be combined if combine_sessions and int(self.session) != 1: # combine eeg and beh files of seperate sessions all_beh = [] all_eeg = [] nr_events = [] for i in range(int(self.session)): with open(self.FolderTracker(extension=['beh', 'processed'], filename='subject-{}_ses-{}.pickle'.format(self.sj, i + 1)), 'rb') as handle: all_beh.append(pickle.load(handle)) all_eeg.append(mne.read_epochs(self.FolderTracker(extension=[ 'processed'], filename='subject-{}_ses-{}-epo.fif'.format(self.sj, i + 1)))) # do actual combining for key in beh_dict.keys(): beh_dict.update( {key: np.hstack([beh[key] for beh in all_beh])}) with open(self.FolderTracker(extension=['beh', 'processed'], filename='subject-{}_all.pickle'.format(self.sj)), 'wb') as handle: pickle.dump(beh_dict, handle) all_eeg = mne.concatenate_epochs(all_eeg) all_eeg.save(self.FolderTracker(extension=[ 'processed'], filename='subject-{}_all-epo.fif'.format(self.sj)), split_size='2GB', overwrite = True) logging.info('EEG sessions combined') class ArtefactReject(object): """ Multiple (automatic artefact rejection procedures) Work in progress """ def __init__(self, z_thresh: float = 4.0, max_bad: int = 5, flt_pad: float = 0, filter_z: bool = True): self.flt_pad = flt_pad self.filter_z = filter_z self.z_thresh = z_thresh self.max_bad = max_bad def run_blink_ICA(self, fit_inst, raw, ica_inst, sj ,session, method = 'picard', threshold = 0.9, report = None, report_path = None): # step 1: fit the data ica = self.fit_ICA(fit_inst, method = 'picard') # step 2: select the blink component (assumed to be component 1) eog_epochs, eog_inds, eog_scores = self.automated_ica_blink_selection(ica, raw, threshold = threshold) ica.exclude = [eog_inds[0]] if report is not None: report.add_ica( ica=ica, title='ICA blink cleaning', picks=range(15), inst=eog_epochs, eog_evoked=eog_epochs.average(), eog_scores=eog_scores[0], ) report.save(report_path, overwrite = True) #step 2a: manually check selected component ica = self.manual_check_ica(ica, sj, session) # step 3: apply ica ica_inst = self.apply_ICA(ica, ica_inst) return ica_inst def fit_ICA(self, fit_inst, method = 'picard'): if method == 'picard': fit_params = dict(fastica_it=5) elif method == 'extended_infomax': fit_params = dict(extended=True) elif method == 'fastica': fit_params = None #logging.info('started fitting ICA') picks = mne.pick_types(fit_inst.info, eeg=True, exclude='bads') ica = ICA(n_components=picks.size-1, method=method, fit_params = fit_params, random_state=97) # do actual fitting ica.fit(fit_inst, picks=picks) return ica def automated_ica_blink_selection(self, ica, raw, threshold = 0.9): pick_eog = mne.pick_types(raw.info, meg=False, eeg=False, ecg=False, eog=True) ch_names = [raw.info['ch_names'][pick] for pick in pick_eog] if pick_eog.any(): # create blink epochs eog_epochs = create_eog_epochs(raw, ch_name=ch_names, baseline=(None, -0.2), tmin=-0.5, tmax=0.5) eog_inds, eog_scores = ica.find_bads_eog( eog_epochs, threshold=threshold) else: eog_epochs = None eog_inds = list() print('No EOG channel is present. Cannot automate IC detection ' 'for EOG') return eog_epochs, eog_inds, eog_scores def manual_check_ica(self, ica, sj, session): time.sleep(5) tcflush(sys.stdin, TCIFLUSH) print('You are preprocessing subject {}, session {}'.format(sj, session)) conf = input( 'Advanced detection selected component(s) {} (see report). Do you agree (y/n)?'.format(ica.exclude)) if conf == 'n': eog_inds = [] nr_comp = input( 'How many components do you want to select (<10)?') for i in range(int(nr_comp)): eog_inds.append( int(input('What is component nr {}?'.format(i + 1)))) ica.exclude = eog_inds return ica def apply_ICA(self, ica, ica_inst): # remove selected component ica_inst = ica.apply(ica_inst) return ica_inst def visualize_blinks(self, raw): eog_epochs = create_eog_epochs(raw, ch_name = ['V_up', 'V_do', 'Fp1','Fpz','Fp2'], baseline=(-0.5, -0.2)) eog_epochs.plot_image(combine='mean') plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( epochs.sj), epochs.session, 'ica'], filename=f'raw_blinks_combined.pdf')) eog_epochs.average().plot_joint() plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( epochs.sj), epochs.session, 'ica'], filename=f'raw_blinks_topo.pdf')) def update_heat_map(self, channels, ch_idx, tr_idx, upd_value): self.heat_map[tr_idx, ch_idx] = upd_value if upd_value == -1: # bad epoch for ch in channels[ch_idx]: self.not_cleaned_info[ch] += 1 else: # cleaned_epoch for ch in channels[ch_idx]: self.cleaned_info[ch] += 1 def plot_auto_repair(self, channels): figs = [] # plot heat_map fig, ax = plt.subplots(1) #sns.despine(offset = 10) plt.title('Interpolated electrodes per marked epoch \n (blue is bad epochs, red is cleaned epoch)') ax.imshow(self.heat_map, aspect = 'auto', cmap = 'bwr', interpolation = 'nearest', vmin = -1, vmax = 1) ax.set(xlabel='channel', ylabel='bad epochs') ax.set_xticks(np.arange(channels.size)) ax.set_xticklabels(channels, fontsize=6, rotation = 90) figs.append(fig) # plot histogram of bad channels clean_df = pd.DataFrame.from_dict(self.cleaned_info, orient = 'index', columns=['count']) clean_df = clean_df.loc[(clean_df != 0).any(axis=1)] if clean_df.size > 0: # marked at least one bad epoch fig, ax = plt.subplots(1) sns.despine(offset = 10) plt.title('Electrode count per cleaned epoch') ax.barh(np.arange(clean_df.values.size), np.hstack(clean_df.values)) ax.set_yticks(np.arange(clean_df.values.size)) ax.set_yticklabels(clean_df.index, fontsize=5) figs.append(fig) noise_df = pd.DataFrame.from_dict(self.not_cleaned_info, orient = 'index', columns=['count']) noise_df = noise_df.loc[(noise_df != 0).any(axis=1)] if noise_df.size > 0: # marked at least one bad epoch fig, ax = plt.subplots(1) sns.despine(offset = 10) plt.title('Electrode count per noise epoch (i.e., not cleaned') ax.barh(np.arange(noise_df.values.size), np.hstack(noise_df.values)) ax.set_yticks(np.arange(noise_df.values.size)) ax.set_yticklabels(noise_df.index, fontsize=5) figs.append(fig) return figs # # show bad epochs # all_epochs = np.arange(len(epochs)) # all_epochs = np.delete(all_epochs, bad_epochs) # for plot, title in zip([bad_epochs, cleaned_epochs, all_epochs], ['bad_epochs', 'cleaned_epochs', 'all_epochs']): # epochs[plot].average().plot(spatial_colors = True, gfp = True) # plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( # epochs.sj), epochs.session], filename=f'{title}.pdf')) # plt.close() @blockPrinting def iterative_interpolation(self, epochs, elecs_z, noise_inf, z_thresh, band_pass): # keep track of channel info for plotting purposes picks = mne.pick_types(epochs.info, eeg=True, exclude= 'bads') channels = np.array(epochs.info['ch_names'])[picks] self.heat_map = np.zeros((len(noise_inf), channels.size)) self.cleaned_info = dict.fromkeys(channels, 0) self.not_cleaned_info = dict.fromkeys(channels, 0) # track bad and cleaned epochs bad_epochs, cleaned_epochs = [], [] for i, event in enumerate(noise_inf): bad_epoch = epochs[event[0]] # search for bad channels in detected artefact periods z = np.concatenate([elecs_z[event[0]][:,slice_[0]] for slice_ in event[1:]], axis = 1) # limit interpolation to 'max_bad' noisiest channels ch_idx = np.argsort(z.mean(axis = 1))[-self.max_bad:][::-1] interp_chs = channels[ch_idx] for c, ch in enumerate(interp_chs): # update heat map bad_epoch.info['bads'] += [ch] bad_epoch.interpolate_bads(exclude = epochs.info['bads']) epochs._data[event[0]] = bad_epoch._data # repeat preprocesing after interpolation to check whether epoch is now 'clean' Z_, _, _, _ = self.preprocess_epochs(epochs[event[0]], band_pass = band_pass) if not np.any(abs(Z_) > z_thresh): # epoch no longer marked as bad break if ch == interp_chs[-1]: self.update_heat_map(channels, ch_idx[:c+1], i, -1) bad_epochs.append(event[0]) else: self.update_heat_map(channels, ch_idx[:c+1], i, 1) cleaned_epochs.append(event[0]) return epochs, bad_epochs, cleaned_epochs def auto_repair_noise(self, epochs: mne.Epochs, band_pass: list =[110, 140], z_thresh: float = 4.0, report: mne.Report = None): # z score data (after hilbert transform) Z, elecs_z, z_thresh, times = self.preprocess_epochs(epochs, band_pass = band_pass) # mark noise epochs noise_inf = self.mark_bads(Z,z_thresh,times) # clean epochs epochs, bad_epochs, cleaned_epochs = self.iterative_interpolation(epochs, elecs_z, noise_inf, z_thresh, band_pass) picks = mne.pick_types(epochs.info, eeg=True, exclude= 'bads') # drop bad epochs epochs.drop(np.array(bad_epochs), reason='Artefact reject') if report is not None: channels = np.array(epochs.info['ch_names'])[picks] report.add_figure(self.plot_auto_repair(channels), title = 'Iterative z cleaning procedure') return epochs, z_thresh, report print('This interactive window selectively shows epochs marked as bad. You can overwrite automatic artifact detection by clicking on selected epochs') bad_eegs = self[bad_epochs] idx_bads = bad_eegs.selection # display bad eegs with 50mV range bad_eegs.plot( n_epochs=5, n_channels=data.shape[1], scalings=dict(eeg = 50)) plt.show() plt.close() missing = np.array([list(idx_bads).index(idx) for idx in idx_bads if idx not in bad_eegs.selection],dtype = int) logging.info('Manually ignored {} epochs out of {} automatically selected({}%)'.format( missing.size, len(bad_epochs),100 * round(missing.size / float(len(bad_epochs)), 2))) bad_epochs = np.delete(bad_epochs, missing) def preprocess_epochs(self, epochs: mne.Epochs, band_pass: list =[110, 140]): # set params flt_pad = self.flt_pad times = epochs.times tmin, tmax = epochs.tmin, epochs.tmax sfreq = epochs.info['sfreq'] # filter data, apply hilbert (limited to 'good' EEG channels) and smooth the data (using defaults) X = self.apply_hilbert(epochs, band_pass[0], band_pass[1]) X = self.box_smoothing(X, sfreq) # z score data (while ignoring flt_pad samples) using default settings mask = np.logical_and(tmin + self.flt_pad <= times, times <= tmax - self.flt_pad) Z, elecs_z, z_thresh = self.z_score_data(X, self.z_thresh, mask, (self.filter_z, sfreq)) # control for filter padding time_idx = epochs.time_as_index([tmin + flt_pad, tmax - flt_pad]) Z = Z[:, slice(*time_idx)] elecs_z = elecs_z[:,:,slice(*time_idx)] times = times[slice(*time_idx)] return Z, elecs_z, z_thresh, times def apply_hilbert(self, epochs: mne.Epochs, lower_band: int = 110, upper_band: int = 140) -> np.array: """ Takes an mne epochs object as input and returns the eeg data after Hilbert transform Args: epochs (mne.Epochs): mne epochs object before muscle artefact detection lower_band (int, optional): Lower limit of the bandpass filter. Defaults to 110. upper_band (int, optional): Upper limit of the bandpass filter. Defaults to 140. Returns: X (np.array): eeg data after applying hilbert transform within the given frequency band """ # exclude channels that are marked as overall bad epochs_ = epochs.copy() epochs_.pick_types(eeg=True, exclude='bads') # filter data and apply Hilbert epochs_.filter(lower_band, upper_band, fir_design='firwin', pad='reflect_limited') epochs_.apply_hilbert(envelope=True) # get data X = epochs_.get_data() del epochs_ return X def filt_pad(self, X: np.array, pad_length: int) -> np.array: """ performs padding (using local mean method) on the data, i.e., adds samples before and after the data TODO: MOVE to signal processing folder (see https://github.com/fieldtrip/fieldtrip/blob/master/preproc/ft_preproc_padding.m)) Args: X (np.array): 2-dimensional array [nr_elec X nr_time] pad_length (int): number of samples that will be padded Returns: X (np.array): 2-dimensional array with padded data [nr_elec X nr_time] """ # set number of pad samples pre_pad = int(min([pad_length, floor(X.shape[1]) / 2.0])) # get local mean on both sides edge_left = X[:, :pre_pad].mean(axis=1) edge_right = X[:, -pre_pad:].mean(axis=1) # pad data X = np.concatenate((np.tile(edge_left.reshape(X.shape[0], 1), pre_pad), X, np.tile( edge_right.reshape(X.shape[0], 1), pre_pad)), axis=1) return X def box_smoothing(self, X: np.array, sfreq: float, boxcar: float = 0.2) -> np.array: """ performs boxcar smoothing with specified length. Modified version of ft_preproc_smooth as implemented in the FieldTrip toolbox (https://www.fieldtriptoolbox.org) Args: X (np.array): 3-dimensional array [nr_epoch X nr_elec X nr_time] sfreq (float): sampling frequency boxcar (float, optional): parameter that determines the length of the filter kernel. Defaults to 0.2 (optimal accrding to fieldtrip documentation). Returns: np.array: [description] """ # create smoothing kernel pad = int(round(boxcar * sfreq)) # make sure that kernel has an odd number of samples if pad % 2 == 0: pad += 1 kernel = np.ones(pad) / pad # padding and smoothing functions expect 2-d input (nr_elec X nr_time) pad_length = int(ceil(pad / 2)) for i, x in enumerate(X): # pad the data x = self.filt_pad(x, pad_length = pad_length) # smooth the data x_smooth = sp.signal.convolve2d( x, kernel.reshape(1, kernel.shape[0]), 'same') X[i] = x_smooth[:, pad_length:(x_smooth.shape[1] - pad_length)] return X def z_score_data(self, X: np.array, z_thresh: int = 4, mask: np.array = None, filter_z: tuple = (False, 512)) -> Tuple[np.array, np.array, float]: """ Z scores input data over the second dimension (i.e., electrodes). The z threshold, which is used to mark artefact segments, is then calculated using a data driven approach, where the upper limit of the 'bandwith' of obtained z scores is added to the provided default threshold. Also returns z scored data per electrode which can be used during iterative automatic cleaning procedure. Args: X (np.array): 3-dimensional array of [trial repeats by electrodes by time points]. z_thresh (int, optional): starting z value cut off. Defaults to 4. mask (np.array, optional): a boolean array that masks out time points such that they are excluded during z scoring. Note these datapoints are still returned in Z_n and elecs_z (see below). filter_z (tuple, optional): prevents false-positive transient peaks by low-pass filtering the resulting z-score time series at 4 Hz. Note: Should never be used without filter padding the data. Second argument in the tuple specifies the sampling frequency. Defaults to False, i.e., no filtering. Returns: Z_n (np.array): 2-dimensional array of normalized z scores across electrodes[trial repeats by time points]. elecs_z (np.array): 3-dimensional array of z scores data per sample [trial repeats by electrodes by time points]. z_thresh (float): z_score theshold used to mark segments of muscle artefacts """ # set params nr_epoch, nr_elec, nr_time = X.shape # get the data and z_score over electrodes X = X.swapaxes(0,1).reshape(nr_elec,-1) X_z = zscore(X, axis = 1) if mask is not None: mask = np.tile(mask, nr_epoch) X_z[:, mask] = zscore(X[:,mask], axis = 1) # reshape to get get epoched data in terms of z scores elecs_z = X_z.reshape(nr_elec, nr_epoch,-1).swapaxes(0,1) # normalize z_score Z_n = X_z.sum(axis = 0)/sqrt(nr_elec) if mask is not None: Z_n[mask] = X_z[:,mask].sum(axis = 0)/sqrt(nr_elec) if filter_z[0]: Z_n = filter_data(Z_n, filter_z[1], None, 4, pad='reflect_limited') # adjust threshold (data driven) if mask is None: mask = np.ones(Z_n.size, dtype = bool) z_thresh += np.median(Z_n[mask]) + abs(Z_n[mask].min() - np.median(Z_n[mask])) # transform back into epochs Z_n = Z_n.reshape(nr_epoch, -1) return Z_n, elecs_z, z_thresh def mark_bads(self, Z: np.array, z_thresh: float, times: np.array) -> list: """ Marks which epochs contain samples that exceed the data driven z threshold (as set by z_score_data). Outputs a list with marked epochs. Per marked epoch alongside the index, a slice of the artefact, the start and end point and the duration of the artefact are saved Args: Z (np.array): 2-dimensional array of normalized z scores across electrodes [trial repeats by time points] z_thresh (float): z_score theshold used to mark segments of muscle artefacts times (np.array): sample time points Returns: noise_events (list): indices of marked epochs. Per epoch time information of each artefact is logged [idx, (artefact slice, start_time, end_time, duration)] """ # start with empty list noise_events = [] # loop over each epoch for ep, x in enumerate(Z): # mask noise samples noise_mask = abs(x) > z_thresh # get start and end point of continuous noise segments starts = np.argwhere((~noise_mask[:-1] & noise_mask[1:])) if noise_mask[0]: starts = np.insert(starts, 0, 0) ends = np.argwhere((noise_mask[:-1] & ~noise_mask[1:])) + 1 # update noise_events if starts.size > 0: starts = np.hstack(starts) if ends.size == 0: ends = np.array([times.size-1]) else: ends = np.hstack(ends) ep_noise = [ep] + [(slice(s, e), times[s],times[e], abs(times[e] - times[s])) for s,e in zip(starts, ends)] noise_events.append(ep_noise) return noise_events def automatic_artifact_detection(self, z_thresh=4, band_pass=[110, 140], plot=True, inspect=True): """ Detect artifacts> modification of FieldTrip's automatic artifact detection procedure (https://www.fieldtriptoolbox.org/tutorial/automatic_artifact_rejection/). Artifacts are detected in three steps: 1. Filtering the data within specified frequency range 2. Z-transforming the filtered data across channels and normalize it over channels 3. Threshold the accumulated z-score Counter to fieldtrip the z_threshold is ajusted based on the noise level within the data Note: all data included for filter padding is now taken into consideration to calculate z values Afer running this function, Epochs contains information about epeochs marked as bad (self.marked_epochs) Arguments: Keyword Arguments: z_thresh {float|int} -- Value that is added to difference between median and min value of accumulated z-score to obtain z-threshold band_pass {list} -- Low and High frequency cutoff for band_pass filter plot {bool} -- If True save detection plots (overview of z scores across epochs, raw signal of channel with highest z score, z distributions, raw signal of all electrodes) inspect {bool} -- If True gives the opportunity to overwrite selected components """ # select data for artifact rejection sfreq = self.info['sfreq'] self_copy = self.copy() self_copy.pick_types(eeg=True, exclude='bads') #filter data and apply Hilbert self_copy.filter(band_pass[0], band_pass[1], fir_design='firwin', pad='reflect_limited') #self_copy.filter(band_pass[0], band_pass[1], method='iir', iir_params=dict(order=6, ftype='butter')) self_copy.apply_hilbert(envelope=True) # get the data and apply box smoothing data = self_copy.get_data() nr_epochs = data.shape[0] for i in range(data.shape[0]): data[i] = self.boxSmoothing(data[i]) # get the data and z_score over electrodes data = data.swapaxes(0,1).reshape(data.shape[1],-1) z_score = zscore(data, axis = 1) # check whether axis is correct!!!!!!!!!!! # z score per electrode and time point (adjust number of electrodes) elecs_z = z_score.reshape(nr_epochs, 64, -1) # normalize z_score z_score = z_score.sum(axis = 0)/sqrt(data.shape[0]) #z_score = filter_data(z_score, self.info['sfreq'], None, 4, pad='reflect_limited') # adjust threshold (data driven) z_thresh += np.median(z_score) + abs(z_score.min() - np.median(z_score)) # transform back into epochs z_score = z_score.reshape(nr_epochs, -1) # control for filter padding if self.flt_pad > 0: idx_ep = self.time_as_index([self.tmin + self.flt_pad, self.tmax - self.flt_pad]) z_score = z_score[:, slice(*idx_ep)] elecs_z # mark bad epochs bad_epochs = [] noise_events = [] cnt = 0 for ep, X in enumerate(z_score): # get start, endpoint and duration in ms per continuous artefact noise_mask = X > z_thresh starts = np.argwhere((~noise_mask[:-1] & noise_mask[1:])) ends = np.argwhere((noise_mask[:-1] & ~noise_mask[1:])) + 1 ep_noise = [(slice(s[0], e[0]), self.times[s][0],self.times[e][0], abs(self.times[e][0] - self.times[s][0])) for s,e in zip(starts, ends)] noise_events.append(ep_noise) noise_smp = np.where(X > z_thresh)[0] if noise_smp.size > 0: bad_epochs.append(ep) if inspect: print('This interactive window selectively shows epochs marked as bad. You can overwrite automatic artifact detection by clicking on selected epochs') bad_eegs = self[bad_epochs] idx_bads = bad_eegs.selection # display bad eegs with 50mV range bad_eegs.plot( n_epochs=5, n_channels=data.shape[1], scalings=dict(eeg = 50)) plt.show() plt.close() missing = np.array([list(idx_bads).index(idx) for idx in idx_bads if idx not in bad_eegs.selection],dtype = int) logging.info('Manually ignored {} epochs out of {} automatically selected({}%)'.format( missing.size, len(bad_epochs),100 * round(missing.size / float(len(bad_epochs)), 2))) bad_epochs = np.delete(bad_epochs, missing) if plot: plt.figure(figsize=(10, 10)) with sns.axes_style('dark'): plt.subplot(111, xlabel='samples', ylabel='z_value', xlim=(0, z_score.size), ylim=(-20, 40)) plt.plot(np.arange(0, z_score.size), z_score.flatten(), color='b') plt.plot(np.arange(0, z_score.size), np.ma.masked_less(z_score.flatten(), z_thresh), color='r') plt.axhline(z_thresh, color='r', ls='--') plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='automatic_artdetect.pdf')) plt.close() # drop bad epochs and save list of dropped epochs self.drop_beh = bad_epochs np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format( self.sj), self.session], filename='noise_epochs.txt'), bad_epochs) print('{} epochs dropped ({}%)'.format(len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))) logging.info('{} epochs dropped ({}%)'.format( len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))) self.drop(np.array(bad_epochs), reason='art detection ecg') logging.info('{} epochs left after artifact detection'.format(len(self))) np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(self.sj), self.session], filename='automatic_artdetect.txt'), ['Artifact detection z threshold set to {}. \n{} epochs dropped ({}%)'. format(round(z_thresh, 1), len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))], fmt='%.100s') return z_thresh if __name__ == '__main__': print('Please run preprocessing via a project script')
16,460
0
538
e5c0d47c76984fe444dc432b4f022b77a68f190d
2,154
py
Python
CondTools/SiStrip/test/SiStripFedCablingBuilder_cfg.py
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
13
2015-11-30T15:49:45.000Z
2022-02-08T16:11:30.000Z
CondTools/SiStrip/test/SiStripFedCablingBuilder_cfg.py
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
640
2015-02-11T18:55:47.000Z
2022-03-31T14:12:23.000Z
CondTools/SiStrip/test/SiStripFedCablingBuilder_cfg.py
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
51
2015-08-11T21:01:40.000Z
2022-03-30T07:31:34.000Z
import FWCore.ParameterSet.Config as cms process = cms.Process("FedCablingBuilder") process.MessageLogger = cms.Service("MessageLogger", debugModules = cms.untracked.vstring(''), cablingBuilder = cms.untracked.PSet( threshold = cms.untracked.string('INFO') ), destinations = cms.untracked.vstring('cablingBuilder.log') ) process.source = cms.Source("EmptySource", numberEventsInRun = cms.untracked.uint32(1), firstRun = cms.untracked.uint32(1) ) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1) ) process.load("CalibTracker.SiStripESProducers.SiStripFedCablingFakeESSource_cfi") process.PoolDBOutputService = cms.Service("PoolDBOutputService", BlobStreamerName = cms.untracked.string('TBufferBlobStreamingService'), DBParameters = cms.PSet( messageLevel = cms.untracked.int32(2), authenticationPath = cms.untracked.string('/afs/cern.ch/cms/DB/conddb') ), timetype = cms.untracked.string('runnumber'), connect = cms.string('sqlite_file:dummy2.db'), toPut = cms.VPSet(cms.PSet( record = cms.string('SiStripFedCablingRcd'), tag = cms.string('SiStripFedCabling_30X') )) ) process.load("Configuration.StandardSequences.Geometry_cff") process.TrackerDigiGeometryESModule.applyAlignment = False process.SiStripConnectivity = cms.ESProducer("SiStripConnectivity") process.SiStripRegionConnectivity = cms.ESProducer("SiStripRegionConnectivity", EtaDivisions = cms.untracked.uint32(20), PhiDivisions = cms.untracked.uint32(20), EtaMax = cms.untracked.double(2.5) ) process.fedcablingbuilder = cms.EDAnalyzer("SiStripFedCablingBuilder", PrintFecCabling = cms.untracked.bool(True), PrintDetCabling = cms.untracked.bool(True), PrintRegionCabling = cms.untracked.bool(True) ) process.p1 = cms.Path(process.fedcablingbuilder)
38.464286
113
0.644847
import FWCore.ParameterSet.Config as cms process = cms.Process("FedCablingBuilder") process.MessageLogger = cms.Service("MessageLogger", debugModules = cms.untracked.vstring(''), cablingBuilder = cms.untracked.PSet( threshold = cms.untracked.string('INFO') ), destinations = cms.untracked.vstring('cablingBuilder.log') ) process.source = cms.Source("EmptySource", numberEventsInRun = cms.untracked.uint32(1), firstRun = cms.untracked.uint32(1) ) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1) ) process.load("CalibTracker.SiStripESProducers.SiStripFedCablingFakeESSource_cfi") process.PoolDBOutputService = cms.Service("PoolDBOutputService", BlobStreamerName = cms.untracked.string('TBufferBlobStreamingService'), DBParameters = cms.PSet( messageLevel = cms.untracked.int32(2), authenticationPath = cms.untracked.string('/afs/cern.ch/cms/DB/conddb') ), timetype = cms.untracked.string('runnumber'), connect = cms.string('sqlite_file:dummy2.db'), toPut = cms.VPSet(cms.PSet( record = cms.string('SiStripFedCablingRcd'), tag = cms.string('SiStripFedCabling_30X') )) ) process.load("Configuration.StandardSequences.Geometry_cff") process.TrackerDigiGeometryESModule.applyAlignment = False process.SiStripConnectivity = cms.ESProducer("SiStripConnectivity") process.SiStripRegionConnectivity = cms.ESProducer("SiStripRegionConnectivity", EtaDivisions = cms.untracked.uint32(20), PhiDivisions = cms.untracked.uint32(20), EtaMax = cms.untracked.double(2.5) ) process.fedcablingbuilder = cms.EDAnalyzer("SiStripFedCablingBuilder", PrintFecCabling = cms.untracked.bool(True), PrintDetCabling = cms.untracked.bool(True), PrintRegionCabling = cms.untracked.bool(True) ) process.p1 = cms.Path(process.fedcablingbuilder)
0
0
0
6755da032d2e91ee6d36df425472a845eeab37be
860
py
Python
games/game_dao.py
ddbb07/modorganizer-basic_games
b7a383200fa4a4cda0d4f6450b47e8b0f376b62d
[ "MIT" ]
22
2020-07-30T12:08:12.000Z
2022-03-12T00:33:34.000Z
games/game_dao.py
ddbb07/modorganizer-basic_games
b7a383200fa4a4cda0d4f6450b47e8b0f376b62d
[ "MIT" ]
32
2020-08-03T22:04:50.000Z
2022-03-31T20:08:26.000Z
games/game_dao.py
ddbb07/modorganizer-basic_games
b7a383200fa4a4cda0d4f6450b47e8b0f376b62d
[ "MIT" ]
32
2020-07-30T18:34:08.000Z
2022-02-25T23:03:06.000Z
import os import mobase from ..basic_features import BasicGameSaveGameInfo from ..basic_game import BasicGame
28.666667
76
0.667442
import os import mobase from ..basic_features import BasicGameSaveGameInfo from ..basic_game import BasicGame class DAOriginsGame(BasicGame): Name = "Dragon Age Origins Support Plugin" Author = "Patchier" Version = "1.1.0" GameName = "Dragon Age: Origins" GameShortName = "dragonage" GameBinary = r"bin_ship\DAOrigins.exe" GameDataPath = r"%DOCUMENTS%\BioWare\Dragon Age\packages\core\override" GameSavesDirectory = r"%DOCUMENTS%\BioWare\Dragon Age\Characters" GameSaveExtension = "das" GameSteamId = [17450, 47810] GameGogId = 1949616134 def init(self, organizer: mobase.IOrganizer): super().init(organizer) self._featureMap[mobase.SaveGameInfo] = BasicGameSaveGameInfo( lambda s: os.path.split(s)[0] + "/screen.dds" ) return True
220
496
24
1d619f4a5a2643cb4104898295632d7a9d2d3fbd
18,299
py
Python
bin/Python27/Lib/site-packages/solid/solidpython.py
lefevre-fraser/openmeta-mms
08f3115e76498df1f8d70641d71f5c52cab4ce5f
[ "MIT" ]
null
null
null
bin/Python27/Lib/site-packages/solid/solidpython.py
lefevre-fraser/openmeta-mms
08f3115e76498df1f8d70641d71f5c52cab4ce5f
[ "MIT" ]
null
null
null
bin/Python27/Lib/site-packages/solid/solidpython.py
lefevre-fraser/openmeta-mms
08f3115e76498df1f8d70641d71f5c52cab4ce5f
[ "MIT" ]
null
null
null
#! /usr/bin/python # -*- coding: utf-8 -*- # Simple Python OpenSCAD Code Generator # Copyright (C) 2009 Philipp Tiefenbacher <wizards23@gmail.com> # Amendments & additions, (C) 2011 Evan Jones <evan_t_jones@mac.com> # # License: LGPL 2.1 or later # import os, sys, re import inspect openscad_builtins = [ # 2D primitives {'name': 'polygon', 'args': ['points', 'paths'], 'kwargs': []} , {'name': 'circle', 'args': [], 'kwargs': ['r', 'segments']} , {'name': 'square', 'args': [], 'kwargs': ['size', 'center']} , # 3D primitives {'name': 'sphere', 'args': [], 'kwargs': ['r', 'segments']} , {'name': 'cube', 'args': [], 'kwargs': ['size', 'center']} , {'name': 'cylinder', 'args': [], 'kwargs': ['r','h','r1', 'r2', 'center', 'segments']} , {'name': 'polyhedron', 'args': ['points', 'triangles' ], 'kwargs': ['convexity']} , # Boolean operations {'name': 'union', 'args': [], 'kwargs': []} , {'name': 'intersection', 'args': [], 'kwargs': []} , {'name': 'difference', 'args': [], 'kwargs': []} , # Transforms {'name': 'translate', 'args': [], 'kwargs': ['v']} , {'name': 'scale', 'args': [], 'kwargs': ['v']} , {'name': 'rotate', 'args': [], 'kwargs': ['a', 'v']} , {'name': 'mirror', 'args': ['v'], 'kwargs': []}, {'name': 'multmatrix', 'args': ['m'], 'kwargs': []}, {'name': 'color', 'args': ['c'], 'kwargs': []}, {'name': 'minkowski', 'args': [], 'kwargs': []}, {'name': 'hull', 'args': [], 'kwargs': []}, {'name': 'render', 'args': [], 'kwargs': ['convexity']}, # 2D to 3D transitions {'name': 'linear_extrude', 'args': [], 'kwargs': ['height', 'center', 'convexity', 'twist','slices']} , {'name': 'rotate_extrude', 'args': [], 'kwargs': ['convexity']} , {'name': 'dxf_linear_extrude', 'args': ['file'], 'kwargs': ['layer', 'height', 'center', 'convexity', 'twist', 'slices']} , {'name': 'projection', 'args': [], 'kwargs': ['cut']} , {'name': 'surface', 'args': ['file'], 'kwargs': ['center','convexity']} , # Import/export {'name': 'import_stl', 'args': ['filename'], 'kwargs': ['convexity']} , # Modifiers; These are implemented by calling e.g. # obj.set_modifier( '*') or # obj.set_modifier('disable') # on an existing object. # {'name': 'background', 'args': [], 'kwargs': []}, # %{} # {'name': 'debug', 'args': [], 'kwargs': []} , # #{} # {'name': 'root', 'args': [], 'kwargs': []} , # !{} # {'name': 'disable', 'args': [], 'kwargs': []} , # *{} {'name': 'intersection_for', 'args': ['n'], 'kwargs': []} , # e.g.: intersection_for( n=[1..6]){} # Unneeded {'name': 'assign', 'args': [], 'kwargs': []} # Not really needed for Python. Also needs a **args argument so it accepts anything ] # Some functions need custom code in them; put that code here builtin_literals = { 'polygon': '''class polygon( openscad_object): def __init__( self, points, paths=None): if not paths: paths = [ range( len( points))] openscad_object.__init__( self, 'polygon', {'points':points, 'paths': paths}) ''' } # =============== # = Including OpenSCAD code = # =============== # use() & include() mimic OpenSCAD's use/include mechanics. # -- use() makes methods in scad_file_path.scad available to # be called. # --include() makes those methods available AND executes all code in # scad_file_path.scad, which may have side effects. # Unless you have a specific need, call use(). def use( scad_file_path, use_not_include=True): ''' TODO: doctest needed ''' # Opens scad_file_path, parses it for all usable calls, # and adds them to caller's namespace try: module = open( scad_file_path) contents = module.read() module.close() except Exception, e: raise Exception( "Failed to import SCAD module '%(scad_file_path)s' with error: %(e)s "%vars()) # Once we have a list of all callables and arguments, dynamically # add openscad_object subclasses for all callables to the calling module's # namespace. symbols_dicts = extract_callable_signatures( scad_file_path) for sd in symbols_dicts: class_str = new_openscad_class_str( sd['name'], sd['args'], sd['kwargs'], scad_file_path, use_not_include) exec class_str in calling_module().__dict__ return True # ========================================= # = Rendering Python code to OpenSCAD code= # ========================================= # ========================= # = Internal Utilities = # ========================= class included_openscad_object( openscad_object): ''' Identical to openscad_object, but each subclass of included_openscad_object represents imported scad code, so each instance needs to store the path to the scad file it's included from. ''' def calling_module(): ''' Returns the module *2* back in the frame stack. That means: code in module A calls code in module B, which asks calling_module() for module A. Got that? ''' frm = inspect.stack()[2] calling_mod = inspect.getmodule( frm[0]) return calling_mod # =========== # = Parsing = # =========== def parse_scad_callables( scad_code_str): """>>> test_str = '''module hex (width=10, height=10, ... flats= true, center=false){} ... function righty (angle=90) = 1; ... function lefty( avar) = 2; ... module more( a=[something, other]) {} ... module pyramid(side=10, height=-1, square=false, centerHorizontal=true, centerVertical=false){} ... module no_comments( arg=10, //test comment ... other_arg=2, /* some extra comments ... on empty lines */ ... last_arg=4){} ... module float_arg( arg=1.0){} ... ''' >>> parse_scad_callables( test_str) [{'args': [], 'name': 'hex', 'kwargs': ['width', 'height', 'flats', 'center']}, {'args': [], 'name': 'righty', 'kwargs': ['angle']}, {'args': ['avar'], 'name': 'lefty', 'kwargs': []}, {'args': [], 'name': 'more', 'kwargs': ['a']}, {'args': [], 'name': 'pyramid', 'kwargs': ['side', 'height', 'square', 'centerHorizontal', 'centerVertical']}, {'args': [], 'name': 'no_comments', 'kwargs': ['arg', 'other_arg', 'last_arg']}, {'args': [], 'name': 'float_arg', 'kwargs': ['arg']}] >>> """ callables = [] # Note that this isn't comprehensive; tuples or nested data structures in # a module definition will defeat it. # Current implementation would throw an error if you tried to call a(x, y) # since Python would expect a( x); OpenSCAD itself ignores extra arguments, # but that's not really preferable behavior # TODO: write a pyparsing grammar for OpenSCAD, or, even better, use the yacc parse grammar # used by the language itself. -ETJ 06 Feb 2011 no_comments_re = r'(?mxs)(//.*?\n|/\*.*?\*/)' # Also note: this accepts: 'module x(arg) =' and 'function y(arg) {', both of which are incorrect syntax mod_re = r'(?mxs)^\s*(?:module|function)\s+(?P<callable_name>\w+)\s*\((?P<all_args>.*?)\)\s*(?:{|=)' # This is brittle. To get a generally applicable expression for all arguments, # we'd need a real parser to handle nested-list default args or parenthesized statements. # For the moment, assume a maximum of one square-bracket-delimited list args_re = r'(?mxs)(?P<arg_name>\w+)(?:\s*=\s*(?P<default_val>[\w.-]+|\[.*\]))?(?:,|$)' # remove all comments from SCAD code scad_code_str = re.sub(no_comments_re,'', scad_code_str) # get all SCAD callables mod_matches = re.finditer( mod_re, scad_code_str) for m in mod_matches: callable_name = m.group('callable_name') args = [] kwargs = [] all_args = m.group('all_args') if all_args: arg_matches = re.finditer( args_re, all_args) for am in arg_matches: arg_name = am.group('arg_name') if am.group('default_val'): kwargs.append( arg_name) else: args.append( arg_name) callables.append( { 'name':callable_name, 'args': args, 'kwargs':kwargs}) return callables # Dynamically add all builtins to this namespace on import for sym_dict in openscad_builtins: # entries in 'builtin_literals' override the entries in 'openscad_builtins' if sym_dict['name'] in builtin_literals: class_str = builtin_literals[ sym_dict['name']] else: class_str = new_openscad_class_str( sym_dict['name'], sym_dict['args'], sym_dict['kwargs']) exec class_str
37.421268
476
0.53451
#! /usr/bin/python # -*- coding: utf-8 -*- # Simple Python OpenSCAD Code Generator # Copyright (C) 2009 Philipp Tiefenbacher <wizards23@gmail.com> # Amendments & additions, (C) 2011 Evan Jones <evan_t_jones@mac.com> # # License: LGPL 2.1 or later # import os, sys, re import inspect openscad_builtins = [ # 2D primitives {'name': 'polygon', 'args': ['points', 'paths'], 'kwargs': []} , {'name': 'circle', 'args': [], 'kwargs': ['r', 'segments']} , {'name': 'square', 'args': [], 'kwargs': ['size', 'center']} , # 3D primitives {'name': 'sphere', 'args': [], 'kwargs': ['r', 'segments']} , {'name': 'cube', 'args': [], 'kwargs': ['size', 'center']} , {'name': 'cylinder', 'args': [], 'kwargs': ['r','h','r1', 'r2', 'center', 'segments']} , {'name': 'polyhedron', 'args': ['points', 'triangles' ], 'kwargs': ['convexity']} , # Boolean operations {'name': 'union', 'args': [], 'kwargs': []} , {'name': 'intersection', 'args': [], 'kwargs': []} , {'name': 'difference', 'args': [], 'kwargs': []} , # Transforms {'name': 'translate', 'args': [], 'kwargs': ['v']} , {'name': 'scale', 'args': [], 'kwargs': ['v']} , {'name': 'rotate', 'args': [], 'kwargs': ['a', 'v']} , {'name': 'mirror', 'args': ['v'], 'kwargs': []}, {'name': 'multmatrix', 'args': ['m'], 'kwargs': []}, {'name': 'color', 'args': ['c'], 'kwargs': []}, {'name': 'minkowski', 'args': [], 'kwargs': []}, {'name': 'hull', 'args': [], 'kwargs': []}, {'name': 'render', 'args': [], 'kwargs': ['convexity']}, # 2D to 3D transitions {'name': 'linear_extrude', 'args': [], 'kwargs': ['height', 'center', 'convexity', 'twist','slices']} , {'name': 'rotate_extrude', 'args': [], 'kwargs': ['convexity']} , {'name': 'dxf_linear_extrude', 'args': ['file'], 'kwargs': ['layer', 'height', 'center', 'convexity', 'twist', 'slices']} , {'name': 'projection', 'args': [], 'kwargs': ['cut']} , {'name': 'surface', 'args': ['file'], 'kwargs': ['center','convexity']} , # Import/export {'name': 'import_stl', 'args': ['filename'], 'kwargs': ['convexity']} , # Modifiers; These are implemented by calling e.g. # obj.set_modifier( '*') or # obj.set_modifier('disable') # on an existing object. # {'name': 'background', 'args': [], 'kwargs': []}, # %{} # {'name': 'debug', 'args': [], 'kwargs': []} , # #{} # {'name': 'root', 'args': [], 'kwargs': []} , # !{} # {'name': 'disable', 'args': [], 'kwargs': []} , # *{} {'name': 'intersection_for', 'args': ['n'], 'kwargs': []} , # e.g.: intersection_for( n=[1..6]){} # Unneeded {'name': 'assign', 'args': [], 'kwargs': []} # Not really needed for Python. Also needs a **args argument so it accepts anything ] # Some functions need custom code in them; put that code here builtin_literals = { 'polygon': '''class polygon( openscad_object): def __init__( self, points, paths=None): if not paths: paths = [ range( len( points))] openscad_object.__init__( self, 'polygon', {'points':points, 'paths': paths}) ''' } # =============== # = Including OpenSCAD code = # =============== # use() & include() mimic OpenSCAD's use/include mechanics. # -- use() makes methods in scad_file_path.scad available to # be called. # --include() makes those methods available AND executes all code in # scad_file_path.scad, which may have side effects. # Unless you have a specific need, call use(). def use( scad_file_path, use_not_include=True): ''' TODO: doctest needed ''' # Opens scad_file_path, parses it for all usable calls, # and adds them to caller's namespace try: module = open( scad_file_path) contents = module.read() module.close() except Exception, e: raise Exception( "Failed to import SCAD module '%(scad_file_path)s' with error: %(e)s "%vars()) # Once we have a list of all callables and arguments, dynamically # add openscad_object subclasses for all callables to the calling module's # namespace. symbols_dicts = extract_callable_signatures( scad_file_path) for sd in symbols_dicts: class_str = new_openscad_class_str( sd['name'], sd['args'], sd['kwargs'], scad_file_path, use_not_include) exec class_str in calling_module().__dict__ return True def include( scad_file_path): return use( scad_file_path, use_not_include=False) # ========================================= # = Rendering Python code to OpenSCAD code= # ========================================= def scad_render( scad_object, file_header=''): # Find the root of the tree, calling x.parent until there is none root = scad_object # Scan the tree for all instances of # included_openscad_object, storing their strings def find_include_strings( obj): include_strings = set() if isinstance( obj, included_openscad_object): include_strings.add( obj.include_string ) for child in obj.children: include_strings.update( find_include_strings( child)) return include_strings include_strings = find_include_strings( root) # and render the string includes = ''.join(include_strings) + "\n" scad_body = root._render() return file_header + includes + scad_body def scad_render_to_file( scad_object, filepath=None, file_header='', include_orig_code=True): rendered_string = scad_render( scad_object, file_header) calling_file = os.path.abspath( calling_module().__file__) if include_orig_code: # Once a SCAD file has been created, it's difficult to reconstruct # how it got there, since it has no variables, modules, etc. So, include # the Python code that generated the scad code as comments at the end of # the SCAD code pyopenscad_str = open(calling_file, 'r').read() pyopenscad_str = ''' /*********************************************** ****** SolidPython code: ************* ************************************************ %(pyopenscad_str)s ***********************************************/ '''%vars() rendered_string += pyopenscad_str # This write is destructive, and ought to do some checks that the write # was successful. # If filepath isn't supplied, place a .scad file with the same name # as the calling module next to it if not filepath: filepath = os.path.splitext( calling_file)[0] + '.scad' f = open( filepath,"w") f.write( rendered_string) f.close # ========================= # = Internal Utilities = # ========================= class openscad_object( object): def __init__(self, name, params): self.name = name self.params = params self.children = [] self.modifier = "" self.parent= None def set_modifier(self, m): # Used to add one of the 4 single-character modifiers: #(debug) !(root) %(background) or *(disable) string_vals = { 'disable': '*', 'debug': '#', 'background': '%', 'root': '!', '*':'*', '#':'#', '%':'%', '!':'!'} self.modifier = string_vals.get(m.lower(), '') return self def _render(self): ''' NOTE: In general, you won't want to call this method. For most purposes, you really want scad_render(), Calling obj._render won't include necessary 'use' or 'include' statements ''' s = "\n" + self.modifier + self.name + "(" first = True # OpenSCAD doesn't have a 'segments' argument, but it does # have '$fn'. Swap one for the other if 'segments' in self.params: self.params['$fn'] = self.params.pop('segments') valid_keys = self.params.keys() # intkeys are the positional parameters intkeys = filter(lambda x: type(x)==int, valid_keys) intkeys.sort() # named parameters nonintkeys = filter(lambda x: not type(x)==int, valid_keys) for k in intkeys+nonintkeys: v = self.params[k] if v == None: continue if not first: s += ", " first = False if type(k)==int: s += py2openscad(v) else: s += k + " = " + py2openscad(v) s += ")" if self.children != None and len(self.children) > 0: s += " {" for child in self.children: s += indent(child._render()) s += "\n}" else: s += ";" return s def add(self, child): ''' if child is a single object, assume it's an openscad_object and add it to self.children if child is a list, assume its members are all openscad_objects and add them all to self.children ''' if isinstance( child, list) or isinstance( child, tuple): [self.add( c) for c in child] else: self.children.append(child) child.set_parent( self) return self def set_parent( self, parent): self.parent = parent def add_param(self, k, v): self.params[k] = v return self def copy( self): # Provides a copy of this object and all children, # but doesn't copy self.parent, meaning the new object belongs # to a different tree other = openscad_object( self.name, self.params) for c in self.children: other.add( c.copy()) return other def __call__( self, *args): ''' Adds all objects in args to self. This enables OpenSCAD-like syntax, e.g.: union()( cube(), sphere() ) ''' return self.add(args) def __add__(self, x): ''' This makes u = a+b identical to: u = union()( a, b ) ''' return union()(self, x) def __sub__(self, x): ''' This makes u = a - b identical to: u = difference()( a, b ) ''' return difference()(self, x) def __mul__(self, x): ''' This makes u = a * b identical to: u = intersection()( a, b ) ''' return intersection()(self, x) class included_openscad_object( openscad_object): ''' Identical to openscad_object, but each subclass of included_openscad_object represents imported scad code, so each instance needs to store the path to the scad file it's included from. ''' def __init__( self, name, params, include_file_path, use_not_include=False): self.include_file_path = self._get_include_path( include_file_path) if use_not_include: self.include_string = 'use <%s>\n'%self.include_file_path else: self.include_string = 'include <%s>\n'%self.include_file_path openscad_object.__init__( self, name, params) def _get_include_path( self, include_file_path): # Look through sys.path for anyplace we can find a valid file ending # in include_file_path. Return that absolute path if os.path.isabs( include_file_path): return include_file_path else: for p in sys.path: whole_path = os.path.join( p, include_file_path) if os.path.isfile( whole_path): return os.path.abspath(whole_path) # No loadable SCAD file was found in sys.path. Raise an error raise( ValueError, "Unable to find included SCAD file: " "%(include_file_path)s in sys.path"%vars()) def calling_module(): ''' Returns the module *2* back in the frame stack. That means: code in module A calls code in module B, which asks calling_module() for module A. Got that? ''' frm = inspect.stack()[2] calling_mod = inspect.getmodule( frm[0]) return calling_mod def new_openscad_class_str( class_name, args=[], kwargs=[], include_file_path=None, use_not_include=True): args_str = '' args_pairs = '' for arg in args: args_str += ', '+arg args_pairs += "'%(arg)s':%(arg)s, "%vars() # kwargs have a default value defined in their SCAD versions. We don't # care what that default value will be (SCAD will take care of that), just # that one is defined. for kwarg in kwargs: args_str += ', %(kwarg)s=None'%vars() args_pairs += "'%(kwarg)s':%(kwarg)s, "%vars() if include_file_path: result = '''class %(class_name)s( included_openscad_object): def __init__(self%(args_str)s): included_openscad_object.__init__(self, '%(class_name)s', {%(args_pairs)s }, include_file_path='%(include_file_path)s', use_not_include=%(use_not_include)s ) '''%vars() else: result = '''class %(class_name)s( openscad_object): def __init__(self%(args_str)s): openscad_object.__init__(self, '%(class_name)s', {%(args_pairs)s }) '''%vars() return result def py2openscad(o): if type(o) == bool: return str(o).lower() if type(o) == float: return "%.10f" % o if type(o) == list: s = "[" first = True for i in o: if not first: s += ", " first = False s += py2openscad(i) s += "]" return s if type(o) == str: return '"' + o + '"' return str(o) def indent(s): return s.replace("\n", "\n\t") # =========== # = Parsing = # =========== def extract_callable_signatures( scad_file_path): scad_code_str = open(scad_file_path).read() return parse_scad_callables( scad_code_str) def parse_scad_callables( scad_code_str): """>>> test_str = '''module hex (width=10, height=10, ... flats= true, center=false){} ... function righty (angle=90) = 1; ... function lefty( avar) = 2; ... module more( a=[something, other]) {} ... module pyramid(side=10, height=-1, square=false, centerHorizontal=true, centerVertical=false){} ... module no_comments( arg=10, //test comment ... other_arg=2, /* some extra comments ... on empty lines */ ... last_arg=4){} ... module float_arg( arg=1.0){} ... ''' >>> parse_scad_callables( test_str) [{'args': [], 'name': 'hex', 'kwargs': ['width', 'height', 'flats', 'center']}, {'args': [], 'name': 'righty', 'kwargs': ['angle']}, {'args': ['avar'], 'name': 'lefty', 'kwargs': []}, {'args': [], 'name': 'more', 'kwargs': ['a']}, {'args': [], 'name': 'pyramid', 'kwargs': ['side', 'height', 'square', 'centerHorizontal', 'centerVertical']}, {'args': [], 'name': 'no_comments', 'kwargs': ['arg', 'other_arg', 'last_arg']}, {'args': [], 'name': 'float_arg', 'kwargs': ['arg']}] >>> """ callables = [] # Note that this isn't comprehensive; tuples or nested data structures in # a module definition will defeat it. # Current implementation would throw an error if you tried to call a(x, y) # since Python would expect a( x); OpenSCAD itself ignores extra arguments, # but that's not really preferable behavior # TODO: write a pyparsing grammar for OpenSCAD, or, even better, use the yacc parse grammar # used by the language itself. -ETJ 06 Feb 2011 no_comments_re = r'(?mxs)(//.*?\n|/\*.*?\*/)' # Also note: this accepts: 'module x(arg) =' and 'function y(arg) {', both of which are incorrect syntax mod_re = r'(?mxs)^\s*(?:module|function)\s+(?P<callable_name>\w+)\s*\((?P<all_args>.*?)\)\s*(?:{|=)' # This is brittle. To get a generally applicable expression for all arguments, # we'd need a real parser to handle nested-list default args or parenthesized statements. # For the moment, assume a maximum of one square-bracket-delimited list args_re = r'(?mxs)(?P<arg_name>\w+)(?:\s*=\s*(?P<default_val>[\w.-]+|\[.*\]))?(?:,|$)' # remove all comments from SCAD code scad_code_str = re.sub(no_comments_re,'', scad_code_str) # get all SCAD callables mod_matches = re.finditer( mod_re, scad_code_str) for m in mod_matches: callable_name = m.group('callable_name') args = [] kwargs = [] all_args = m.group('all_args') if all_args: arg_matches = re.finditer( args_re, all_args) for am in arg_matches: arg_name = am.group('arg_name') if am.group('default_val'): kwargs.append( arg_name) else: args.append( arg_name) callables.append( { 'name':callable_name, 'args': args, 'kwargs':kwargs}) return callables # Dynamically add all builtins to this namespace on import for sym_dict in openscad_builtins: # entries in 'builtin_literals' override the entries in 'openscad_builtins' if sym_dict['name'] in builtin_literals: class_str = builtin_literals[ sym_dict['name']] else: class_str = new_openscad_class_str( sym_dict['name'], sym_dict['args'], sym_dict['kwargs']) exec class_str
5,859
2,927
238
6137276e96e751acdcfec42711c4938cc9f70eca
1,151
py
Python
tests/__init__.py
Crunch-io/probes
cf85e047cdb30a1a20ed583d8f9a122c16ef9d06
[ "MIT" ]
19
2019-07-06T21:40:26.000Z
2022-01-01T22:48:08.000Z
tests/__init__.py
Crunch-io/probes
cf85e047cdb30a1a20ed583d8f9a122c16ef9d06
[ "MIT" ]
null
null
null
tests/__init__.py
Crunch-io/probes
cf85e047cdb30a1a20ed583d8f9a122c16ef9d06
[ "MIT" ]
2
2020-09-15T14:52:40.000Z
2021-01-06T13:28:16.000Z
from contextlib import contextmanager import datetime import unittest import diagnose from diagnose import probes diagnose.manager.instrument_classes.setdefault( "test", diagnose.instruments.ProbeTestInstrument )
29.512821
88
0.529974
from contextlib import contextmanager import datetime import unittest import diagnose from diagnose import probes diagnose.manager.instrument_classes.setdefault( "test", diagnose.instruments.ProbeTestInstrument ) class ProbeTestCase(unittest.TestCase): @contextmanager def probe(self, type, name, target, value, lifespan=1, custom=None, event="return"): mgr = diagnose.manager instrument_id = None try: instrument_id = "probe-%s" % name mgr.specs[instrument_id] = { "target": target, "instrument": { "type": type, "name": name, "value": value, "event": event, "custom": custom or {}, }, "lifespan": lifespan, "lastmodified": datetime.datetime.utcnow(), "applied": {}, } mgr.apply() yield probes.active_probes[target] finally: if instrument_id is not None: mgr.specs.pop(instrument_id, None) mgr.apply()
844
64
23
a1aeaa851ba3167686d3755a3a79b49475ddbf5f
237
py
Python
blogtools/tests/urls.py
ixc/glamkit-blogtools
a3024d983eabafeba5df789eacbcc389e4181866
[ "BSD-3-Clause" ]
null
null
null
blogtools/tests/urls.py
ixc/glamkit-blogtools
a3024d983eabafeba5df789eacbcc389e4181866
[ "BSD-3-Clause" ]
null
null
null
blogtools/tests/urls.py
ixc/glamkit-blogtools
a3024d983eabafeba5df789eacbcc389e4181866
[ "BSD-3-Clause" ]
null
null
null
from django.conf.urls import url, include from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^blog/', include('blogtools.tests.test_blog.urls', app_name='blogtools', namespace='test_blog')), ]
33.857143
107
0.772152
from django.conf.urls import url, include from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^blog/', include('blogtools.tests.test_blog.urls', app_name='blogtools', namespace='test_blog')), ]
0
0
0
d28ba2716cff55579e19597fce16db0ff4f34413
336
py
Python
questions/migrations/0002_auto_20191209_0854.py
Jay-68/moringa_flow
9cf72e8279a4b5397be8b1b2c57d7b5ff629b23b
[ "MIT" ]
null
null
null
questions/migrations/0002_auto_20191209_0854.py
Jay-68/moringa_flow
9cf72e8279a4b5397be8b1b2c57d7b5ff629b23b
[ "MIT" ]
6
2019-12-11T08:54:34.000Z
2021-09-08T01:29:12.000Z
questions/migrations/0002_auto_20191209_0854.py
Jay-68/moringa_flow
9cf72e8279a4b5397be8b1b2c57d7b5ff629b23b
[ "MIT" ]
1
2019-12-13T11:24:50.000Z
2019-12-13T11:24:50.000Z
# Generated by Django 2.0 on 2019-12-09 08:54 from django.db import migrations
18.666667
45
0.577381
# Generated by Django 2.0 on 2019-12-09 08:54 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('questions', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='answer', options={'ordering': ['-likes']}, ), ]
0
232
23
35908d199e7e63d6541937f7efe3e6726631a197
549
py
Python
custom_metric.py
stoplime/kaggle
108639dea1ed16f24748f0f83a4c01ee5930d4f6
[ "MIT" ]
null
null
null
custom_metric.py
stoplime/kaggle
108639dea1ed16f24748f0f83a4c01ee5930d4f6
[ "MIT" ]
null
null
null
custom_metric.py
stoplime/kaggle
108639dea1ed16f24748f0f83a4c01ee5930d4f6
[ "MIT" ]
null
null
null
import numpy as np from sklearn.metrics import fbeta_score from keras import backend as K def FScore2(y_true, y_pred): ''' The F score, beta=2 ''' B2 = K.variable(4) OnePlusB2 = K.variable(5) pred = K.round(y_pred) tp = K.sum(K.cast(K.less(K.abs(pred - K.clip(y_true, .5, 1.)), 0.01), 'float32'), -1) fp = K.sum(K.cast(K.greater(pred - y_true, 0.1), 'float32'), -1) fn = K.sum(K.cast(K.less(pred - y_true, -0.1), 'float32'), -1) f2 = OnePlusB2 * tp / (OnePlusB2 * tp + B2 * fn + fp) return K.mean(f2)
27.45
89
0.590164
import numpy as np from sklearn.metrics import fbeta_score from keras import backend as K def FScore2(y_true, y_pred): ''' The F score, beta=2 ''' B2 = K.variable(4) OnePlusB2 = K.variable(5) pred = K.round(y_pred) tp = K.sum(K.cast(K.less(K.abs(pred - K.clip(y_true, .5, 1.)), 0.01), 'float32'), -1) fp = K.sum(K.cast(K.greater(pred - y_true, 0.1), 'float32'), -1) fn = K.sum(K.cast(K.less(pred - y_true, -0.1), 'float32'), -1) f2 = OnePlusB2 * tp / (OnePlusB2 * tp + B2 * fn + fp) return K.mean(f2)
0
0
0
cd3d4b839da134541c1bd60d41d9822810206145
4,071
py
Python
iiif_api_services/helpers/PreProcessRequest.py
utlib/utl_iiif_api
e2d77ad5a677487e205b840cc800af46b4697eab
[ "Apache-2.0" ]
4
2019-12-08T18:39:37.000Z
2021-11-09T19:35:44.000Z
iiif_api_services/helpers/PreProcessRequest.py
utlib/utl_iiif_api
e2d77ad5a677487e205b840cc800af46b4697eab
[ "Apache-2.0" ]
2
2020-06-05T16:45:31.000Z
2021-06-10T17:30:00.000Z
iiif_api_services/helpers/PreProcessRequest.py
utlib/utl_iiif_api
e2d77ad5a677487e205b840cc800af46b4697eab
[ "Apache-2.0" ]
1
2019-12-08T18:45:52.000Z
2019-12-08T18:45:52.000Z
import json from django.conf import settings from rest_framework import status from rest_framework.response import Response from iiif_api_services.models.QueueModel import Queue from iiif_api_services.models.ActivityModel import Activity if settings.QUEUE_RUNNER=="THREAD": from threading import Thread as Runner else: from multiprocessing import Process as Runner
69
223
0.70818
import json from django.conf import settings from rest_framework import status from rest_framework.response import Response from iiif_api_services.models.QueueModel import Queue from iiif_api_services.models.ActivityModel import Activity if settings.QUEUE_RUNNER=="THREAD": from threading import Thread as Runner else: from multiprocessing import Process as Runner def initialize_new_bulk_actions(): return {"Collection": [], "Manifest": [], "Sequence": [], "Range": [], "Canvas": [], "Annotation": [], "AnnotationList": [], "Layer": []} def process_create_or_update_request(request, create_or_update_function, request_top_level_key, identifier=None, name=None): try: request_body = json.loads(request.body)[request_top_level_key] # Create the Activity object activity = Activity(username=request.user.username, requestPath=settings.IIIF_BASE_URL+request.get_full_path(), requestBody=request_body, requestMethod=request.method, remoteAddress=request.META['REMOTE_ADDR']).save() user = request.user.to_mongo() del user["_id"] # Mongo ObjectID is not serializable request_body["identifier"], request_body["name"] = identifier, name # Include these url fields with the requestBody if (request.method == "POST" and settings.QUEUE_POST_ENABLED) or (request.method == "PUT" and settings.QUEUE_PUT_ENABLED): queue = Queue(status="Pending", activity=activity.to_mongo()).save() # Create the Queue object queue_activity = "{0}_{1}".format(queue.id, activity.id) # link the Queue and Activity object queue_status_url = "{0}/queue/{1}".format(settings.IIIF_BASE_URL, queue.id) # Get the Queue status url if settings.QUEUE_RUNNER != "CELERY": # Either 'PROCESS' or 'THREAD' imported as 'Runner' Runner(target=create_or_update_function, args=(user, request_body, False, queue_activity, initialize_new_bulk_actions())).start() else: create_or_update_function.delay(user, request_body, False, queue_activity, initialize_new_bulk_actions()) return Response(status=status.HTTP_202_ACCEPTED, data={'message': "Request Accepted", "status": queue_status_url}) else: result = create_or_update_function(user, request_body, False, "_"+str(activity.id), initialize_new_bulk_actions()) return Response(status=result["status"], data={"responseBody": result["data"], "responseCode": result["status"]}) except Exception as e: # pragma: no cover return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': e.message}) def process_delete_request(request, delete_function, identifier="", name=""): try: activity = Activity(username=request.user.username, requestPath=settings.IIIF_BASE_URL+request.get_full_path(), requestMethod=request.method, remoteAddress=request.META['REMOTE_ADDR']).save() user = request.user.to_mongo() del user["_id"] # Mongo ObjectID is not serializable if settings.QUEUE_DELETE_ENABLED: queue = Queue(status="Pending", activity=activity.to_mongo()).save() # Create the Queue object queue_activity = "{0}_{1}".format(queue.id, activity.id) # link the Queue and Activity object if settings.QUEUE_RUNNER != "CELERY": # Either 'PROCESS' or 'THREAD' imported as 'Runner' Runner(target=delete_function, args=(user, identifier+"__"+name, queue_activity)).start() else: delete_function.delay(user, identifier+"__"+name, queue_activity) return Response(status=status.HTTP_202_ACCEPTED, data={'message': "Request Accepted", "status": settings.IIIF_BASE_URL + '/queue/' + str(queue.id)}) else: result = delete_function(user, identifier+"__"+name, "_"+str(activity.id)) return Response(status=result["status"], data={"responseBody": result["data"], "responseCode": result["status"]}) except Exception as e: # pragma: no cover return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': e.message})
3,612
0
71
fdef7cb22602ce528c8233594d1d153bab4403a5
8,930
py
Python
tests/unit/test_helpers.py
peopledoc/ml-versioning-tools
2a797303b2b0e988f8063fc1d418f65c821efa97
[ "BSD-3-Clause" ]
36
2018-09-19T09:50:05.000Z
2020-03-14T22:15:15.000Z
tests/unit/test_helpers.py
peopledoc/ml-versioning-tools
2a797303b2b0e988f8063fc1d418f65c821efa97
[ "BSD-3-Clause" ]
29
2018-10-12T16:09:51.000Z
2020-03-13T14:12:02.000Z
tests/unit/test_helpers.py
peopledoc/mlvtools
f04f69b34291b85bd7a5fc2baf19fccb1535a983
[ "BSD-3-Clause" ]
8
2019-04-06T11:08:37.000Z
2020-02-06T17:02:15.000Z
import stat from os import stat as os_stat from os.path import join, exists from tempfile import TemporaryDirectory import pytest from jinja2 import UndefinedError, TemplateSyntaxError from mlvtools.exception import MlVToolException from mlvtools.helper import extract_type, to_dvc_meta_filename, to_instructions_list, \ write_python_script, write_template, to_sanitized_path from mlvtools.helper import to_cmd_param, to_method_name, to_bash_variable, to_script_name, to_dvc_cmd_name def test_should_convert_to_command_param(): """ Test convert to command parameter """ assert to_cmd_param('my_param_One') == 'my-param-One' def test_should_convert_to_bash_variable(): """ Test convert to bash variable """ assert to_bash_variable('my-param-one') == 'MY_PARAM_ONE' def test_should_convert_to_method_name(): """ Test convert file name without extension to a python method name """ assert to_method_name('01my-Meth$odk++ Name.truc') == 'mlvtools_01my_meth_odk_name_truc' def test_should_convert_to_script_name(): """ Test convert file name to script name """ assert to_script_name('My notebook.ipynb') == 'mlvtools_my_notebook.py' def test_should_convert_to_dvc_meta_filename(): """ Test convert notebook path to dvc meta filename """ assert to_dvc_meta_filename('./toto/truc/My notebook.ipynb') == 'my_notebook.dvc' def test_should_convert_to_instructions_list(): """ Test convert a string of several instructions into a list of instructions """ assert to_instructions_list('\nimport os\na = 45\n') == ['import os', 'a = 45'] def test_should_extract_python_str_and_int(): """ Test extract python str and int types """ type_info = extract_type('str ') assert type_info.type_name == 'str' assert not type_info.is_list type_info = extract_type(' int') assert type_info.type_name == 'int' assert not type_info.is_list def test_should_return_none_if_extract_python_of_no_type(): """ Test extract python return None if empty type """ type_info = extract_type('') assert not type_info.type_name assert not type_info.is_list type_info = extract_type(None) assert not type_info.type_name assert not type_info.is_list def test_should_extract_python_list_type(): """ Test extract python list type """ type_info = extract_type('list') assert type_info.type_name == 'str' assert type_info.is_list type_info = extract_type('List') assert type_info.type_name == 'str' assert type_info.is_list type_info = extract_type('list[str]') assert type_info.type_name == 'str' assert type_info.is_list type_info = extract_type('List[int]') assert type_info.type_name == 'int' assert type_info.is_list def test_should_convert_to_dvc_cmd_name(): """ Test convert script name to dvc command name """ assert to_dvc_cmd_name('my_notebook.py') == 'my_notebook_dvc' def test_should_sanitize_path(): """ Test should add ./ to path if does not start wiht / or ./ """ assert to_sanitized_path('toto.py') == './toto.py' def test_sanitize_should_not_change_absolute_path(): """ Test sanitize should not change absolute path """ absolute_path = '/absolut/path/toto.py' assert to_sanitized_path(absolute_path) == absolute_path def test_sanitize_should_not_change_path_starting_with_dot_slash(): """ Test sanitize should not change path starting with dot slash """ path = './toto.py' assert to_sanitized_path(path) == path @pytest.fixture def test_should_write_template(work_dir, valid_template_path): """ Test write an executable file from a given template and data """ output_path = join(work_dir, 'my_exe.sh') write_template(output_path, valid_template_path, given_data='test') assert exists(output_path) assert stat.S_IMODE(os_stat(output_path).st_mode) == 0o755 with open(output_path, 'r') as fd: assert fd.read() == 'a_value=test' def test_should_create_directory_to_write_template(work_dir, valid_template_path): """ Test create directory and write template """ output_path = join(work_dir, 'a_dir', 'my_exe.sh') write_template(output_path, valid_template_path, given_data='test') assert exists(join(work_dir, 'a_dir')) assert exists(output_path) def test_write_template_should_raise_if_template_does_not_exist(work_dir): """ Test write_template raise an MlVToolException if the template file does not exist """ template_path = join(work_dir, 'not_existing_template.tpl') check_write_template_error_case(template_path, data={}, exp_error=IOError) def test_write_template_should_raise_if_template_format_error(work_dir): """ Test write_template raise an MlVToolException if the template is wrongly formatted """ template_data = 'a_value={{ t_data' template_path = join(work_dir, 'template_wrong_format.tpl') with open(template_path, 'w') as fd: fd.write(template_data) check_write_template_error_case(template_path, data={'t_data': 'test'}, exp_error=TemplateSyntaxError) @pytest.mark.parametrize('missing_pattern', (('{{ printed_var }}', '{% for val in iterated_var %}{% endfor %}', '{{ accessed.var }}'))) def test_write_template_should_raise_if_missing_template_data(work_dir, missing_pattern): """ Test write_template raise an MlVToolException if there is an undefined template variable Case of : - print - iteration - other access """ template_data = f'a_value={missing_pattern}' template_path = join(work_dir, 'template.tpl') with open(template_path, 'w') as fd: fd.write(template_data) check_write_template_error_case(template_path, data={}, exp_error=UndefinedError) def test_write_template_should_raise_if_can_not_write_executable_output(work_dir, mocker, valid_template_path): """ Test write_template raise an MlVToolException if the executable output cannot be written """ output_path = join(work_dir, 'output.sh') mocker.patch('builtins.open', side_effect=IOError) with pytest.raises(MlVToolException) as e: write_template(output_path, valid_template_path, given_data='test') assert isinstance(e.value.__cause__, IOError) def test_should_write_formatted_python_script(work_dir): """ Test write formatted and executable python script """ script_content = 'my_var=4\nmy_list=[1,2,3]' script_path = join(work_dir, 'test.py') write_python_script(script_content, script_path) assert exists(script_path) assert stat.S_IMODE(os_stat(script_path).st_mode) == 0o755 with open(script_path, 'r') as fd: assert fd.read() == 'my_var = 4\nmy_list = [1, 2, 3]\n' def test_should_create_directory_to_write_formatted_python_script(work_dir): """ Test create directory and write formatted and executable python script """ script_content = 'my_var=4' script_path = join(work_dir, 'a_dir', 'test.py') write_python_script(script_content, script_path) assert exists(join(work_dir, 'a_dir')) assert exists(script_path) def test_write_python_script_should_raise_if_cannot_write_executable_script(work_dir, mocker): """ Test write_python_script raise an MlVToolException if can not write executable output """ script_content = 'my_var=4\nmy_list=[1,2,3]' script_path = join(work_dir, 'test.py') mocker.patch('builtins.open', side_effect=IOError) with pytest.raises(MlVToolException) as e: write_python_script(script_content, script_path) assert isinstance(e.value.__cause__, IOError) def test_write_python_script_should_raise_if_python_syntax_error(work_dir): """ Test write_python_script raise an MlVToolException if python syntax error """ script_content = 'my_var :=: 4' script_path = join(work_dir, 'test.py') with pytest.raises(MlVToolException) as e: write_python_script(script_content, script_path) assert isinstance(e.value.__cause__, SyntaxError)
32.710623
111
0.710974
import stat from os import stat as os_stat from os.path import join, exists from tempfile import TemporaryDirectory import pytest from jinja2 import UndefinedError, TemplateSyntaxError from mlvtools.exception import MlVToolException from mlvtools.helper import extract_type, to_dvc_meta_filename, to_instructions_list, \ write_python_script, write_template, to_sanitized_path from mlvtools.helper import to_cmd_param, to_method_name, to_bash_variable, to_script_name, to_dvc_cmd_name def test_should_convert_to_command_param(): """ Test convert to command parameter """ assert to_cmd_param('my_param_One') == 'my-param-One' def test_should_convert_to_bash_variable(): """ Test convert to bash variable """ assert to_bash_variable('my-param-one') == 'MY_PARAM_ONE' def test_should_convert_to_method_name(): """ Test convert file name without extension to a python method name """ assert to_method_name('01my-Meth$odk++ Name.truc') == 'mlvtools_01my_meth_odk_name_truc' def test_should_convert_to_script_name(): """ Test convert file name to script name """ assert to_script_name('My notebook.ipynb') == 'mlvtools_my_notebook.py' def test_should_convert_to_dvc_meta_filename(): """ Test convert notebook path to dvc meta filename """ assert to_dvc_meta_filename('./toto/truc/My notebook.ipynb') == 'my_notebook.dvc' def test_should_convert_to_instructions_list(): """ Test convert a string of several instructions into a list of instructions """ assert to_instructions_list('\nimport os\na = 45\n') == ['import os', 'a = 45'] def test_should_extract_python_str_and_int(): """ Test extract python str and int types """ type_info = extract_type('str ') assert type_info.type_name == 'str' assert not type_info.is_list type_info = extract_type(' int') assert type_info.type_name == 'int' assert not type_info.is_list def test_should_return_none_if_extract_python_of_no_type(): """ Test extract python return None if empty type """ type_info = extract_type('') assert not type_info.type_name assert not type_info.is_list type_info = extract_type(None) assert not type_info.type_name assert not type_info.is_list def test_should_extract_python_list_type(): """ Test extract python list type """ type_info = extract_type('list') assert type_info.type_name == 'str' assert type_info.is_list type_info = extract_type('List') assert type_info.type_name == 'str' assert type_info.is_list type_info = extract_type('list[str]') assert type_info.type_name == 'str' assert type_info.is_list type_info = extract_type('List[int]') assert type_info.type_name == 'int' assert type_info.is_list def test_should_convert_to_dvc_cmd_name(): """ Test convert script name to dvc command name """ assert to_dvc_cmd_name('my_notebook.py') == 'my_notebook_dvc' def test_should_sanitize_path(): """ Test should add ./ to path if does not start wiht / or ./ """ assert to_sanitized_path('toto.py') == './toto.py' def test_sanitize_should_not_change_absolute_path(): """ Test sanitize should not change absolute path """ absolute_path = '/absolut/path/toto.py' assert to_sanitized_path(absolute_path) == absolute_path def test_sanitize_should_not_change_path_starting_with_dot_slash(): """ Test sanitize should not change path starting with dot slash """ path = './toto.py' assert to_sanitized_path(path) == path @pytest.fixture def valid_template_path(work_dir): template_data = 'a_value={{ given_data }}' template_path = join(work_dir, 'template.tpl') with open(template_path, 'w') as fd: fd.write(template_data) return template_path def test_should_write_template(work_dir, valid_template_path): """ Test write an executable file from a given template and data """ output_path = join(work_dir, 'my_exe.sh') write_template(output_path, valid_template_path, given_data='test') assert exists(output_path) assert stat.S_IMODE(os_stat(output_path).st_mode) == 0o755 with open(output_path, 'r') as fd: assert fd.read() == 'a_value=test' def test_should_create_directory_to_write_template(work_dir, valid_template_path): """ Test create directory and write template """ output_path = join(work_dir, 'a_dir', 'my_exe.sh') write_template(output_path, valid_template_path, given_data='test') assert exists(join(work_dir, 'a_dir')) assert exists(output_path) def check_write_template_error_case(template_path: str, data: dict, exp_error: Exception): with TemporaryDirectory() as tmp_dir: output_path = join(tmp_dir, 'my_exe.sh') with pytest.raises(MlVToolException) as e: write_template(output_path, template_path, **data) assert isinstance(e.value.__cause__, exp_error) def test_write_template_should_raise_if_template_does_not_exist(work_dir): """ Test write_template raise an MlVToolException if the template file does not exist """ template_path = join(work_dir, 'not_existing_template.tpl') check_write_template_error_case(template_path, data={}, exp_error=IOError) def test_write_template_should_raise_if_template_format_error(work_dir): """ Test write_template raise an MlVToolException if the template is wrongly formatted """ template_data = 'a_value={{ t_data' template_path = join(work_dir, 'template_wrong_format.tpl') with open(template_path, 'w') as fd: fd.write(template_data) check_write_template_error_case(template_path, data={'t_data': 'test'}, exp_error=TemplateSyntaxError) @pytest.mark.parametrize('missing_pattern', (('{{ printed_var }}', '{% for val in iterated_var %}{% endfor %}', '{{ accessed.var }}'))) def test_write_template_should_raise_if_missing_template_data(work_dir, missing_pattern): """ Test write_template raise an MlVToolException if there is an undefined template variable Case of : - print - iteration - other access """ template_data = f'a_value={missing_pattern}' template_path = join(work_dir, 'template.tpl') with open(template_path, 'w') as fd: fd.write(template_data) check_write_template_error_case(template_path, data={}, exp_error=UndefinedError) def test_write_template_should_raise_if_can_not_write_executable_output(work_dir, mocker, valid_template_path): """ Test write_template raise an MlVToolException if the executable output cannot be written """ output_path = join(work_dir, 'output.sh') mocker.patch('builtins.open', side_effect=IOError) with pytest.raises(MlVToolException) as e: write_template(output_path, valid_template_path, given_data='test') assert isinstance(e.value.__cause__, IOError) def test_should_write_formatted_python_script(work_dir): """ Test write formatted and executable python script """ script_content = 'my_var=4\nmy_list=[1,2,3]' script_path = join(work_dir, 'test.py') write_python_script(script_content, script_path) assert exists(script_path) assert stat.S_IMODE(os_stat(script_path).st_mode) == 0o755 with open(script_path, 'r') as fd: assert fd.read() == 'my_var = 4\nmy_list = [1, 2, 3]\n' def test_should_create_directory_to_write_formatted_python_script(work_dir): """ Test create directory and write formatted and executable python script """ script_content = 'my_var=4' script_path = join(work_dir, 'a_dir', 'test.py') write_python_script(script_content, script_path) assert exists(join(work_dir, 'a_dir')) assert exists(script_path) def test_write_python_script_should_raise_if_cannot_write_executable_script(work_dir, mocker): """ Test write_python_script raise an MlVToolException if can not write executable output """ script_content = 'my_var=4\nmy_list=[1,2,3]' script_path = join(work_dir, 'test.py') mocker.patch('builtins.open', side_effect=IOError) with pytest.raises(MlVToolException) as e: write_python_script(script_content, script_path) assert isinstance(e.value.__cause__, IOError) def test_write_python_script_should_raise_if_python_syntax_error(work_dir): """ Test write_python_script raise an MlVToolException if python syntax error """ script_content = 'my_var :=: 4' script_path = join(work_dir, 'test.py') with pytest.raises(MlVToolException) as e: write_python_script(script_content, script_path) assert isinstance(e.value.__cause__, SyntaxError)
535
0
45
53c4a2c8bc3e7b21877246873b9e265e6ac85017
6,675
py
Python
tablo/grid.py
jessedp/tut
6864f953e3dacd800c9f5a50cec7221e89d47f7d
[ "MIT" ]
4
2020-01-24T21:40:36.000Z
2021-09-10T22:30:17.000Z
tablo/grid.py
jessedp/tut
6864f953e3dacd800c9f5a50cec7221e89d47f7d
[ "MIT" ]
null
null
null
tablo/grid.py
jessedp/tut
6864f953e3dacd800c9f5a50cec7221e89d47f7d
[ "MIT" ]
1
2021-09-11T09:36:46.000Z
2021-09-11T09:36:46.000Z
import os import json import time import datetime import tablo from lib import backgroundthread from .util import logger SAVE_VERSION = 1 INTERVAL_HOURS = 2 INTERVAL_TIMEDELTA = datetime.timedelta(hours=INTERVAL_HOURS) PENDING_UPDATE = {}
29.535398
77
0.593408
import os import json import time import datetime import tablo from lib import backgroundthread from .util import logger SAVE_VERSION = 1 INTERVAL_HOURS = 2 INTERVAL_TIMEDELTA = datetime.timedelta(hours=INTERVAL_HOURS) PENDING_UPDATE = {} def addPending(path=None, airing=None): path = path or airing.data['airing_details']['channel_path'] PENDING_UPDATE[path] = 1 class ChannelTask(backgroundthread.Task): def setup(self, channel, callback): self.path = channel.path self.channel = channel self.callback = callback def run(self): n = tablo.api.UTCNow() start = n - tablo.compat.datetime.timedelta( minutes=n.minute % 30, seconds=n.second, microseconds=n.microsecond ) sec_in_day = 86400 # This is weird. 5400 = 90 minutes. # So currently below it's 1 day + 3 hrs (90 min * 2) interval_secs = 5400 data = tablo.API.views.livetv.channels(self.channel.object_id).get( start=start.strftime('%Y-%m-%dT%H:%MZ'), duration=sec_in_day + (interval_secs * INTERVAL_HOURS) ) if self.isCanceled(): return logger.debug('Retrieved channel: {0}'.format(self.channel.object_id)) self.callback(self.path, data) class Grid(object): def __init__(self, work_path, update_callback): self.channels = {} self.paths = [] self._airings = {} self._hasData = {} self.updateCallback = update_callback self._tasks = [] self.workPath = os.path.join(work_path, 'grid') self.oldestUpdate = datetime.datetime.now() self.pendingUpdate = {} self.initSave() def initSave(self): if not os.path.exists(self.workPath): os.makedirs(self.workPath) def saveVersion(self): data = {'version': SAVE_VERSION} with open(os.path.join(self.workPath, 'version'), 'w') as f: json.dump(data, f) def saveChannelData(self, data): with open(os.path.join(self.workPath, 'channels.data'), 'w') as f: json.dump(data, f) def saveChannelAiringData(self, channel, data): file = str(channel.object_id) + '.air' with open(os.path.join(self.workPath, file, 'w')) as f: updated = time.mktime(datetime.datetime.now().timetuple()) json.dump({'updated': updated, 'data': data}, f) def updateChannelAiringData(self, channel=None, path=None): channel = channel or self.channels[path] path = str(channel.object_id) + '.air' # os.remove(os.path.join( # self.workPath, str(channel.object_id) + '.air')) with open(os.path.join(self.workPath, path, 'r')) as f: data = json.load(f) data['updated'] = 0 with open(os.path.join(self.workPath, path, 'w')) as f: json.dump(data, f) self.getChannelData(channel) def loadVersion(self): path = os.path.join(self.workPath, 'version') if not os.path.exists(path): return None with open(path, 'r') as f: data = json.load(f) return data def loadChannels(self): self.cancelTasks() # path = os.path.join(self.workPath, 'channels.data') # if not os.path.exists(path): # return False # logger.debug('Loading saved grid data...') # with open(path, 'r') as f: # self.channels = json.load(f) logger.debug('Loading grid data...') self.channels = {} channels = tablo.API.batch.post(self.paths) for path in channels: channel = tablo.Channel(channels[path]) self.channels[path] = channel if path not in self._airings: self._airings[path] = [] self.updateCallback(channel) self.loadAirings(channel) for path in channels: self.getChannelData(self.channels[path]) logger.debug('Loading of grid data done.') return True def loadAirings(self, channel): path = os.path.join(self.workPath, str(channel.object_id) + '.air') if not os.path.exists(path): self._airings[channel.path] = [] return False with open(path, 'r') as f: data = json.load(f) ret = True updated = datetime.datetime.fromtimestamp(int(data['updated'])) age = (datetime.datetime.now() - updated) if age > INTERVAL_TIMEDELTA: ret = False if updated < self.oldestUpdate: self.oldestUpdate = updated self._airings[channel.path] = \ [tablo.GridAiring(a) for a in data['data']] if self._airings[channel.path]: self.updateCallback(channel) return ret return False def getChannelData(self, channel=None, path=None): channel = channel or self.channels[path] t = ChannelTask() self._tasks.append(t) t.setup(channel, self.channelDataCallback) backgroundthread.BGThreader.addTask(t) def channelDataCallback(self, path, data): self._hasData[path] = data and True or False # This only works HERE - before we convert the airing data self.saveChannelAiringData(self.channels[path], data) self._airings[path] = [tablo.GridAiring(a) for a in data] self.updateCallback(self.channels[path]) def cancelTasks(self): if not self._tasks: return logger.debug('Canceling {0} tasks (GRID)'.format(len(self._tasks))) for t in self._tasks: t.cancel() self._tasks = [] def getChannels(self, paths=None): self.paths = paths or tablo.API.guide.channels.get() self.loadChannels() self.saveVersion() def triggerUpdates(self): for path in self.channels: self.updateCallback(self.channels[path]) def airings(self, start, cutoff, channel_path=None, channel=None): channel = channel or self.channels[channel_path] return [a for a in self._airings[channel.path] if a.datetimeEnd > start and a.datetime < cutoff] def hasNoData(self, path): return self._hasData.get(path) is False def getAiring(self, path): for c in self._airings.values(): for a in c: if a.path == path: return a return None def updatePending(self): global PENDING_UPDATE for p in PENDING_UPDATE.keys(): self.getChannelData(path=p) PENDING_UPDATE = {}
5,804
18
607
3ee770460cefa4f48ae7543f053e1b5598cb884b
5,874
py
Python
experiments/plot_benchmark.py
ashley062190/pycpa_taskchain
4274371b90407fe9715ca2d5d5793bf4736f53e2
[ "MIT" ]
1
2021-07-25T19:37:03.000Z
2021-07-25T19:37:03.000Z
experiments/plot_benchmark.py
ashley062190/pycpa_taskchain
4274371b90407fe9715ca2d5d5793bf4736f53e2
[ "MIT" ]
null
null
null
experiments/plot_benchmark.py
ashley062190/pycpa_taskchain
4274371b90407fe9715ca2d5d5793bf4736f53e2
[ "MIT" ]
1
2020-12-10T17:01:20.000Z
2020-12-10T17:01:20.000Z
#!/usr/bin/env python import argparse import csv from pyplot_helper import barchart from matplotlib import pyplot from palettable.colorbrewer.qualitative import Paired_12 as Colors parser = argparse.ArgumentParser(description='Plot benchmark results.') parser.add_argument('--inputs', type=str, required=True, nargs='+', help='Input files') parser.add_argument('--output', type=str, help='Output file') parser.add_argument('--delimiter', default='\t', type=str, help='CSV delimiter') parser.add_argument('--fontsize', default=20, type=int, help='Font size') parser.add_argument('--colorshift', default=1, type=int) parser.add_argument('--parameters', type=str, nargs='+', required=True, help='Parameters to evaluate') parser.add_argument('--names', type=str, default=None, nargs="+", help='Names') parser.add_argument('--filter_load', type=str, default=None, nargs='+') parser.add_argument('--filter_length', type=str, default=None, nargs='+') parser.add_argument('--filter_number', type=str, default=None, nargs='+') parser.add_argument('--filter_nesting', type=str, default=None, nargs='+') parser.add_argument('--filter_sharing', type=str, default=None, nargs='+') parser.add_argument('--absolute', action='store_true') parser.add_argument('--stackfailed', action='store_true') parser.add_argument('--failed', action='store_true') args = parser.parse_args() charts = dict() i = 0 for param in args.parameters: name = param if args.names is not None: name = args.names[i] ylabel = "" charts[param] = barchart.BarChart(ylabel=ylabel, xlabel=name, title="", width=1, rotation=0, colors=Colors.mpl_colors, colorshift=args.colorshift, xticksize=args.fontsize, labelsize=args.fontsize, legend_loc="upper right", legend_cols=len(args.parameters)+1, legend_anchor=(1,1.2), legendsize=args.fontsize) i += 1 fig, axes = pyplot.subplots(1, len(charts), figsize=(6*len(charts),5)) i = 0 for param in charts: data = read_data(param) for group in data: values = list() for cat in data[group]: if args.absolute: if args.stackfailed: val = [data[group][cat]['failed'], data[group][cat]['good']] elif args.failed: val = data[group][cat]['failed'] else: val = data[group][cat]['good'] else: good = data[group][cat]['good'] total = data[group][cat]['total'] failed = data[group][cat]['failed'] if args.stackfailed: val = [failed * 100 / total, good * 100 / total] elif args.failed: val = failed * 100 / total else: val = good * 100 / total values.append((cat, val)) charts[param].add_group_data(group, values) if args.filter_load is not None: for load in args.filter_load: charts[param].add_category(load, load +"% Load") else: charts[param].add_category("60", "60% Load") charts[param].add_category("80", "80% Load") charts[param].add_category("90", "90% Load") charts[param].add_category("95", "95% Load") charts[param].add_category("98", "98% Load") charts[param].add_category("99", "99% Load") charts[param].add_category("100", "100% Load") charts[param].plot(axes[i], stacked=False, sort=False) i += 1 for ax in axes: ax.set_yticks([20, 40, 60, 80, 100]) ax.set_yticklabels(list()) axes[0].set_yticklabels(["20%", "40%", "60%", "80%", "100%"], fontsize=args.fontsize) pyplot.rcParams.update({'font.size': args.fontsize}) # output if args.output is not None: # fig.subplots_adjust(top=0.5, bottom=0.15) pyplot.tight_layout(rect=(0, -0.05, 1, 0.95)) pyplot.savefig(args.output) else: pyplot.show() # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
35.817073
105
0.562138
#!/usr/bin/env python import argparse import csv from pyplot_helper import barchart from matplotlib import pyplot from palettable.colorbrewer.qualitative import Paired_12 as Colors parser = argparse.ArgumentParser(description='Plot benchmark results.') parser.add_argument('--inputs', type=str, required=True, nargs='+', help='Input files') parser.add_argument('--output', type=str, help='Output file') parser.add_argument('--delimiter', default='\t', type=str, help='CSV delimiter') parser.add_argument('--fontsize', default=20, type=int, help='Font size') parser.add_argument('--colorshift', default=1, type=int) parser.add_argument('--parameters', type=str, nargs='+', required=True, help='Parameters to evaluate') parser.add_argument('--names', type=str, default=None, nargs="+", help='Names') parser.add_argument('--filter_load', type=str, default=None, nargs='+') parser.add_argument('--filter_length', type=str, default=None, nargs='+') parser.add_argument('--filter_number', type=str, default=None, nargs='+') parser.add_argument('--filter_nesting', type=str, default=None, nargs='+') parser.add_argument('--filter_sharing', type=str, default=None, nargs='+') parser.add_argument('--absolute', action='store_true') parser.add_argument('--stackfailed', action='store_true') parser.add_argument('--failed', action='store_true') args = parser.parse_args() charts = dict() i = 0 for param in args.parameters: name = param if args.names is not None: name = args.names[i] ylabel = "" charts[param] = barchart.BarChart(ylabel=ylabel, xlabel=name, title="", width=1, rotation=0, colors=Colors.mpl_colors, colorshift=args.colorshift, xticksize=args.fontsize, labelsize=args.fontsize, legend_loc="upper right", legend_cols=len(args.parameters)+1, legend_anchor=(1,1.2), legendsize=args.fontsize) i += 1 def read_data(param): groups = dict() for filename in args.inputs: with open(filename, 'r') as csvfile: reader = csv.DictReader(csvfile, delimiter='\t') for row in reader: group = row[param] cat = row['Load'] if args.filter_load is not None: if cat not in args.filter_load: continue if args.filter_number is not None: if row['Number'] not in args.filter_number: continue if args.filter_length is not None: if row['Length'] not in args.filter_length: continue if args.filter_nesting is not None: if row['Nesting'] not in args.filter_nesting: continue if args.filter_sharing is not None: if row['Sharing'] not in args.filter_sharing: continue if group not in groups: groups[group] = dict() if cat not in groups[group]: groups[group][cat] = dict() groups[group][cat]['total'] = 0 groups[group][cat]['good'] = 0 # schedulable / (total-good-failed) = unschedulable groups[group][cat]['failed'] = 0 # too may recursions groups[group][cat]['total'] += 1 if row['Schedulable'] == 'True': groups[group][cat]['good'] += 1 assert(row['MaxRecur'] == 'False') elif row['MaxRecur'] == 'True': groups[group][cat]['failed'] += 1 return groups fig, axes = pyplot.subplots(1, len(charts), figsize=(6*len(charts),5)) i = 0 for param in charts: data = read_data(param) for group in data: values = list() for cat in data[group]: if args.absolute: if args.stackfailed: val = [data[group][cat]['failed'], data[group][cat]['good']] elif args.failed: val = data[group][cat]['failed'] else: val = data[group][cat]['good'] else: good = data[group][cat]['good'] total = data[group][cat]['total'] failed = data[group][cat]['failed'] if args.stackfailed: val = [failed * 100 / total, good * 100 / total] elif args.failed: val = failed * 100 / total else: val = good * 100 / total values.append((cat, val)) charts[param].add_group_data(group, values) if args.filter_load is not None: for load in args.filter_load: charts[param].add_category(load, load +"% Load") else: charts[param].add_category("60", "60% Load") charts[param].add_category("80", "80% Load") charts[param].add_category("90", "90% Load") charts[param].add_category("95", "95% Load") charts[param].add_category("98", "98% Load") charts[param].add_category("99", "99% Load") charts[param].add_category("100", "100% Load") charts[param].plot(axes[i], stacked=False, sort=False) i += 1 for ax in axes: ax.set_yticks([20, 40, 60, 80, 100]) ax.set_yticklabels(list()) axes[0].set_yticklabels(["20%", "40%", "60%", "80%", "100%"], fontsize=args.fontsize) pyplot.rcParams.update({'font.size': args.fontsize}) # output if args.output is not None: # fig.subplots_adjust(top=0.5, bottom=0.15) pyplot.tight_layout(rect=(0, -0.05, 1, 0.95)) pyplot.savefig(args.output) else: pyplot.show() # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
1,734
0
23
fbfd3b50dfdb41c7c33541e22d66678c2f866fd8
7,527
py
Python
lib/googlecloudsdk/api_lib/compute/vpn_gateways/vpn_gateways_utils.py
google-cloud-sdk-unofficial/google-cloud-sdk
2a48a04df14be46c8745050f98768e30474a1aac
[ "Apache-2.0" ]
2
2019-11-10T09:17:07.000Z
2019-12-18T13:44:08.000Z
lib/googlecloudsdk/api_lib/compute/vpn_gateways/vpn_gateways_utils.py
google-cloud-sdk-unofficial/google-cloud-sdk
2a48a04df14be46c8745050f98768e30474a1aac
[ "Apache-2.0" ]
null
null
null
lib/googlecloudsdk/api_lib/compute/vpn_gateways/vpn_gateways_utils.py
google-cloud-sdk-unofficial/google-cloud-sdk
2a48a04df14be46c8745050f98768e30474a1aac
[ "Apache-2.0" ]
1
2020-07-25T01:40:19.000Z
2020-07-25T01:40:19.000Z
# -*- coding: utf-8 -*- # # Copyright 2019 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """API utilities for gcloud compute vpn-gateways commands.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.api_lib.compute.operations import poller from googlecloudsdk.api_lib.util import waiter import six class VpnGatewayHelper(object): """Helper for VPN gateway service in the Compute API.""" def __init__(self, holder): """Initializes the helper for VPN Gateway operations. Args: holder: Object representing the Compute API holder instance. """ self._compute_client = holder.client self._resources = holder.resources @property @property @property def GetVpnGatewayForInsert(self, name, description, network, vpn_interfaces_with_interconnect_attachments, stack_type): """Returns the VpnGateway message for an insert request. Args: name: String representing the name of the VPN Gateway resource. description: String representing the description for the VPN Gateway resource. network: String representing the network URL the VPN gateway resource belongs to. vpn_interfaces_with_interconnect_attachments: Dict representing pairs interface id and interconnected attachment associated with vpn gateway on this interface. stack_type: Enum presenting the stack type of the vpn gateway resource. Returns: The VpnGateway message object that can be used in an insert request. """ if vpn_interfaces_with_interconnect_attachments is not None: vpn_interfaces = [] for key, value in sorted( vpn_interfaces_with_interconnect_attachments.items()): vpn_interfaces.append( self._messages.VpnGatewayVpnGatewayInterface( id=int(key), interconnectAttachment=six.text_type(value))) if stack_type is not None: return self._messages.VpnGateway( name=name, description=description, network=network, vpnInterfaces=vpn_interfaces, stackType=self._messages.VpnGateway.StackTypeValueValuesEnum( stack_type)) else: return self._messages.VpnGateway( name=name, description=description, network=network, vpnInterfaces=vpn_interfaces) else: if stack_type is not None: return self._messages.VpnGateway( name=name, description=description, network=network, stackType=self._messages.VpnGateway.StackTypeValueValuesEnum( stack_type)) else: return self._messages.VpnGateway( name=name, description=description, network=network) def WaitForOperation(self, vpn_gateway_ref, operation_ref, wait_message): """Waits for the specified operation to complete and returns the target. Args: vpn_gateway_ref: The VPN Gateway reference object. operation_ref: The operation reference object to wait for. wait_message: String representing the wait message to display while the operation is in progress. Returns: The resulting resource object after the operation completes. """ operation_poller = poller.Poller(self._service, vpn_gateway_ref) return waiter.WaitFor(operation_poller, operation_ref, wait_message) def Create(self, ref, vpn_gateway): """Sends an Insert request for a VPN Gateway and returns the operation. Args: ref: The VPN Gateway reference object. vpn_gateway: The VPN Gateway message object to use in the insert request. Returns: The operation reference object for the insert request. """ request = self._messages.ComputeVpnGatewaysInsertRequest( project=ref.project, region=ref.region, vpnGateway=vpn_gateway) operation = self._service.Insert(request) return self._resources.Parse( operation.selfLink, collection='compute.regionOperations') def Describe(self, ref): """Sends a Get request for a VPN Gateway and returns the resource. Args: ref: The VPN Gateway reference object. Returns: The VPN Gateway resource object. """ request = self._messages.ComputeVpnGatewaysGetRequest( project=ref.project, region=ref.region, vpnGateway=ref.Name()) return self._service.Get(request) def Delete(self, ref): """Sends a Delete request for a VPN Gateway and returns the operation. Args: ref: The VPN Gateway reference object. Returns: The operation reference object for the delete request. """ request = self._messages.ComputeVpnGatewaysDeleteRequest( project=ref.project, region=ref.region, vpnGateway=ref.Name()) operation = self._service.Delete(request) return self._resources.Parse( operation.selfLink, collection='compute.regionOperations') def List(self, project, filter_expr): """Yields a VPN Gateway resource from the list of VPN Gateways. Sends an AggregatedList request to obtain the list of VPN Gateways and yields the next VPN Gateway in this list. Args: project: String representing the project to use for the request. filter_expr: The expression used to filter the results. """ next_page_token = None while True: request = self._messages.ComputeVpnGatewaysAggregatedListRequest( project=project, filter=filter_expr, pageToken=next_page_token) response = self._service.AggregatedList(request) next_page_token = response.nextPageToken for scoped_vpn_gateways in response.items.additionalProperties: for vpn_gateway in scoped_vpn_gateways.value.vpnGateways: yield vpn_gateway if not next_page_token: break def SetLabels(self, ref, existing_label_fingerprint, new_labels): """Sends a SetLabels request for a VPN Gateway and returns the operation. Args: ref: The VPN Gateway reference object. existing_label_fingerprint: The existing label fingerprint. new_labels: List of new label key, value pairs. Returns: The operation reference object for the SetLabels request. """ set_labels_request = self._messages.RegionSetLabelsRequest( labelFingerprint=existing_label_fingerprint, labels=new_labels) request = self._messages.ComputeVpnGatewaysSetLabelsRequest( project=ref.project, region=ref.region, resource=ref.Name(), regionSetLabelsRequest=set_labels_request) operation = self._service.SetLabels(request) return self._resources.Parse( operation.selfLink, collection='compute.regionOperations')
36.897059
79
0.712369
# -*- coding: utf-8 -*- # # Copyright 2019 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """API utilities for gcloud compute vpn-gateways commands.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.api_lib.compute.operations import poller from googlecloudsdk.api_lib.util import waiter import six class VpnGatewayHelper(object): """Helper for VPN gateway service in the Compute API.""" def __init__(self, holder): """Initializes the helper for VPN Gateway operations. Args: holder: Object representing the Compute API holder instance. """ self._compute_client = holder.client self._resources = holder.resources @property def _client(self): return self._compute_client.apitools_client @property def _messages(self): return self._compute_client.messages @property def _service(self): return self._client.vpnGateways def GetVpnGatewayForInsert(self, name, description, network, vpn_interfaces_with_interconnect_attachments, stack_type): """Returns the VpnGateway message for an insert request. Args: name: String representing the name of the VPN Gateway resource. description: String representing the description for the VPN Gateway resource. network: String representing the network URL the VPN gateway resource belongs to. vpn_interfaces_with_interconnect_attachments: Dict representing pairs interface id and interconnected attachment associated with vpn gateway on this interface. stack_type: Enum presenting the stack type of the vpn gateway resource. Returns: The VpnGateway message object that can be used in an insert request. """ if vpn_interfaces_with_interconnect_attachments is not None: vpn_interfaces = [] for key, value in sorted( vpn_interfaces_with_interconnect_attachments.items()): vpn_interfaces.append( self._messages.VpnGatewayVpnGatewayInterface( id=int(key), interconnectAttachment=six.text_type(value))) if stack_type is not None: return self._messages.VpnGateway( name=name, description=description, network=network, vpnInterfaces=vpn_interfaces, stackType=self._messages.VpnGateway.StackTypeValueValuesEnum( stack_type)) else: return self._messages.VpnGateway( name=name, description=description, network=network, vpnInterfaces=vpn_interfaces) else: if stack_type is not None: return self._messages.VpnGateway( name=name, description=description, network=network, stackType=self._messages.VpnGateway.StackTypeValueValuesEnum( stack_type)) else: return self._messages.VpnGateway( name=name, description=description, network=network) def WaitForOperation(self, vpn_gateway_ref, operation_ref, wait_message): """Waits for the specified operation to complete and returns the target. Args: vpn_gateway_ref: The VPN Gateway reference object. operation_ref: The operation reference object to wait for. wait_message: String representing the wait message to display while the operation is in progress. Returns: The resulting resource object after the operation completes. """ operation_poller = poller.Poller(self._service, vpn_gateway_ref) return waiter.WaitFor(operation_poller, operation_ref, wait_message) def Create(self, ref, vpn_gateway): """Sends an Insert request for a VPN Gateway and returns the operation. Args: ref: The VPN Gateway reference object. vpn_gateway: The VPN Gateway message object to use in the insert request. Returns: The operation reference object for the insert request. """ request = self._messages.ComputeVpnGatewaysInsertRequest( project=ref.project, region=ref.region, vpnGateway=vpn_gateway) operation = self._service.Insert(request) return self._resources.Parse( operation.selfLink, collection='compute.regionOperations') def Describe(self, ref): """Sends a Get request for a VPN Gateway and returns the resource. Args: ref: The VPN Gateway reference object. Returns: The VPN Gateway resource object. """ request = self._messages.ComputeVpnGatewaysGetRequest( project=ref.project, region=ref.region, vpnGateway=ref.Name()) return self._service.Get(request) def Delete(self, ref): """Sends a Delete request for a VPN Gateway and returns the operation. Args: ref: The VPN Gateway reference object. Returns: The operation reference object for the delete request. """ request = self._messages.ComputeVpnGatewaysDeleteRequest( project=ref.project, region=ref.region, vpnGateway=ref.Name()) operation = self._service.Delete(request) return self._resources.Parse( operation.selfLink, collection='compute.regionOperations') def List(self, project, filter_expr): """Yields a VPN Gateway resource from the list of VPN Gateways. Sends an AggregatedList request to obtain the list of VPN Gateways and yields the next VPN Gateway in this list. Args: project: String representing the project to use for the request. filter_expr: The expression used to filter the results. """ next_page_token = None while True: request = self._messages.ComputeVpnGatewaysAggregatedListRequest( project=project, filter=filter_expr, pageToken=next_page_token) response = self._service.AggregatedList(request) next_page_token = response.nextPageToken for scoped_vpn_gateways in response.items.additionalProperties: for vpn_gateway in scoped_vpn_gateways.value.vpnGateways: yield vpn_gateway if not next_page_token: break def SetLabels(self, ref, existing_label_fingerprint, new_labels): """Sends a SetLabels request for a VPN Gateway and returns the operation. Args: ref: The VPN Gateway reference object. existing_label_fingerprint: The existing label fingerprint. new_labels: List of new label key, value pairs. Returns: The operation reference object for the SetLabels request. """ set_labels_request = self._messages.RegionSetLabelsRequest( labelFingerprint=existing_label_fingerprint, labels=new_labels) request = self._messages.ComputeVpnGatewaysSetLabelsRequest( project=ref.project, region=ref.region, resource=ref.Name(), regionSetLabelsRequest=set_labels_request) operation = self._service.SetLabels(request) return self._resources.Parse( operation.selfLink, collection='compute.regionOperations')
119
0
72
b1aa34333b0943f112cf870b0d9e96b53724f625
628
py
Python
examples/example_3/tuned_solver.py
ghbrown/mg_tune
674957e4eb24e94d9f033bffdf5e42a54b00f155
[ "MIT" ]
null
null
null
examples/example_3/tuned_solver.py
ghbrown/mg_tune
674957e4eb24e94d9f033bffdf5e42a54b00f155
[ "MIT" ]
null
null
null
examples/example_3/tuned_solver.py
ghbrown/mg_tune
674957e4eb24e94d9f033bffdf5e42a54b00f155
[ "MIT" ]
null
null
null
import numpy as np import pyamg #the function must be called solve and take (A,b) as inputs
41.866667
195
0.735669
import numpy as np import pyamg #the function must be called solve and take (A,b) as inputs def solve(A,b): #max_levels not an effective tuning parameter, since often #it just results in a multilevel hierarchy which is far too #large on the coarsest level #therefore fix it to be large so depth of hierarchy is #controlled by max_coarse alone ml = pyamg.aggregation.smoothed_aggregation_solver(A,max_levels=1000, strength='classical', aggregate='standard', smooth='energy', presmoother='richardson', postsmoother='sor', max_coarse=16) x = ml.solve(b,tol=1e-6, cycle='F', accel='cgne') return x
512
0
22
b7224b29868dc27f45e86b949857a205ad1d621b
9,852
py
Python
tf_image_segmentation/recipes/pascal_voc/data_pascal_voc.py
tataganesh95/tf-image-segmentation
c609bf71924191de7ae1dd887ee613fa7c1c5797
[ "MIT" ]
null
null
null
tf_image_segmentation/recipes/pascal_voc/data_pascal_voc.py
tataganesh95/tf-image-segmentation
c609bf71924191de7ae1dd887ee613fa7c1c5797
[ "MIT" ]
null
null
null
tf_image_segmentation/recipes/pascal_voc/data_pascal_voc.py
tataganesh95/tf-image-segmentation
c609bf71924191de7ae1dd887ee613fa7c1c5797
[ "MIT" ]
null
null
null
#!/usr/bin/env python # coding=utf-8 """ This is a script for downloading and converting the pascal voc 2012 dataset and the berkely extended version. # original PASCAL VOC 2012 # wget http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar # 2 GB # berkeley augmented Pascal VOC # wget http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/semantic_contours/benchmark.tgz # 1.3 GB This can be run as an independent executable to download the dataset or be imported by scripts used for larger experiments. If you aren't sure run this to do a full download + conversion setup of the dataset: ./data_pascal_voc.py pascal_voc_setup """ from __future__ import division, print_function, unicode_literals from sacred import Ingredient, Experiment import sys import numpy as np from PIL import Image from collections import defaultdict import os from keras.utils import get_file # from tf_image_segmentation.recipes import datasets from tf_image_segmentation.utils.tf_records import write_image_annotation_pairs_to_tfrecord from tf_image_segmentation.utils import pascal_voc import tarfile # ============== Ingredient 2: dataset ======================= data_pascal_voc = Experiment("dataset") @data_pascal_voc.config @data_pascal_voc.capture @data_pascal_voc.command @data_pascal_voc.command @data_pascal_voc.config @data_pascal_voc.command @data_pascal_voc.command @data_pascal_voc.command @data_pascal_voc.automain
42.465517
117
0.676918
#!/usr/bin/env python # coding=utf-8 """ This is a script for downloading and converting the pascal voc 2012 dataset and the berkely extended version. # original PASCAL VOC 2012 # wget http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar # 2 GB # berkeley augmented Pascal VOC # wget http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/semantic_contours/benchmark.tgz # 1.3 GB This can be run as an independent executable to download the dataset or be imported by scripts used for larger experiments. If you aren't sure run this to do a full download + conversion setup of the dataset: ./data_pascal_voc.py pascal_voc_setup """ from __future__ import division, print_function, unicode_literals from sacred import Ingredient, Experiment import sys import numpy as np from PIL import Image from collections import defaultdict import os from keras.utils import get_file # from tf_image_segmentation.recipes import datasets from tf_image_segmentation.utils.tf_records import write_image_annotation_pairs_to_tfrecord from tf_image_segmentation.utils import pascal_voc import tarfile # ============== Ingredient 2: dataset ======================= data_pascal_voc = Experiment("dataset") @data_pascal_voc.config def voc_config(): # TODO(ahundt) add md5 sums for each file verbose = True dataset_root = os.path.expanduser("~") + "/.keras/datasets" dataset_path = dataset_root + '/VOC2012' # sys.path.append("tf-image-segmentation/") # os.environ["CUDA_VISIBLE_DEVICES"] = '1' # based on https://github.com/martinkersner/train-DeepLab # original PASCAL VOC 2012 # wget http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar # 2 GB pascal_root = dataset_path + '/VOCdevkit/VOC2012' # berkeley augmented Pascal VOC # wget http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/semantic_contours/benchmark.tgz # 1.3 GB # Pascal Context # http://www.cs.stanford.edu/~roozbeh/pascal-context/ # http://www.cs.stanford.edu/~roozbeh/pascal-context/trainval.tar.gz pascal_berkeley_root = dataset_path + '/benchmark_RELEASE' urls = [ 'http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar', 'http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/semantic_contours/benchmark.tgz', 'http://www.cs.stanford.edu/~roozbeh/pascal-context/trainval.tar.gz', 'http://www.cs.stanford.edu/~roozbeh/pascal-context/33_context_labels.tar.gz', 'http://www.cs.stanford.edu/~roozbeh/pascal-context/59_context_labels.tar.gz', 'http://www.cs.stanford.edu/~roozbeh/pascal-context/33_labels.txt', 'http://www.cs.stanford.edu/~roozbeh/pascal-context/59_labels.txt' ] filenames = ['VOCtrainval_11-May-2012.tar', 'benchmark.tgz', 'trainval.tar.gz', '33_context_labels.tar.gz', '59_context_labels.tar.gz', '33_labels.txt', '59_labels.txt' ] md5s = ['6cd6e144f989b92b3379bac3b3de84fd', '82b4d87ceb2ed10f6038a1cba92111cb', 'df034edb2c12aa7d33b42b20bb1796e3', '180101cfc01c71867b6686207f071eb9', 'f85d450010762a0e1080304286ce30ed', '8840f5439b471aecf991ac6448b826e6', '993901f2d930cc038c406845f08fa082'] combined_imageset_train_txt = dataset_path + '/combined_imageset_train.txt' combined_imageset_val_txt = dataset_path + '/combined_imageset_val.txt' combined_annotations_path = dataset_path + '/combined_annotations' # see get_augmented_pascal_image_annotation_filename_pairs() voc_data_subset_mode = 2 @data_pascal_voc.capture def pascal_voc_files(dataset_path, filenames, dataset_root, urls, md5s): print(dataset_path) print(dataset_root) print(urls) print(filenames) print(md5s) return [dataset_path + filename for filename in filenames] @data_pascal_voc.command def pascal_voc_download(dataset_path, filenames, dataset_root, urls, md5s): zip_paths = pascal_voc_files(dataset_path, filenames, dataset_root, urls, md5s) for url, filename, md5 in zip(urls, filenames, md5s): path = get_file(filename, url, md5_hash=md5, extract=True, cache_subdir=dataset_path) @data_pascal_voc.command def convert_pascal_berkeley_augmented_mat_annotations_to_png(pascal_berkeley_root): pascal_voc.convert_pascal_berkeley_augmented_mat_annotations_to_png(pascal_berkeley_root) @data_pascal_voc.config def cfg_pascal_voc_segmentation_to_tfrecord(dataset_path, filenames, dataset_root): tfrecords_train_filename = dataset_path + '/pascal_augmented_train.tfrecords' tfrecords_val_filename = dataset_path + '/pascal_augmented_val.tfrecords' @data_pascal_voc.command def pascal_voc_berkeley_combined(dataset_path, pascal_root, pascal_berkeley_root, voc_data_subset_mode, combined_imageset_train_txt, combined_imageset_val_txt, combined_annotations_path): # Returns a list of (image, annotation) # filename pairs (filename.jpg, filename.png) overall_train_image_annotation_filename_pairs, \ overall_val_image_annotation_filename_pairs = \ pascal_voc.get_augmented_pascal_image_annotation_filename_pairs( pascal_root=pascal_root, pascal_berkeley_root=pascal_berkeley_root, mode=voc_data_subset_mode) # combine the annotation files into one folder pascal_voc.pascal_combine_annotation_files( overall_train_image_annotation_filename_pairs + overall_val_image_annotation_filename_pairs, combined_annotations_path) # generate the train imageset txt pascal_voc.pascal_filename_pairs_to_imageset_txt( combined_imageset_train_txt, overall_train_image_annotation_filename_pairs ) # generate the val imageset txt pascal_voc.pascal_filename_pairs_to_imageset_txt( combined_imageset_val_txt, overall_val_image_annotation_filename_pairs ) @data_pascal_voc.command def pascal_voc_segmentation_to_tfrecord(dataset_path, pascal_root, pascal_berkeley_root, voc_data_subset_mode, tfrecords_train_filename, tfrecords_val_filename): # Returns a list of (image, annotation) # filename pairs (filename.jpg, filename.png) overall_train_image_annotation_filename_pairs, \ overall_val_image_annotation_filename_pairs = \ pascal_voc.get_augmented_pascal_image_annotation_filename_pairs( pascal_root=pascal_root, pascal_berkeley_root=pascal_berkeley_root, mode=voc_data_subset_mode) # You can create your own tfrecords file by providing # your list with (image, annotation) filename pairs here # # this will create a tfrecord in: # tf_image_segmentation/tf_image_segmentation/recipes/pascal_voc/ write_image_annotation_pairs_to_tfrecord( filename_pairs=overall_val_image_annotation_filename_pairs, tfrecords_filename=tfrecords_val_filename) write_image_annotation_pairs_to_tfrecord( filename_pairs=overall_train_image_annotation_filename_pairs, tfrecords_filename=tfrecords_train_filename) @data_pascal_voc.command def pascal_voc_setup(filenames, dataset_path, pascal_root, pascal_berkeley_root, dataset_root, voc_data_subset_mode, tfrecords_train_filename, tfrecords_val_filename, urls, md5s, combined_imageset_train_txt, combined_imageset_val_txt, combined_annotations_path): # download the dataset pascal_voc_download(dataset_path, filenames, dataset_root, urls, md5s) # convert the relevant files to a more useful format convert_pascal_berkeley_augmented_mat_annotations_to_png( pascal_berkeley_root) pascal_voc_berkeley_combined(dataset_path, pascal_root, pascal_berkeley_root, voc_data_subset_mode, combined_imageset_train_txt, combined_imageset_val_txt, combined_annotations_path) pascal_voc_segmentation_to_tfrecord(dataset_path, pascal_root, pascal_berkeley_root, voc_data_subset_mode, tfrecords_train_filename, tfrecords_val_filename) @data_pascal_voc.automain def main(filenames, dataset_path, pascal_root, pascal_berkeley_root, dataset_root, voc_data_subset_mode, tfrecords_train_filename, tfrecords_val_filename, urls, md5s, combined_imageset_train_txt, combined_imageset_val_txt, combined_annotations_path): voc_config() pascal_voc_setup(filenames, dataset_path, pascal_root, pascal_berkeley_root, dataset_root, voc_data_subset_mode, tfrecords_train_filename, tfrecords_val_filename, urls, md5s, combined_imageset_train_txt, combined_imageset_val_txt, combined_annotations_path)
8,171
0
198
f5236ae02d9cb4b7aa1b4b2f25262d9ce4b65fad
265
py
Python
products/models.py
AironMattos/GS-Labs-Challenge
1f7a97324c559bc3ec764f693d6b2ec838eaeae9
[ "MIT" ]
null
null
null
products/models.py
AironMattos/GS-Labs-Challenge
1f7a97324c559bc3ec764f693d6b2ec838eaeae9
[ "MIT" ]
null
null
null
products/models.py
AironMattos/GS-Labs-Challenge
1f7a97324c559bc3ec764f693d6b2ec838eaeae9
[ "MIT" ]
null
null
null
from django.db import models
26.5
64
0.720755
from django.db import models class Produto(models.Model): nome = models.CharField(max_length=200, blank=False) descricao = models.TextField() valor = models.DecimalField(max_digits=20, decimal_places=2) def __str__(self): return self.nome
22
191
23
c8d40a7145863760b525cbcbc7dbb5513a42ddd1
3,057
py
Python
misc_utility/load_data.py
weber-s/inversionPO
847ef9c8848e28cf09f10918c8c7d9807baecaf8
[ "CC-BY-4.0" ]
null
null
null
misc_utility/load_data.py
weber-s/inversionPO
847ef9c8848e28cf09f10918c8c7d9807baecaf8
[ "CC-BY-4.0" ]
null
null
null
misc_utility/load_data.py
weber-s/inversionPO
847ef9c8848e28cf09f10918c8c7d9807baecaf8
[ "CC-BY-4.0" ]
null
null
null
import matplotlib.pyplot as plt import numpy as np import pandas as pd def load_CHEMorPO(station, inputDir, CHEMorPO="CHEM", fromSource=True): """ Import the concentration file into a DataFrame Parameters ---------- stationName: str, the name of the station inputDir: str, the path of file CHEMorPO: str, {"CHEM","PO"} fromSource: bool, default True whith CHEMorPO == "CHEM", chose if the CHEM file is from source or from raw chemistry. Output ------ df: a panda DataFrame """ if CHEMorPO == "CHEM": if fromSource: nameFile = "_ContributionsMass_positive.csv" else: nameFile = "CHEM_conc.csv" elif CHEMorPO == "PO": nameFile = "PO.csv" else: print("Error: CHEMorPO must be 'CHEM' or 'PO'") return df = pd.read_csv(inputDir+station+"/"+station+nameFile, index_col="date", parse_dates=["date"]) df.name = station return df def setSourcesCategories(df): """ Return the DataFrame df with a renamed columns. The renaming axes set the source's name to its category, i.e Road traffic → Vehicular VEH → Vehicular Secondary bio → Secondary_bio BB → Bio_burning Biomass burning → Bio_burning etc. """ possible_sources ={ "Vehicular": "Vehicular", "VEH": "Vehicular", "VEH ind": "Vehicular_ind", "VEH dir": "Vehicular_dir", "Oil/Vehicular": "Vehicular", "Road traffic": "Vehicular", "Bio. burning": "Bio_burning", "Bio burning": "Bio_burning", "BB": "Bio_burning", "BB1": "Bio_burning1", "BB2": "Bio_burning2", "Sulfate-rich": "Sulfate_rich", "Nitrate-rich": "Nitrate_rich", "Sulfate rich": "Sulfate_rich", "Nitrate rich": "Nitrate_rich", "Secondaire": "Secondary_bio", "Secondary bio": "Secondary_bio", "Secondary biogenic": "Secondary_bio", "Marine biogenic/HFO": "Marine_bio/HFO", "Marine bio/HFO": "Marine_bio/HFO", "Marin bio/HFO": "Marine_bio/HFO", "Marine secondary": "Marine_bio", "Marin secondaire": "Marine_bio", "HFO": "HFO", "Marin": "Marine", "Sea/road salt": "Salt", "Sea salt": "Salt", "Aged sea salt": "Aged_salt", "Aged seasalt": "Aged_salt", "Primary bio": "Primary_bio", "Primary biogenic": "Primary_bio", "Biogenique": "Primary_bio", "Biogenic": "Primary_bio", "Mineral dust": "Dust", "Resuspended dust": "Dust", "Dust": "Dust", "Dust (mineral)": "Dust", "AOS/dust": "Dust", "Industrial": "Industrial", "Industry/vehicular": "Indus._veh.", "Arcellor": "Industrial", "Siderurgie": "Industrial", "Débris végétaux": "Plant_debris", "Chlorure": "Chloride", "PM other": "Other" } return df.rename(columns=possible_sources)
29.394231
79
0.566241
import matplotlib.pyplot as plt import numpy as np import pandas as pd def load_CHEMorPO(station, inputDir, CHEMorPO="CHEM", fromSource=True): """ Import the concentration file into a DataFrame Parameters ---------- stationName: str, the name of the station inputDir: str, the path of file CHEMorPO: str, {"CHEM","PO"} fromSource: bool, default True whith CHEMorPO == "CHEM", chose if the CHEM file is from source or from raw chemistry. Output ------ df: a panda DataFrame """ if CHEMorPO == "CHEM": if fromSource: nameFile = "_ContributionsMass_positive.csv" else: nameFile = "CHEM_conc.csv" elif CHEMorPO == "PO": nameFile = "PO.csv" else: print("Error: CHEMorPO must be 'CHEM' or 'PO'") return df = pd.read_csv(inputDir+station+"/"+station+nameFile, index_col="date", parse_dates=["date"]) df.name = station return df def setSourcesCategories(df): """ Return the DataFrame df with a renamed columns. The renaming axes set the source's name to its category, i.e Road traffic → Vehicular VEH → Vehicular Secondary bio → Secondary_bio BB → Bio_burning Biomass burning → Bio_burning etc. """ possible_sources ={ "Vehicular": "Vehicular", "VEH": "Vehicular", "VEH ind": "Vehicular_ind", "VEH dir": "Vehicular_dir", "Oil/Vehicular": "Vehicular", "Road traffic": "Vehicular", "Bio. burning": "Bio_burning", "Bio burning": "Bio_burning", "BB": "Bio_burning", "BB1": "Bio_burning1", "BB2": "Bio_burning2", "Sulfate-rich": "Sulfate_rich", "Nitrate-rich": "Nitrate_rich", "Sulfate rich": "Sulfate_rich", "Nitrate rich": "Nitrate_rich", "Secondaire": "Secondary_bio", "Secondary bio": "Secondary_bio", "Secondary biogenic": "Secondary_bio", "Marine biogenic/HFO": "Marine_bio/HFO", "Marine bio/HFO": "Marine_bio/HFO", "Marin bio/HFO": "Marine_bio/HFO", "Marine secondary": "Marine_bio", "Marin secondaire": "Marine_bio", "HFO": "HFO", "Marin": "Marine", "Sea/road salt": "Salt", "Sea salt": "Salt", "Aged sea salt": "Aged_salt", "Aged seasalt": "Aged_salt", "Primary bio": "Primary_bio", "Primary biogenic": "Primary_bio", "Biogenique": "Primary_bio", "Biogenic": "Primary_bio", "Mineral dust": "Dust", "Resuspended dust": "Dust", "Dust": "Dust", "Dust (mineral)": "Dust", "AOS/dust": "Dust", "Industrial": "Industrial", "Industry/vehicular": "Indus._veh.", "Arcellor": "Industrial", "Siderurgie": "Industrial", "Débris végétaux": "Plant_debris", "Chlorure": "Chloride", "PM other": "Other" } return df.rename(columns=possible_sources)
0
0
0
411adb10e149c599353d4b19f3f8c772ee597133
3,976
py
Python
bayesian_lifetimes/estimator.py
nebw/bb_bayesian_lifetimes
b6242eed666ab4f0546c1fd804a6867eb5f28ad8
[ "MIT" ]
null
null
null
bayesian_lifetimes/estimator.py
nebw/bb_bayesian_lifetimes
b6242eed666ab4f0546c1fd804a6867eb5f28ad8
[ "MIT" ]
null
null
null
bayesian_lifetimes/estimator.py
nebw/bb_bayesian_lifetimes
b6242eed666ab4f0546c1fd804a6867eb5f28ad8
[ "MIT" ]
null
null
null
import datetime import numpy as np import pandas as pd import pymc3 as pm import scipy import scipy.stats from bb_utils.ids import BeesbookID from bb_utils.meta import BeeMetaInfo
34.877193
89
0.632294
import datetime import numpy as np import pandas as pd import pymc3 as pm import scipy import scipy.stats from bb_utils.ids import BeesbookID from bb_utils.meta import BeeMetaInfo class LifetimeEstimator: mu_days_alive = 21 sigma_days_alive = 25 p_tagged = 0.75 def __init__( self, min_doy=201, max_doy=263, pad_days_after=40, use_tagged_date=True, min_detections=np.expm1(8), max_detections=np.expm1(12), dead_rate_beta=25, p_hatchdates=None, ): self.min_doy = min_doy self.max_doy = max_doy + pad_days_after self.pad_days_after = pad_days_after self.min_detections = min_detections self.max_detections = max_detections self.dead_rate_beta = dead_rate_beta all_doys = np.arange(self.min_doy, self.max_doy).astype(np.float) self.all_doys = pd.DataFrame(all_doys, columns=["doy"]) self.use_tagged_date = use_tagged_date if use_tagged_date: self.meta = BeeMetaInfo() self.p_hatchdates = p_hatchdates def fit(self, bee_id, bee_detections, num_tune=1000, num_draws=1000, progress=False): bee_detections = bee_detections.merge(self.all_doys, how="outer") bee_detections.fillna(0, inplace=True) bee_detections.sort_values("doy", inplace=True) bee_detections.bee_id = bee_id num_detections = bee_detections["count"].values num_detections -= self.min_detections num_detections = np.clip(num_detections, 0, self.max_detections) num_detections = num_detections / self.max_detections days = np.array(list(range(num_detections.shape[0]))).astype(np.float64) num_detections = num_detections.astype(np.float32) if self.use_tagged_date: hatchdate = self.meta.get_hatchdate(BeesbookID.from_ferwar(bee_id)) tagged_doy = (hatchdate - datetime.datetime(hatchdate.year, 1, 1)).days tagged_dor = tagged_doy - self.min_doy + 1 tagged_day = np.clip(tagged_dor, 0, np.inf) tagged_day_unclipped = tagged_dor num_days_clipped = np.abs(tagged_day - tagged_day_unclipped) if np.isnan(tagged_day): return None else: num_days_clipped = 0 model = pm.Model() with model: p_emergence = np.ones(len(days)) p_emergence[-self.pad_days_after :] = 0.0 if self.p_hatchdates is not None: p_emergence *= 0.001 p_emergence[list(map(int, self.p_hatchdates))] = 1.0 p_emergence /= p_emergence.sum() if self.use_tagged_date: p_emergence[int(tagged_day)] = self.p_tagged p_emergence /= p_emergence.sum() p_days_alive = scipy.stats.norm.pdf( np.arange(0, len(days)), self.mu_days_alive, self.sigma_days_alive ) p_days_alive /= p_days_alive.sum() switchpoint_emerged = pm.Categorical("switchpoint_emerged", p=p_emergence) days_alive = pm.Categorical("days_alive", p=p_days_alive) switchpoint_died = pm.Deterministic( "switchpoint_died", switchpoint_emerged + days_alive - num_days_clipped ) threshold = pm.Beta("dead_rate", alpha=1, beta=self.dead_rate_beta) probability_higher = pm.Beta("probability_higher", alpha=5, beta=1) probability_lower = pm.Beta("probability_lower", alpha=1, beta=5) rate = pm.math.switch( (days >= switchpoint_emerged) & (days <= switchpoint_died), probability_higher, probability_lower, ) _ = pm.Bernoulli("detections", rate, observed=num_detections > threshold) trace = pm.sample(tune=num_tune, draws=num_draws, progressbar=progress) return model, trace, num_detections
3,644
126
23
0857ae9c6890ce3f361d3dc6166a8e14c0626f05
1,462
py
Python
bench/scribble_plotting.py
histocartography/athena
8a1af389dc936bf5b8e62c56ae682a2fe4d2d71a
[ "BSD-3-Clause" ]
9
2021-12-07T07:08:55.000Z
2022-03-24T13:40:51.000Z
bench/scribble_plotting.py
histocartography/athena
8a1af389dc936bf5b8e62c56ae682a2fe4d2d71a
[ "BSD-3-Clause" ]
null
null
null
bench/scribble_plotting.py
histocartography/athena
8a1af389dc936bf5b8e62c56ae682a2fe4d2d71a
[ "BSD-3-Clause" ]
2
2021-10-08T07:11:13.000Z
2022-02-02T18:52:52.000Z
import spatialHeterogeneity as sh import pickle as pk import os import matplotlib.pyplot as plt hdf = '/Users/art/Documents/spatial-omics/spatialOmics.hdf5' f = '/Users/art/Documents/spatial-omics/spatialOmics.pkl' # so = SpatialOmics.form_h5py(f) with open(f, 'rb') as f: so = pk.load(f) # with open(f, 'wb') as file: # pk.dump(so, file) so.h5py_file = hdf so.spl_keys = list(so.X.keys()) spl = so.spl_keys[0] sh.pl.spatial(so,spl, 'meta_id') sh.pl.spatial(so,spl, 'meta_id', mode='mask') fig, ax = plt.subplots() sh.pl.spatial(so,spl, 'meta_id', mode='mask', ax=ax) fig.show() sh.pl.spatial(so,spl, 'EGFR') sh.pl.spatial(so,spl, 'EGFR', mode='mask') sh.pl.spatial(so,spl, 'meta_id', edges=True) sh.pl.spatial(so,spl, 'meta_id', mode='mask', edges=True) # %% sh.pl.napari_viewer(so, spl, ['DNA2', 'EGFR', 'H3'], add_masks='cellmask') #%% import numpy as np import napari from skimage import data viewer = napari.view_image(data.astronaut(), rgb=True) img = [so.images[spl][i,...] for i in [8,39]] a0 = np.stack(img, axis=0) a2 = np.stack(img, axis=2) img = so.images[spl][[8,39]] mask = so.masks[spl]['cellmask'] viewer = napari.view_image(img[0,], name='adsf') labels_layer = viewer.add_labels(mask, name='assd') viewer = napari.Viewer() viewer.add_image(img, channel_axis=0, name=['Ich', 'Du']) labels_layer = viewer.add_labels(mask, name='assd') with napari.gui_qt(): viewer = napari.Viewer() viewer.add_image(data.astronaut())
25.206897
74
0.684679
import spatialHeterogeneity as sh import pickle as pk import os import matplotlib.pyplot as plt hdf = '/Users/art/Documents/spatial-omics/spatialOmics.hdf5' f = '/Users/art/Documents/spatial-omics/spatialOmics.pkl' # so = SpatialOmics.form_h5py(f) with open(f, 'rb') as f: so = pk.load(f) # with open(f, 'wb') as file: # pk.dump(so, file) so.h5py_file = hdf so.spl_keys = list(so.X.keys()) spl = so.spl_keys[0] sh.pl.spatial(so,spl, 'meta_id') sh.pl.spatial(so,spl, 'meta_id', mode='mask') fig, ax = plt.subplots() sh.pl.spatial(so,spl, 'meta_id', mode='mask', ax=ax) fig.show() sh.pl.spatial(so,spl, 'EGFR') sh.pl.spatial(so,spl, 'EGFR', mode='mask') sh.pl.spatial(so,spl, 'meta_id', edges=True) sh.pl.spatial(so,spl, 'meta_id', mode='mask', edges=True) # %% sh.pl.napari_viewer(so, spl, ['DNA2', 'EGFR', 'H3'], add_masks='cellmask') #%% import numpy as np import napari from skimage import data viewer = napari.view_image(data.astronaut(), rgb=True) img = [so.images[spl][i,...] for i in [8,39]] a0 = np.stack(img, axis=0) a2 = np.stack(img, axis=2) img = so.images[spl][[8,39]] mask = so.masks[spl]['cellmask'] viewer = napari.view_image(img[0,], name='adsf') labels_layer = viewer.add_labels(mask, name='assd') viewer = napari.Viewer() viewer.add_image(img, channel_axis=0, name=['Ich', 'Du']) labels_layer = viewer.add_labels(mask, name='assd') with napari.gui_qt(): viewer = napari.Viewer() viewer.add_image(data.astronaut())
0
0
0
a63ff270678d7b5bebf7431b19aa3171dd6b6531
76
py
Python
tests/inline_test_resources/11/script.py
thesynman/pybricksdev
6f34cfb7a5f26628fe3cedae1ce51ee6024f57b9
[ "MIT" ]
null
null
null
tests/inline_test_resources/11/script.py
thesynman/pybricksdev
6f34cfb7a5f26628fe3cedae1ce51ee6024f57b9
[ "MIT" ]
null
null
null
tests/inline_test_resources/11/script.py
thesynman/pybricksdev
6f34cfb7a5f26628fe3cedae1ce51ee6024f57b9
[ "MIT" ]
null
null
null
import importA my_drive = importA.HasConstants(importA.HasConstants.DRIVE)
19
59
0.842105
import importA my_drive = importA.HasConstants(importA.HasConstants.DRIVE)
0
0
0
5dd8045a94410c34e269d958145e1d76c296450c
7,147
py
Python
Tests/test_SeqUtils.py
rht/biopython
3a44496d7bd79446266a4951b7d1f64569e4a96d
[ "BSD-3-Clause" ]
3
2016-11-21T09:55:56.000Z
2019-04-09T17:39:43.000Z
Tests/test_SeqUtils.py
rht/biopython
3a44496d7bd79446266a4951b7d1f64569e4a96d
[ "BSD-3-Clause" ]
32
2016-11-21T07:38:21.000Z
2017-08-16T13:00:03.000Z
Tests/test_SeqUtils.py
rht/biopython
3a44496d7bd79446266a4951b7d1f64569e4a96d
[ "BSD-3-Clause" ]
8
2016-11-24T18:57:35.000Z
2022-01-16T08:15:25.000Z
# Copyright 2007-2009 by Peter Cock. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. import os import unittest from Bio import SeqIO from Bio.Alphabet import single_letter_alphabet from Bio.Seq import Seq, MutableSeq from Bio.SeqRecord import SeqRecord from Bio.SeqUtils import GC, seq1, seq3, GC_skew from Bio.SeqUtils.lcc import lcc_simp, lcc_mult from Bio.SeqUtils.CheckSum import crc32, crc64, gcg, seguid from Bio.SeqUtils.CodonUsage import CodonAdaptationIndex if __name__ == "__main__": runner = unittest.TextTestRunner(verbosity=2) unittest.main(testRunner=runner)
44.949686
112
0.612285
# Copyright 2007-2009 by Peter Cock. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. import os import unittest from Bio import SeqIO from Bio.Alphabet import single_letter_alphabet from Bio.Seq import Seq, MutableSeq from Bio.SeqRecord import SeqRecord from Bio.SeqUtils import GC, seq1, seq3, GC_skew from Bio.SeqUtils.lcc import lcc_simp, lcc_mult from Bio.SeqUtils.CheckSum import crc32, crc64, gcg, seguid from Bio.SeqUtils.CodonUsage import CodonAdaptationIndex def u_crc32(seq): # NOTE - On Python 2 crc32 could return a signed int, but on Python 3 it is # always unsigned # Docs suggest should use crc32(x) & 0xffffffff for consistency. return crc32(seq) & 0xffffffff def simple_LCC(s): # Avoid cross platforms with printing floats by doing conversion explicitly return "%0.2f" % lcc_simp(s) def windowed_LCC(s): return ", ".join("%0.2f" % v for v in lcc_mult(s, 20)) class SeqUtilsTests(unittest.TestCase): def setUp(self): # Example of crc64 collision from Sebastian Bassi using the # immunoglobulin lambda light chain variable region from Homo sapiens # Both sequences share the same CRC64 checksum: 44CAAD88706CC153 self.str_light_chain_one = "QSALTQPASVSGSPGQSITISCTGTSSDVGSYNLVSWYQQHPGK" \ + "APKLMIYEGSKRPSGVSNRFSGSKSGNTASLTISGLQAEDEADY" \ + "YCSSYAGSSTLVFGGGTKLTVL" self.str_light_chain_two = "QSALTQPASVSGSPGQSITISCTGTSSDVGSYNLVSWYQQHPGK" \ + "APKLMIYEGSKRPSGVSNRFSGSKSGNTASLTISGLQAEDEADY" \ + "YCCSYAGSSTWVFGGGTKLTVL" def test_codon_usage_ecoli(self): """Test Codon Adaptation Index (CAI) using default E. coli data.""" CAI = CodonAdaptationIndex() self.assertEqual("%0.5f" % CAI.cai_for_gene("ATGCGTATCGATCGCGATACGATTAGGCGGATG"), "0.09978") def test_codon_usage_custom(self): """Test Codon Adaptation Index (CAI) using FASTA file for background.""" # We need a FASTA file of CDS sequences to count the codon usage... dna_fasta_filename = "fasta.tmp" dna_genbank_filename = "GenBank/NC_005816.gb" record = SeqIO.read(dna_genbank_filename, "genbank") records = [] for feature in record.features: if feature.type == "CDS" and len(feature.location.parts) == 1: start = feature.location.start.position end = feature.location.end.position table = int(feature.qualifiers["transl_table"][0]) if feature.strand == -1: seq = record.seq[start:end].reverse_complement() else: seq = record.seq[start:end] # Double check we have the CDS sequence expected # TODO - Use any cds_start option if/when added to deal with the met a = "M" + str(seq[3:].translate(table)) b = feature.qualifiers["translation"][0] + "*" self.assertEqual(a, b, "%r vs %r" % (a, b)) records.append(SeqRecord(seq, id=feature.qualifiers["protein_id"][0], description=feature.qualifiers["product"][0])) with open(dna_fasta_filename, "w") as handle: SeqIO.write(records, handle, "fasta") CAI = CodonAdaptationIndex() # Note - this needs a FASTA file which containing non-ambiguous DNA coding # sequences - which should each be a whole number of codons. CAI.generate_index(dna_fasta_filename) # Now check codon usage index (CAI) using this species self.assertEqual(record.annotations["source"], "Yersinia pestis biovar Microtus str. 91001") self.assertEqual("%0.5f" % CAI.cai_for_gene("ATGCGTATCGATCGCGATACGATTAGGCGGATG"), "0.67213") os.remove(dna_fasta_filename) def test_crc_checksum_collision(self): # Explicit testing of crc64 collision: self.assertNotEqual(self.str_light_chain_one, self.str_light_chain_two) self.assertNotEqual(crc32(self.str_light_chain_one), crc32(self.str_light_chain_two)) self.assertEqual(crc64(self.str_light_chain_one), crc64(self.str_light_chain_two)) self.assertNotEqual(gcg(self.str_light_chain_one), gcg(self.str_light_chain_two)) self.assertNotEqual(seguid(self.str_light_chain_one), seguid(self.str_light_chain_two)) def seq_checksums(self, seq_str, exp_crc32, exp_crc64, exp_gcg, exp_seguid, exp_simple_LCC, exp_window_LCC): for s in [seq_str, Seq(seq_str, single_letter_alphabet), MutableSeq(seq_str, single_letter_alphabet)]: self.assertEqual(exp_crc32, u_crc32(s)) self.assertEqual(exp_crc64, crc64(s)) self.assertEqual(exp_gcg, gcg(s)) self.assertEqual(exp_seguid, seguid(s)) self.assertEqual(exp_simple_LCC, simple_LCC(s)) self.assertEqual(exp_window_LCC, windowed_LCC(s)) def test_checksum1(self): self.seq_checksums(self.str_light_chain_one, 2994980265, "CRC-44CAAD88706CC153", 9729, "BpBeDdcNUYNsdk46JoJdw7Pd3BI", "1.03", "0.00, 1.00, 0.96, 0.96, 0.96, 0.65, 0.43, 0.35, 0.35, 0.35, 0.35, 0.53, 0.59, 0.26") def test_checksum2(self): self.seq_checksums(self.str_light_chain_two, 802105214, "CRC-44CAAD88706CC153", 9647, "X5XEaayob1nZLOc7eVT9qyczarY", "1.07", "0.00, 1.00, 0.96, 0.96, 0.96, 0.65, 0.43, 0.35, 0.35, 0.35, 0.35, 0.53, 0.59, 0.26") def test_checksum3(self): self.seq_checksums("ATGCGTATCGATCGCGATACGATTAGGCGGAT", 817679856, "CRC-6234FF451DC6DFC6", 7959, "8WCUbVjBgiRmM10gfR7XJNjbwnE", "1.98", "0.00, 2.00, 1.99, 1.99, 2.00, 1.99, 1.97, 1.99, 1.99, 1.99, 1.96, 1.96, 1.96, 1.96") def test_GC(self): seq = "ACGGGCTACCGTATAGGCAAGAGATGATGCCC" self.assertEqual(GC(seq), 56.25) def test_GC_skew(self): seq = "A" * 50 self.assertEqual(GC_skew(seq)[0], 0) def test_seq1_seq3(self): s3 = "MetAlaTyrtrpcysthrLYSLEUILEGlYPrOGlNaSnaLapRoTyRLySSeRHisTrpLysThr" s1 = "MAYWCTKLIGPQNAPYKSHWKT" self.assertEqual(seq1(s3), s1) self.assertEqual(seq3(s1).upper(), s3.upper()) self.assertEqual(seq1(seq3(s1)), s1) self.assertEqual(seq3(seq1(s3)).upper(), s3.upper()) if __name__ == "__main__": runner = unittest.TextTestRunner(verbosity=2) unittest.main(testRunner=runner)
3,744
2,580
92
3b8e3601dc4d695e8301e5b36e46da78b13f753b
756
py
Python
tests/workflow/plot.py
BavYeti/bbfsa
42023bd4823f4215f670a1924595cbde20e0cf21
[ "MIT" ]
null
null
null
tests/workflow/plot.py
BavYeti/bbfsa
42023bd4823f4215f670a1924595cbde20e0cf21
[ "MIT" ]
null
null
null
tests/workflow/plot.py
BavYeti/bbfsa
42023bd4823f4215f670a1924595cbde20e0cf21
[ "MIT" ]
null
null
null
import numpy as np import matplotlib.pyplot as plt import pandas as pd from context import bbfsa #read csv file spectra = pd.read_csv('./tests/workflow/input/700cow.csv', delimiter=',', names= ['wn', 'ab']) # cristallinity index s = bbfsa.slice(spectra,700,400) #slice for baseline b = bbfsa.baseline(s) #baseline s2 = bbfsa.slice(b,620,530) #slice for peak picking pp = bbfsa.peakpickMin (s2) #needs test if 2 values pn = bbfsa.peakpickMin (s2) #needs test if 1 value #nearest peak NV = pp['ab'].where (pp['a'].abs(500)==min(pp['a'].abs(500))) print (NV) plotmeX = s2.wn plotmeY = s2.ab plt.plot(plotmeX, plotmeY) plt.plot(pp.wn, pp.ab,'ro') plt.xlim(max(plotmeX)+100, min(plotmeX)-100) plt.ylim(min(plotmeY), max(plotmeY)+0.1) #plt.show()
22.235294
94
0.695767
import numpy as np import matplotlib.pyplot as plt import pandas as pd from context import bbfsa #read csv file spectra = pd.read_csv('./tests/workflow/input/700cow.csv', delimiter=',', names= ['wn', 'ab']) # cristallinity index s = bbfsa.slice(spectra,700,400) #slice for baseline b = bbfsa.baseline(s) #baseline s2 = bbfsa.slice(b,620,530) #slice for peak picking pp = bbfsa.peakpickMin (s2) #needs test if 2 values pn = bbfsa.peakpickMin (s2) #needs test if 1 value #nearest peak NV = pp['ab'].where (pp['a'].abs(500)==min(pp['a'].abs(500))) print (NV) plotmeX = s2.wn plotmeY = s2.ab plt.plot(plotmeX, plotmeY) plt.plot(pp.wn, pp.ab,'ro') plt.xlim(max(plotmeX)+100, min(plotmeX)-100) plt.ylim(min(plotmeY), max(plotmeY)+0.1) #plt.show()
0
0
0
b0a755cc52ef03572fc7257db25c3dc683e3cb2b
2,383
py
Python
hodgepodge/hashing.py
whitfieldsdad/hodgepodge
cf023179c30ae84641f1f8863749e8325df9811e
[ "MIT" ]
1
2021-09-15T17:27:15.000Z
2021-09-15T17:27:15.000Z
hodgepodge/hashing.py
whitfieldsdad/hodgepodge
cf023179c30ae84641f1f8863749e8325df9811e
[ "MIT" ]
null
null
null
hodgepodge/hashing.py
whitfieldsdad/hodgepodge
cf023179c30ae84641f1f8863749e8325df9811e
[ "MIT" ]
null
null
null
from typing import Callable, Optional, Union from dataclasses import dataclass import hashlib import hodgepodge.types from hodgepodge.serialization import Serializable DEFAULT_FILE_IO_BLOCK_SIZE = 8192 MD5 = 'md5' SHA1 = 'sha1' SHA256 = 'sha256' SHA512 = 'sha512' HASH_ALGORITHMS = [MD5, SHA1, SHA256, SHA512] @dataclass(frozen=True) @dataclass(frozen=True)
24.56701
87
0.668065
from typing import Callable, Optional, Union from dataclasses import dataclass import hashlib import hodgepodge.types from hodgepodge.serialization import Serializable DEFAULT_FILE_IO_BLOCK_SIZE = 8192 MD5 = 'md5' SHA1 = 'sha1' SHA256 = 'sha256' SHA512 = 'sha512' HASH_ALGORITHMS = [MD5, SHA1, SHA256, SHA512] @dataclass(frozen=True) class Hashes(Serializable): md5: Optional[str] sha1: Optional[str] sha256: Optional[str] sha512: Optional[str] @dataclass(frozen=True) class _HashlibWrapper: name: str update: Callable[[bytes], None] get_hex_digest: Callable[[], str] def _get_hashlib_wrapper(f) -> _HashlibWrapper: return _HashlibWrapper( name=f.name, update=f.update, get_hex_digest=f.hexdigest, ) def _get_hex_digest_via_hashlib(f, data: Union[str, bytes]) -> str: if isinstance(data, str): data = hodgepodge.types.str_to_bytes(data) h = _get_hashlib_wrapper(f) h.update(data) return h.get_hex_digest() def get_md5(data: Union[str, bytes]) -> str: return _get_hex_digest_via_hashlib(hashlib.md5(), data=data) def get_sha1(data: Union[str, bytes]) -> str: return _get_hex_digest_via_hashlib(hashlib.sha1(), data=data) def get_sha256(data: Union[str, bytes]) -> str: return _get_hex_digest_via_hashlib(hashlib.sha256(), data=data) def get_sha512(data: Union[str, bytes]) -> str: return _get_hex_digest_via_hashlib(hashlib.sha512(), data=data) def get_hashes(data: Union[str, bytes]) -> Hashes: if isinstance(data, str): data = hodgepodge.types.str_to_bytes(data) return Hashes( md5=get_md5(data), sha1=get_sha1(data), sha256=get_sha256(data), sha512=get_sha512(data), ) def get_file_hashes(path: str, block_size: int = DEFAULT_FILE_IO_BLOCK_SIZE) -> Hashes: hashes = { MD5: _get_hashlib_wrapper(hashlib.md5()), SHA1: _get_hashlib_wrapper(hashlib.sha1()), SHA256: _get_hashlib_wrapper(hashlib.sha256()), SHA512: _get_hashlib_wrapper(hashlib.sha512()), } with open(path, 'rb') as fp: while True: data = fp.read(block_size) if not data: break for h in hashes.values(): h.update(data) for (k, h) in hashes.items(): hashes[k] = h.get_hex_digest() return Hashes(**hashes)
1,587
194
228
3bbb20d2e61b3010e3dd21f721a9ae2fe38ebd6e
11,699
py
Python
main.py
srogers47/Trulia-Web-Scraper
18d8472a765aba8580ae878aa73582f3f00a9860
[ "MIT" ]
null
null
null
main.py
srogers47/Trulia-Web-Scraper
18d8472a765aba8580ae878aa73582f3f00a9860
[ "MIT" ]
null
null
null
main.py
srogers47/Trulia-Web-Scraper
18d8472a765aba8580ae878aa73582f3f00a9860
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Web client, html parsing import aiohttp from lxml import html from bs4 import BeautifulSoup as BS # Web driver, browser/network interaction from seleniumwire import webdriver from selenium.webdriver.firefox.options import Options # Downloading, compressing images from PIL import Image import numpy as np from numpy import asarray import blosc #PYMONGO import asyncio import gzip import os import re from random import randint from subprocess import run import time class Main: """ Source property data from trulia real estate. Main.dispatch() controls the execution of tasks at a high level. functions called through dispatch() will comprise of multiple enclosures to optimize refactorability. """ base_url = "https://www.trulia.com/" # Gather grab cookies and headers for requests sitemap = "https://www.trulia.com/sitemaps/xml/p/index.xml" #XML list of gz compressed urls for all properties. urls = [] # Empty placeholder for urls image_requests = [] # Placeholder for urls to static images pages_visited = 0 # Placeholder. Every 50 pages visited call switch proxy sleep_time = randint(1,5) # Randomized sleep/wait. Increase range for slower but sneakier crawl. proxy_wait_time = randint(3,5) # Give expressvpn time to connect to a different relay. async def fetch_urls(self, session, gzip_url) -> list: """ Fetch listings wrapper. Uses nested functions as there is room to implement more control flows in pipeline. For example extracting urls from rental-properties sitemap. """ async def load_in_urls(filename) -> dict: """ Read streamed gzip files from local dir. Cannot be done on the fly. Yield a dict {filename: lines} """ with gzip.open(filename, 'rb') as f: xml_content = f.readlines() await self.parse_xml(str(xml_content)) print(f"{len(self.urls)} urls extracted. \n {self.urls}") async def prep_fetch() -> str: """ Get urls to listings. Stream gzip compressed files and write to local dir. """ async with session.get(gzip_url) as resp: chunk_size = 10 # Set chunk for streaming # Name files based on url basename filename = "./urls/" + str(os.path.basename(gzip_url)) # .strip(".gz")) print(filename) # Debug with open(filename, 'wb') as fd: # Save in urls dir while True: #Stream to files chunk = await resp.content.read(chunk_size) if not chunk: break fd.write(chunk) # Write print(f"File {filename} has been saved to urls/") await load_in_urls(filename) # Call helper to extract/load urls await prep_fetch() async def extract_listing(self, session, listing_url) -> dict: """ Extract data from listings. """ # Track pages visted and switch proxies/vpn relay every 50 pages. self.pages_visited += 1 if self.pages_visited % 50 == 0: switch_proxy() # Blocking call to prevent dns leak during rotation. def switch_proxy(): #NOTE: Blocking call all requests will halt until new relay connection. """ For dev testing purposes. This function will be refactored as a script imported via docker-compose. Run vpn_routing.sh to interact with expressvpn CLI. All outbound requests will pause during this transition. """ # Vpn aliases vpn_aliases = ["hk2", "usny","uswd", "usse", "usda2", "usda", "usla", "ussf", "sgju","in","cato","camo","defr1","ukdo","uklo","nlam","nlam2", "esba","mx","ch2","frpa1","itmi"] # Randomize rotation. random_alias = dict(enumerate(vpn_aliases))[randint(0, int(len(vpn_aliases)))] # Run the vpn_routing script pass in the alias run(["./vpn_routing.sh", f"{random_alias}"]) time.sleep(self.proxy_wait_time) # Give expressvpn time to connect async def interceptor() -> list: """ Intercepts and modifies requests on the fly. View network requests for api data and static imageset urls. Return a list of request urls' to thumbnail imagesets of listing. """ # Concatenate this str to url to view modal lightbox triggering imageset of thumbnails to load (Fetched from graphql api). modal_box = "?mid=0#lil-mediaTab" # Replace '-mediaTab' for different requests/data ie '-crime' returns requests to api for crime stats/rate. async with driver.get(str(listing_url) + str(modal_box)) as response: # Load modal and imageset requests with 'response' _requests = await response.requests # List of requests. Parse for imagset urls. requests = re.find_all(_requests, ("/pictures/thumbs_5/zillowstatic")) # Parse list of network connections for thumbnail image urls. self.image_requests.append(requests) async def download_images(): """ Download images from trulia listings and insert into mongodb. Note that the images are compressed bianries. """ async with session.get(image_request) as resp: # Output of resp image will be binary, No need to compress again. #TODO Use blosc to put binary into array for MongoClient insert. _image = await resp #compressed_image = Image.from #TODO pass # TODO INSERT DATA async def parse_html() -> dict: """ Provided html, parse for data points. Need to use xpath as classnames are dynamically generated/change frequently. """ # xpaths to data points. These will most likely change which sucks. temp_sale_tag = "/html/body/div[2]/div[2]/div/div[2]/div[1]/div/div/div[2]/div[1]/span/text()" temp_address = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div[1]/div[1]/h1/span[1]/text()" temp_state_zip = " /html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div[1]/div[1]/h1/span[2]/text()" temp_price = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div[2]/div/h3/div/text()" temp_beds = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div[2]/div/h3/div/text()" temp_baths = " /html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div[1]/div[2]/div[1]/div/ul/li[2]/div/div/text()" temp_sqft = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div[1]/div[2]/div[1]/div/ul/li[3]/div/div/text()" temp_hoa_fee = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[4]/div[2]/div/div[4]/div/div/div[3]text()" temp_heating = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[4]/div[2]/div/div[5]/div/div/div[3]/text()" temp_cooling = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[4]/div[2]/div/div[6]/div/div/div[3]/text()" temp_description = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[4]/div[2]/div/text()" # Use lxml to parse xpath from soup. tree = html.fromstring(html_content) # Create element tree. sale_tag = tree.xpath(temp_sale_tag) address = tree.xpath(temp_address) state_zip = tree.xpath(temp_state_zip) price = tree.xpath(temp_price) beds = tree.xpath(temp_beds) baths = tree.xpath(temp_baths) sqft = tree.xpath(temp_sqft) hoa_fee = tree.xpath(temp_hoa_fee) heating = tree.xpath(temp_heating) cooling = tree.xpath(temp_cooling) description = tree.xpath(temp_descrption) # Extract Listings # Initiate webdriver. options = Options() options.headless = True driver = webdriver.Firefox(options=options,executable_path=r"geckodriver") # Make sure the driver is an exe. Intended to be run in linux vm. # Get listing response async with session.get(listing_url) as resp: html_content = resp.text() await asyncio.sleep(self.sleep_time) # Sleep a few second between every request. Be nice to the trulia graphql api backend! await html_content datapoints = await parse_html() # Get listing images' urls with webdriver imageset_requests = await interceptor() # Call interceptor. Aggregates all requests for property images. images_task = [download_images() for image_url in imageset_requests] get_images = await asyncio.gather(*images_task) # Load into DB async def parse_xml(self, xml_content) -> list: """Return a list of urls from sitemaps' xml content""" urls = [] #Temp storage in mem soup = BS(xml_content, "lxml") # Pass xml content and parser into soup for url in soup.find_all('loc'): urls.append(url.get_text()) self.urls = urls assert len(self.urls) > 10 # We should have way more. Better end to end testing will be implemented in the store_data.py module. ' async def dispatch(self, loop) -> dict: """ Init ClientSession(). Dispatch urls to unzip/decompress. Return dict of all datapoints including status of db insert:Bool. """ # headers headers = ({'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36', 'Accept-Language': 'en-US, en;q=0.5'}) # Wrap method calls in ClientSession() context manager. async with aiohttp.ClientSession(loop=loop) as session: # Get xml page containg urls to active property sitemaps async with session.get(self.sitemap) as resp: xml_content = await resp.text() await self.parse_xml(xml_content) print(f"Collected {len(self.urls)} urls. \n {self.urls}") assert len(self.urls) > 10 # Fetch Listing sitemaps. Extract/Read gzip urls to file tasks = [self.fetch_urls(session, gzip_url) for gzip_url in self.urls] results = asyncio.gather(*tasks) await results # Fetch Extracted listing urls & parse html tasks = [self.extract_listing(session, listing_url, random_alias) for listing_url in self.urls] results = asyncio.gather(*tasks) await results if __name__ == '__main__': m = Main() loop = asyncio.get_event_loop() results = loop.run_until_complete(m.dispatch(loop))
45.878431
153
0.600393
#!/usr/bin/env python3 # Web client, html parsing import aiohttp from lxml import html from bs4 import BeautifulSoup as BS # Web driver, browser/network interaction from seleniumwire import webdriver from selenium.webdriver.firefox.options import Options # Downloading, compressing images from PIL import Image import numpy as np from numpy import asarray import blosc #PYMONGO import asyncio import gzip import os import re from random import randint from subprocess import run import time class Main: """ Source property data from trulia real estate. Main.dispatch() controls the execution of tasks at a high level. functions called through dispatch() will comprise of multiple enclosures to optimize refactorability. """ base_url = "https://www.trulia.com/" # Gather grab cookies and headers for requests sitemap = "https://www.trulia.com/sitemaps/xml/p/index.xml" #XML list of gz compressed urls for all properties. urls = [] # Empty placeholder for urls image_requests = [] # Placeholder for urls to static images pages_visited = 0 # Placeholder. Every 50 pages visited call switch proxy sleep_time = randint(1,5) # Randomized sleep/wait. Increase range for slower but sneakier crawl. proxy_wait_time = randint(3,5) # Give expressvpn time to connect to a different relay. async def fetch_urls(self, session, gzip_url) -> list: """ Fetch listings wrapper. Uses nested functions as there is room to implement more control flows in pipeline. For example extracting urls from rental-properties sitemap. """ async def load_in_urls(filename) -> dict: """ Read streamed gzip files from local dir. Cannot be done on the fly. Yield a dict {filename: lines} """ with gzip.open(filename, 'rb') as f: xml_content = f.readlines() await self.parse_xml(str(xml_content)) print(f"{len(self.urls)} urls extracted. \n {self.urls}") async def prep_fetch() -> str: """ Get urls to listings. Stream gzip compressed files and write to local dir. """ async with session.get(gzip_url) as resp: chunk_size = 10 # Set chunk for streaming # Name files based on url basename filename = "./urls/" + str(os.path.basename(gzip_url)) # .strip(".gz")) print(filename) # Debug with open(filename, 'wb') as fd: # Save in urls dir while True: #Stream to files chunk = await resp.content.read(chunk_size) if not chunk: break fd.write(chunk) # Write print(f"File {filename} has been saved to urls/") await load_in_urls(filename) # Call helper to extract/load urls await prep_fetch() async def extract_listing(self, session, listing_url) -> dict: """ Extract data from listings. """ # Track pages visted and switch proxies/vpn relay every 50 pages. self.pages_visited += 1 if self.pages_visited % 50 == 0: switch_proxy() # Blocking call to prevent dns leak during rotation. def switch_proxy(): #NOTE: Blocking call all requests will halt until new relay connection. """ For dev testing purposes. This function will be refactored as a script imported via docker-compose. Run vpn_routing.sh to interact with expressvpn CLI. All outbound requests will pause during this transition. """ # Vpn aliases vpn_aliases = ["hk2", "usny","uswd", "usse", "usda2", "usda", "usla", "ussf", "sgju","in","cato","camo","defr1","ukdo","uklo","nlam","nlam2", "esba","mx","ch2","frpa1","itmi"] # Randomize rotation. random_alias = dict(enumerate(vpn_aliases))[randint(0, int(len(vpn_aliases)))] # Run the vpn_routing script pass in the alias run(["./vpn_routing.sh", f"{random_alias}"]) time.sleep(self.proxy_wait_time) # Give expressvpn time to connect async def interceptor() -> list: """ Intercepts and modifies requests on the fly. View network requests for api data and static imageset urls. Return a list of request urls' to thumbnail imagesets of listing. """ # Concatenate this str to url to view modal lightbox triggering imageset of thumbnails to load (Fetched from graphql api). modal_box = "?mid=0#lil-mediaTab" # Replace '-mediaTab' for different requests/data ie '-crime' returns requests to api for crime stats/rate. async with driver.get(str(listing_url) + str(modal_box)) as response: # Load modal and imageset requests with 'response' _requests = await response.requests # List of requests. Parse for imagset urls. requests = re.find_all(_requests, ("/pictures/thumbs_5/zillowstatic")) # Parse list of network connections for thumbnail image urls. self.image_requests.append(requests) async def download_images(): """ Download images from trulia listings and insert into mongodb. Note that the images are compressed bianries. """ async with session.get(image_request) as resp: # Output of resp image will be binary, No need to compress again. #TODO Use blosc to put binary into array for MongoClient insert. _image = await resp #compressed_image = Image.from #TODO pass # TODO INSERT DATA async def parse_html() -> dict: """ Provided html, parse for data points. Need to use xpath as classnames are dynamically generated/change frequently. """ # xpaths to data points. These will most likely change which sucks. temp_sale_tag = "/html/body/div[2]/div[2]/div/div[2]/div[1]/div/div/div[2]/div[1]/span/text()" temp_address = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div[1]/div[1]/h1/span[1]/text()" temp_state_zip = " /html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div[1]/div[1]/h1/span[2]/text()" temp_price = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div[2]/div/h3/div/text()" temp_beds = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div[2]/div/h3/div/text()" temp_baths = " /html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div[1]/div[2]/div[1]/div/ul/li[2]/div/div/text()" temp_sqft = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div[1]/div[2]/div[1]/div/ul/li[3]/div/div/text()" temp_hoa_fee = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[4]/div[2]/div/div[4]/div/div/div[3]text()" temp_heating = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[4]/div[2]/div/div[5]/div/div/div[3]/text()" temp_cooling = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[4]/div[2]/div/div[6]/div/div/div[3]/text()" temp_description = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[4]/div[2]/div/text()" # Use lxml to parse xpath from soup. tree = html.fromstring(html_content) # Create element tree. sale_tag = tree.xpath(temp_sale_tag) address = tree.xpath(temp_address) state_zip = tree.xpath(temp_state_zip) price = tree.xpath(temp_price) beds = tree.xpath(temp_beds) baths = tree.xpath(temp_baths) sqft = tree.xpath(temp_sqft) hoa_fee = tree.xpath(temp_hoa_fee) heating = tree.xpath(temp_heating) cooling = tree.xpath(temp_cooling) description = tree.xpath(temp_descrption) async def load_into_db(): # Return a dict of data points return {"Sale Tag": sale_tag, "Address": address, "State Zip Code": state_zip, "Price": price, "Beds": beds, "Baths": baths, "Square Footage": sqft, "HOA Fees": hoa_fee, "Cooling": cooling, "Description": description, "Images": image_arr} #TODO pass #TODO # Extract Listings # Initiate webdriver. options = Options() options.headless = True driver = webdriver.Firefox(options=options,executable_path=r"geckodriver") # Make sure the driver is an exe. Intended to be run in linux vm. # Get listing response async with session.get(listing_url) as resp: html_content = resp.text() await asyncio.sleep(self.sleep_time) # Sleep a few second between every request. Be nice to the trulia graphql api backend! await html_content datapoints = await parse_html() # Get listing images' urls with webdriver imageset_requests = await interceptor() # Call interceptor. Aggregates all requests for property images. images_task = [download_images() for image_url in imageset_requests] get_images = await asyncio.gather(*images_task) # Load into DB async def parse_xml(self, xml_content) -> list: """Return a list of urls from sitemaps' xml content""" urls = [] #Temp storage in mem soup = BS(xml_content, "lxml") # Pass xml content and parser into soup for url in soup.find_all('loc'): urls.append(url.get_text()) self.urls = urls assert len(self.urls) > 10 # We should have way more. Better end to end testing will be implemented in the store_data.py module. ' async def dispatch(self, loop) -> dict: """ Init ClientSession(). Dispatch urls to unzip/decompress. Return dict of all datapoints including status of db insert:Bool. """ # headers headers = ({'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36', 'Accept-Language': 'en-US, en;q=0.5'}) # Wrap method calls in ClientSession() context manager. async with aiohttp.ClientSession(loop=loop) as session: # Get xml page containg urls to active property sitemaps async with session.get(self.sitemap) as resp: xml_content = await resp.text() await self.parse_xml(xml_content) print(f"Collected {len(self.urls)} urls. \n {self.urls}") assert len(self.urls) > 10 # Fetch Listing sitemaps. Extract/Read gzip urls to file tasks = [self.fetch_urls(session, gzip_url) for gzip_url in self.urls] results = asyncio.gather(*tasks) await results # Fetch Extracted listing urls & parse html tasks = [self.extract_listing(session, listing_url, random_alias) for listing_url in self.urls] results = asyncio.gather(*tasks) await results if __name__ == '__main__': m = Main() loop = asyncio.get_event_loop() results = loop.run_until_complete(m.dispatch(loop))
529
0
31
d86c455eaaae2af14cec6f33123c2601b31632af
1,300
py
Python
server/jukeboxify_cli.py
SteveParrington/jukeboxify
7008832d666c65f4e56581d7463d3ae0c2b49156
[ "Apache-2.0" ]
null
null
null
server/jukeboxify_cli.py
SteveParrington/jukeboxify
7008832d666c65f4e56581d7463d3ae0c2b49156
[ "Apache-2.0" ]
null
null
null
server/jukeboxify_cli.py
SteveParrington/jukeboxify
7008832d666c65f4e56581d7463d3ae0c2b49156
[ "Apache-2.0" ]
null
null
null
import zmq from getpass import getpass if __name__ == '__main__': main()
26
59
0.549231
import zmq from getpass import getpass def jsonify(text_command): tokens = text_command.split() args = [] if len(tokens) > 1: args = tokens[1:] json = { "opcode": tokens[0], "args": args } return json def login_prompt(): login_payload = { "opcode": "login", "args": [ raw_input("Username: "), getpass() ] } return login_payload def enter_repl(socket): print("Jukeboxify CLI - Developed by Steve Parrington") try: while True: text_command = raw_input("> ") json = jsonify(text_command) if json['opcode'] == 'exit': raise KeyboardInterrupt elif json['opcode'] == 'login': json = login_prompt() socket.send_json(json) response = socket.recv_json() if "message" in response: print(response["message"]) else: print(response) except KeyboardInterrupt: print("Exiting Jukeboxify CLI...") socket.disconnect('tcp://127.0.0.1:7890') def main(): context = zmq.Context.instance() socket = context.socket(zmq.REQ) socket.connect('tcp://127.0.0.1:7890') enter_repl(socket) if __name__ == '__main__': main()
1,130
0
92
9bd4cd58e1813c3bba3fb98b07b0a1a92ef7ab87
2,029
py
Python
lib/config/models.py
Zealoe/HRNet-Semantic-Segmentation
e5082879d6a46f1eb1127429e9948c80c0e15418
[ "MIT" ]
2
2020-11-02T11:38:59.000Z
2021-03-23T09:54:14.000Z
lib/config/models.py
Zealoe/HRNet-Semantic-Segmentation
e5082879d6a46f1eb1127429e9948c80c0e15418
[ "MIT" ]
null
null
null
lib/config/models.py
Zealoe/HRNet-Semantic-Segmentation
e5082879d6a46f1eb1127429e9948c80c0e15418
[ "MIT" ]
null
null
null
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft # Licensed under the MIT License. # Written by Ke Sun (sunk@mail.ustc.edu.cn) # ------------------------------------------------------------------------------ from __future__ import absolute_import from __future__ import division from __future__ import print_function from yacs.config import CfgNode as CN # high_resoluton_net related params for segmentation HIGH_RESOLUTION_NET = CN() HIGH_RESOLUTION_NET.PRETRAINED_LAYERS = ['*'] HIGH_RESOLUTION_NET.STEM_INPLANES = 64 HIGH_RESOLUTION_NET.FINAL_CONV_KERNEL = 1 HIGH_RESOLUTION_NET.WITH_HEAD = True HIGH_RESOLUTION_NET.STAGE1 = CN() HIGH_RESOLUTION_NET.STAGE1.NUM_MODULES = 1 HIGH_RESOLUTION_NET.STAGE1.NUM_BRANCHES = 1 HIGH_RESOLUTION_NET.STAGE1.NUM_BLOCKS = [4] HIGH_RESOLUTION_NET.STAGE1.NUM_CHANNELS = [32] HIGH_RESOLUTION_NET.STAGE1.BLOCK = 'BASIC' HIGH_RESOLUTION_NET.STAGE1.FUSE_METHOD = 'SUM' HIGH_RESOLUTION_NET.STAGE2 = CN() HIGH_RESOLUTION_NET.STAGE2.NUM_MODULES = 1 HIGH_RESOLUTION_NET.STAGE2.NUM_BRANCHES = 2 HIGH_RESOLUTION_NET.STAGE2.NUM_BLOCKS = [4, 4] HIGH_RESOLUTION_NET.STAGE2.NUM_CHANNELS = [32, 64] HIGH_RESOLUTION_NET.STAGE2.BLOCK = 'BASIC' HIGH_RESOLUTION_NET.STAGE2.FUSE_METHOD = 'SUM' HIGH_RESOLUTION_NET.STAGE3 = CN() HIGH_RESOLUTION_NET.STAGE3.NUM_MODULES = 1 HIGH_RESOLUTION_NET.STAGE3.NUM_BRANCHES = 3 HIGH_RESOLUTION_NET.STAGE3.NUM_BLOCKS = [4, 4, 4] HIGH_RESOLUTION_NET.STAGE3.NUM_CHANNELS = [32, 64, 128] HIGH_RESOLUTION_NET.STAGE3.BLOCK = 'BASIC' HIGH_RESOLUTION_NET.STAGE3.FUSE_METHOD = 'SUM' HIGH_RESOLUTION_NET.STAGE4 = CN() HIGH_RESOLUTION_NET.STAGE4.NUM_MODULES = 1 HIGH_RESOLUTION_NET.STAGE4.NUM_BRANCHES = 4 HIGH_RESOLUTION_NET.STAGE4.NUM_BLOCKS = [4, 4, 4, 4] HIGH_RESOLUTION_NET.STAGE4.NUM_CHANNELS = [32, 64, 128, 256] HIGH_RESOLUTION_NET.STAGE4.BLOCK = 'BASIC' HIGH_RESOLUTION_NET.STAGE4.FUSE_METHOD = 'SUM' MODEL_EXTRAS = { 'seg_hrnet': HIGH_RESOLUTION_NET, }
36.890909
81
0.726959
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft # Licensed under the MIT License. # Written by Ke Sun (sunk@mail.ustc.edu.cn) # ------------------------------------------------------------------------------ from __future__ import absolute_import from __future__ import division from __future__ import print_function from yacs.config import CfgNode as CN # high_resoluton_net related params for segmentation HIGH_RESOLUTION_NET = CN() HIGH_RESOLUTION_NET.PRETRAINED_LAYERS = ['*'] HIGH_RESOLUTION_NET.STEM_INPLANES = 64 HIGH_RESOLUTION_NET.FINAL_CONV_KERNEL = 1 HIGH_RESOLUTION_NET.WITH_HEAD = True HIGH_RESOLUTION_NET.STAGE1 = CN() HIGH_RESOLUTION_NET.STAGE1.NUM_MODULES = 1 HIGH_RESOLUTION_NET.STAGE1.NUM_BRANCHES = 1 HIGH_RESOLUTION_NET.STAGE1.NUM_BLOCKS = [4] HIGH_RESOLUTION_NET.STAGE1.NUM_CHANNELS = [32] HIGH_RESOLUTION_NET.STAGE1.BLOCK = 'BASIC' HIGH_RESOLUTION_NET.STAGE1.FUSE_METHOD = 'SUM' HIGH_RESOLUTION_NET.STAGE2 = CN() HIGH_RESOLUTION_NET.STAGE2.NUM_MODULES = 1 HIGH_RESOLUTION_NET.STAGE2.NUM_BRANCHES = 2 HIGH_RESOLUTION_NET.STAGE2.NUM_BLOCKS = [4, 4] HIGH_RESOLUTION_NET.STAGE2.NUM_CHANNELS = [32, 64] HIGH_RESOLUTION_NET.STAGE2.BLOCK = 'BASIC' HIGH_RESOLUTION_NET.STAGE2.FUSE_METHOD = 'SUM' HIGH_RESOLUTION_NET.STAGE3 = CN() HIGH_RESOLUTION_NET.STAGE3.NUM_MODULES = 1 HIGH_RESOLUTION_NET.STAGE3.NUM_BRANCHES = 3 HIGH_RESOLUTION_NET.STAGE3.NUM_BLOCKS = [4, 4, 4] HIGH_RESOLUTION_NET.STAGE3.NUM_CHANNELS = [32, 64, 128] HIGH_RESOLUTION_NET.STAGE3.BLOCK = 'BASIC' HIGH_RESOLUTION_NET.STAGE3.FUSE_METHOD = 'SUM' HIGH_RESOLUTION_NET.STAGE4 = CN() HIGH_RESOLUTION_NET.STAGE4.NUM_MODULES = 1 HIGH_RESOLUTION_NET.STAGE4.NUM_BRANCHES = 4 HIGH_RESOLUTION_NET.STAGE4.NUM_BLOCKS = [4, 4, 4, 4] HIGH_RESOLUTION_NET.STAGE4.NUM_CHANNELS = [32, 64, 128, 256] HIGH_RESOLUTION_NET.STAGE4.BLOCK = 'BASIC' HIGH_RESOLUTION_NET.STAGE4.FUSE_METHOD = 'SUM' MODEL_EXTRAS = { 'seg_hrnet': HIGH_RESOLUTION_NET, }
0
0
0
5dd252c8cdbd1b74c09d109c4140190861574d5b
3,679
py
Python
code/multifuture_eval_trajs_prob.py
ziyan0302/Multiverse
3b2f590a7d99758b6a8795070ca25a9698b767a9
[ "Apache-2.0" ]
190
2020-01-10T06:24:49.000Z
2022-03-24T10:21:46.000Z
code/multifuture_eval_trajs_prob.py
ziyan0302/Multiverse
3b2f590a7d99758b6a8795070ca25a9698b767a9
[ "Apache-2.0" ]
32
2020-06-18T23:36:10.000Z
2022-03-30T11:33:13.000Z
code/multifuture_eval_trajs_prob.py
ziyan0302/Multiverse
3b2f590a7d99758b6a8795070ca25a9698b767a9
[ "Apache-2.0" ]
60
2020-01-04T13:29:03.000Z
2022-03-27T09:26:13.000Z
# coding=utf-8 """Given the multifuture trajectory output, compute NLL""" import argparse import os import pickle import numpy as np from tqdm import tqdm parser = argparse.ArgumentParser() parser.add_argument("gt_path") parser.add_argument("prediction_file") parser.add_argument("--scene_h", type=int, default=18) parser.add_argument("--scene_w", type=int, default=32) parser.add_argument("--video_h", type=int, default=1080) parser.add_argument("--video_w", type=int, default=1920) def softmax(x, axis=None): """Stable softmax.""" x = x - x.max(axis=axis, keepdims=True) y = np.exp(x) return y / y.sum(axis=axis, keepdims=True) if __name__ == "__main__": args = parser.parse_args() args.w_gap = args.video_w*1.0/args.scene_w args.h_gap = args.video_h*1.0/args.scene_h with open(args.prediction_file, "rb") as f: predictions = pickle.load(f) # traj_id -> [1, beam_size, T, h*W] # T ~ [14, 25] time_list = [0, 1, 2, 3, 4] # 5 frame, 2second and 10 frame 4 second length prediction # NLL for each sample nlls = {} for timestep in time_list: nlls["T=%d" % (timestep+1)] = [] for traj_id in tqdm(predictions): camera = traj_id.split("_")[-1] # cam4 ... gt_file = os.path.join(args.gt_path, "%s.p" % traj_id) with open(gt_file, "rb") as f: gt = pickle.load(f) # annotation_key -> x_agent_traj # [1, beam_size, T, H*W] and beam_size of prob beams, logprobs = predictions[traj_id] # normalize the prob first logprobs = softmax(np.squeeze(logprobs)) beams = softmax(np.squeeze(beams), axis=-1) assert beams.shape[-1] == args.scene_h * args.scene_w # time_list number of h*w grid_probs = [get_hw_prob(beams, logprobs, t) for t in time_list] for i, timestep in enumerate(time_list): gt_xys = [] for future_id in gt: if len(gt[future_id]["x_agent_traj"]) <= timestep: continue x, y = gt[future_id]["x_agent_traj"][timestep][2:] gt_xys.append([x, y]) if not gt_xys: continue # a list of indices between 1 and h*w gt_indexes = xys_to_indexes(np.asarray(gt_xys), args) nll = compute_nll(grid_probs[i], gt_indexes) nlls["T=%d" % (timestep+1)].append(nll) print([len(nlls[k]) for k in nlls]) print("NLL:") keys = sorted(nlls.keys()) print(" ".join(keys)) print(" ".join(["%s" % np.mean(nlls[k]) for k in keys]))
30.658333
89
0.645556
# coding=utf-8 """Given the multifuture trajectory output, compute NLL""" import argparse import os import pickle import numpy as np from tqdm import tqdm parser = argparse.ArgumentParser() parser.add_argument("gt_path") parser.add_argument("prediction_file") parser.add_argument("--scene_h", type=int, default=18) parser.add_argument("--scene_w", type=int, default=32) parser.add_argument("--video_h", type=int, default=1080) parser.add_argument("--video_w", type=int, default=1920) def softmax(x, axis=None): """Stable softmax.""" x = x - x.max(axis=axis, keepdims=True) y = np.exp(x) return y / y.sum(axis=axis, keepdims=True) def get_hw_prob(beams, probs, t): # beams [beam_size, T, h*w] # probs [beam_size] beam_size, _, hw = beams.shape new_prob = np.zeros((beam_size, hw), dtype="float32") for b in range(beam_size): new_prob[b, :] = beams[b, t, :] * probs[b] # sum to 1 new_prob = np.sum(new_prob, axis=0) # [h*w] return new_prob def compute_nll(pred_probs, gt_indexes): # pred_probs is [h*w], sum to 1 # gt_indexs is K index from 0 to h*w -1 nll = 0.0 for gt_index in gt_indexes: nll += -np.log(pred_probs[gt_index] + np.finfo(float).eps) nll /= len(gt_indexes) return nll def xys_to_indexes(xys, args): # xys [K, 2] x_indexes = np.ceil(xys[:, 0] / args.w_gap) y_indexes = np.ceil(xys[:, 1] / args.h_gap) x_indexes = np.asarray(x_indexes, dtype="int") y_indexes = np.asarray(y_indexes, dtype="int") # ceil(0.0) = 0.0, we need x_indexes[x_indexes == 0] = 1 y_indexes[y_indexes == 0] = 1 x_indexes = x_indexes - 1 y_indexes = y_indexes - 1 one_hot = np.zeros((len(xys), args.scene_h, args.scene_w), dtype="uint8") one_hot[range(len(xys)), y_indexes, x_indexes] = 1 one_hot_flat = one_hot.reshape((len(xys), -1)) # [len(xys), h*w] classes = np.argmax(one_hot_flat, axis=1) # [len(xys)] return classes.tolist() if __name__ == "__main__": args = parser.parse_args() args.w_gap = args.video_w*1.0/args.scene_w args.h_gap = args.video_h*1.0/args.scene_h with open(args.prediction_file, "rb") as f: predictions = pickle.load(f) # traj_id -> [1, beam_size, T, h*W] # T ~ [14, 25] time_list = [0, 1, 2, 3, 4] # 5 frame, 2second and 10 frame 4 second length prediction # NLL for each sample nlls = {} for timestep in time_list: nlls["T=%d" % (timestep+1)] = [] for traj_id in tqdm(predictions): camera = traj_id.split("_")[-1] # cam4 ... gt_file = os.path.join(args.gt_path, "%s.p" % traj_id) with open(gt_file, "rb") as f: gt = pickle.load(f) # annotation_key -> x_agent_traj # [1, beam_size, T, H*W] and beam_size of prob beams, logprobs = predictions[traj_id] # normalize the prob first logprobs = softmax(np.squeeze(logprobs)) beams = softmax(np.squeeze(beams), axis=-1) assert beams.shape[-1] == args.scene_h * args.scene_w # time_list number of h*w grid_probs = [get_hw_prob(beams, logprobs, t) for t in time_list] for i, timestep in enumerate(time_list): gt_xys = [] for future_id in gt: if len(gt[future_id]["x_agent_traj"]) <= timestep: continue x, y = gt[future_id]["x_agent_traj"][timestep][2:] gt_xys.append([x, y]) if not gt_xys: continue # a list of indices between 1 and h*w gt_indexes = xys_to_indexes(np.asarray(gt_xys), args) nll = compute_nll(grid_probs[i], gt_indexes) nlls["T=%d" % (timestep+1)].append(nll) print([len(nlls[k]) for k in nlls]) print("NLL:") keys = sorted(nlls.keys()) print(" ".join(keys)) print(" ".join(["%s" % np.mean(nlls[k]) for k in keys]))
1,191
0
69
9a3aeb0bf305c0a63903c5e9ab76a4899c4f2eb3
4,348
py
Python
smtpClient/main.py
number23/iLibrary
e03c81cb6e355b562ba2e1468d9752b56c6bab56
[ "Apache-2.0" ]
null
null
null
smtpClient/main.py
number23/iLibrary
e03c81cb6e355b562ba2e1468d9752b56c6bab56
[ "Apache-2.0" ]
null
null
null
smtpClient/main.py
number23/iLibrary
e03c81cb6e355b562ba2e1468d9752b56c6bab56
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' vi $HOME/.LoginAccount.txt [mailClient] host = smtp.qq.com port = 25 user = *** pass = *** fr = xxxxxx@qq.com to = xxxxxx@gmail.com debuglevel = True login = False starttls = False ''' __all__ = ['get_smtp_client', 'sendmail'] import os, sys from ConfigParser import ConfigParser from ConfigParser import NoOptionError from smtplib import SMTP from smtplib import SMTPAuthenticationError from email import Encoders from email.base64MIME import encode as encode_base64 from email.MIMEBase import MIMEBase from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText if __name__ == '__main__': from optparse import OptionParser usage = '%prog [-e addr] [-a] args...' parser = OptionParser(usage=usage) parser.add_option('-e', '--addr', dest='addr', help='receive email address', metavar='address') parser.add_option('-a', '--atta', dest='atta', action='store_true', default=False, help='attachment flag') (options, args) = parser.parse_args() if not args: parser.print_usage() sys.exit(1) fn(options, args)
30.194444
90
0.569687
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' vi $HOME/.LoginAccount.txt [mailClient] host = smtp.qq.com port = 25 user = *** pass = *** fr = xxxxxx@qq.com to = xxxxxx@gmail.com debuglevel = True login = False starttls = False ''' __all__ = ['get_smtp_client', 'sendmail'] import os, sys from ConfigParser import ConfigParser from ConfigParser import NoOptionError from smtplib import SMTP from smtplib import SMTPAuthenticationError from email import Encoders from email.base64MIME import encode as encode_base64 from email.MIMEBase import MIMEBase from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText def get_smtp_client(stor): host = stor['host'] port = stor['port'] user = stor['user'] passwd = stor['pass'] debuglevel = stor['debuglevel'] login = stor['login'] starttls = stor['starttls'] s = SMTP(host, port) if debuglevel: s.set_debuglevel(True) if starttls and login: s.ehlo() s.starttls() s.ehlo() s.login(user, passwd) elif login: try: s.login(user, passwd) except SMTPAuthenticationError: sys.stdout.write('\n------- try Auth Login again ------\n') s = SMTP(host, port) if debuglevel: s.set_debuglevel(True) s.ehlo() (code, resp) = s.docmd('AUTH LOGIN') if code != 334: raise SMTPAuthenticationError(code, resp) (code, resp) = s.docmd(encode_base64(user, eol="")) if code != 334: raise SMTPAuthenticationError(code, resp) (code, resp) = s.docmd(encode_base64(passwd, eol="")) if code != 235: raise SMTPAuthenticationError(code, resp) return s def sendmail(server, msg): address = [i for f in ('To', 'Cc', 'Bcc') if msg[f] for i in msg[f].split(',')] server.sendmail(msg['From'], address, msg.as_string()) def fn(options, args): cfg = ConfigParser() cfg.read(os.path.join(os.getenv('HOME'), '.LoginAccount.txt')) flag = 'mailClient' keys = ('host', 'port', 'user', 'pass', 'fr', 'to', 'debuglevel', 'login', 'starttls') stor = {} for k in keys: stor.setdefault(k, '') try: stor['host'] = cfg.get(flag, 'host') stor['port'] = cfg.getint(flag, 'port') stor['user'] = cfg.get(flag, 'user') stor['pass'] = cfg.get(flag, 'pass') stor['fr'] = cfg.get(flag, 'fr') stor['to'] = cfg.get(flag, 'to') stor['debuglevel'] = cfg.getboolean(flag, 'debuglevel') stor['login'] = cfg.getboolean(flag, 'login') stor['starttls'] = cfg.getboolean(flag, 'starttls') except NoOptionError: pass if options.addr: stor['to'] = options.addr s = get_smtp_client(stor) for arg in args: sys.stdout.write('sending... ' + arg) msg = MIMEMultipart() msg['From'] = stor['fr'] msg['Subject'] = arg msg['To'] = stor['to'] msg.set_boundary('===== Baby, I love you. https://twitter.com/number23_cn =====') if options.atta: data = MIMEBase('application', 'octet-stream') data.set_payload(open(arg, 'rb').read()) Encoders.encode_base64(data) data.add_header('Content-Disposition', 'attachment', filename = arg) msg.attach(data) else: b = '''<html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head><body><pre>''' b += open(arg, 'rb').read() b += '''</pre></body></html>''' body = MIMEText(b, _subtype = 'html', _charset = 'utf-8') msg.attach(body) sendmail(s, msg) sys.stdout.write(' done.\n') s.close() if __name__ == '__main__': from optparse import OptionParser usage = '%prog [-e addr] [-a] args...' parser = OptionParser(usage=usage) parser.add_option('-e', '--addr', dest='addr', help='receive email address', metavar='address') parser.add_option('-a', '--atta', dest='atta', action='store_true', default=False, help='attachment flag') (options, args) = parser.parse_args() if not args: parser.print_usage() sys.exit(1) fn(options, args)
3,082
0
69
9858d3b8cadb2fd50cfc53e91f4ca4910bc15ea3
3,103
py
Python
incrowd/push_notifications/fields.py
incrowdio/incrowd
711e99c55b9da815af7749a2930d4184e235fa68
[ "Apache-2.0" ]
4
2015-03-10T04:24:07.000Z
2016-09-18T16:41:12.000Z
incrowd/push_notifications/fields.py
incrowdio/incrowd
711e99c55b9da815af7749a2930d4184e235fa68
[ "Apache-2.0" ]
27
2015-01-03T09:52:50.000Z
2021-06-10T20:37:08.000Z
incrowd/push_notifications/fields.py
incrowdio/incrowd
711e99c55b9da815af7749a2930d4184e235fa68
[ "Apache-2.0" ]
2
2015-09-07T21:06:51.000Z
2016-03-10T11:31:57.000Z
import re import struct from django import forms from django.core.validators import RegexValidator from django.db import models, connection from django.utils import six from django.utils.translation import ugettext_lazy as _ __all__ = ["HexadecimalField", "HexIntegerField"] hex_re = re.compile(r"^[0-9A-f]+$") postgres_engines = [ "django.db.backends.postgresql_psycopg2", "django.contrib.gis.db.backends.postgis", ] class HexadecimalField(forms.CharField): """ A form field that accepts only hexadecimal numbers """ class HexIntegerField(models.CharField): """ This field stores a hexadecimal *string* of up to 64 bits as an unsigned integer on *all* backends including postgres. Reasoning: Postgres only supports signed bigints. Since we don't care about signedness, we store it as signed, and cast it to unsigned when we deal with the actual value (with struct) On sqlite and mysql, native unsigned bigint types are used. In all cases, the value we deal with in python is always in hex. """ # def db_type(self, connection): # engine = connection.settings_dict["ENGINE"] # if "mysql" in engine: # return "bigint unsigned" # elif "sqlite" in engine: # return "TEXT" # else: # return super(HexIntegerField, self).db_type(connection=connection)
35.261364
108
0.636803
import re import struct from django import forms from django.core.validators import RegexValidator from django.db import models, connection from django.utils import six from django.utils.translation import ugettext_lazy as _ __all__ = ["HexadecimalField", "HexIntegerField"] hex_re = re.compile(r"^[0-9A-f]+$") postgres_engines = [ "django.db.backends.postgresql_psycopg2", "django.contrib.gis.db.backends.postgis", ] class HexadecimalField(forms.CharField): """ A form field that accepts only hexadecimal numbers """ def __init__(self, *args, **kwargs): self.default_validators = [RegexValidator(hex_re, _("Enter a valid hexadecimal number"), "invalid")] super(HexadecimalField, self).__init__(*args, **kwargs) class HexIntegerField(models.CharField): """ This field stores a hexadecimal *string* of up to 64 bits as an unsigned integer on *all* backends including postgres. Reasoning: Postgres only supports signed bigints. Since we don't care about signedness, we store it as signed, and cast it to unsigned when we deal with the actual value (with struct) On sqlite and mysql, native unsigned bigint types are used. In all cases, the value we deal with in python is always in hex. """ def __init__(self, *args, **kwargs): self.max_length = 16 super(HexIntegerField, self).__init__(*args, **kwargs) # def db_type(self, connection): # engine = connection.settings_dict["ENGINE"] # if "mysql" in engine: # return "bigint unsigned" # elif "sqlite" in engine: # return "TEXT" # else: # return super(HexIntegerField, self).db_type(connection=connection) def get_prep_value(self, value): if value is None or value == "": return None else: return str(value) # if isinstance(value, six.string_types): # value = int(value, 16) # # on postgres only, interpret as signed # if connection.settings_dict["ENGINE"] in postgres_engines: # value = struct.unpack("q", struct.pack("Q", value))[0] # # elif "sqlite" in connection.settings_dict["ENGINE"]: # # value = hex(int(value)) # return value def to_python(self, value): if isinstance(value, six.string_types): return value if value is None: return "" return str(value) # # on postgres only, re-interpret from signed to unsigned # if connection.settings_dict["ENGINE"] in postgres_engines: # value = hex(struct.unpack("Q", struct.pack("q", value))[0]) # elif "sqlite" in connection.settings_dict["ENGINE"]: # value = str(value) # # return value def formfield(self, **kwargs): defaults = {"form_class": HexadecimalField} # defaults = {'min_value': 0, # 'max_value': models.BigIntegerField.MAX_BIGINT ** 2 - 1} defaults.update(kwargs) return super(HexIntegerField, self).formfield(**defaults)
1,586
0
133
c272ab461573f0045f650a404b0a542762b38393
428
py
Python
heatmap_gen/prediction_filter.py
lthealy/quip_paad_cancer_detection
b05310b6eff7276920ca24c5c7b0b9f42ee563cd
[ "BSD-3-Clause" ]
8
2020-03-02T09:55:37.000Z
2021-07-12T09:13:49.000Z
heatmap_gen/prediction_filter.py
lthealy/quip_paad_cancer_detection
b05310b6eff7276920ca24c5c7b0b9f42ee563cd
[ "BSD-3-Clause" ]
2
2019-07-09T13:38:15.000Z
2021-04-15T15:36:36.000Z
heatmap_gen/prediction_filter.py
lthealy/quip_paad_cancer_detection
b05310b6eff7276920ca24c5c7b0b9f42ee563cd
[ "BSD-3-Clause" ]
7
2019-07-22T10:28:18.000Z
2021-08-09T19:30:00.000Z
import os import sys input = sys.argv[1] output = sys.argv[2] f1 = open(input, 'r') f2 = open('temp.txt', 'w') start = 0 for line in f1: start += 1 if start < 3: f2.write(line) continue parts = line.split() if float(parts[2]) > 1e-3: f2.write(line) f1.close() f2.close() command = 'cp temp.txt' + ' ' + output print('command: ', command) os.system(command) os.system('rm -rf temp.txt')
17.833333
38
0.584112
import os import sys input = sys.argv[1] output = sys.argv[2] f1 = open(input, 'r') f2 = open('temp.txt', 'w') start = 0 for line in f1: start += 1 if start < 3: f2.write(line) continue parts = line.split() if float(parts[2]) > 1e-3: f2.write(line) f1.close() f2.close() command = 'cp temp.txt' + ' ' + output print('command: ', command) os.system(command) os.system('rm -rf temp.txt')
0
0
0
6bb1780b98acbcaeddde95a113f189e1914af121
608
py
Python
tests/test_jaxtainer.py
MABilton/arraytainers
b90da9a7cf3240a7724bf4592f75dccf95885233
[ "MIT" ]
null
null
null
tests/test_jaxtainer.py
MABilton/arraytainers
b90da9a7cf3240a7724bf4592f75dccf95885233
[ "MIT" ]
null
null
null
tests/test_jaxtainer.py
MABilton/arraytainers
b90da9a7cf3240a7724bf4592f75dccf95885233
[ "MIT" ]
null
null
null
import jax.numpy as jnp import jaxlib from arraytainers import Jaxtainer from main_tests.test_class import ArraytainerTests
25.333333
67
0.694079
import jax.numpy as jnp import jaxlib from arraytainers import Jaxtainer from main_tests.test_class import ArraytainerTests class TestJaxtainer(ArraytainerTests): container_class = Jaxtainer expected_array_types = (jaxlib.xla_extension.DeviceArrayBase,) @staticmethod def array_constructor(x): return jnp.array(object=x) # self.array = lambda self, x : jnp.array(object=x) # self.array_types = (jaxlib.xla_extension.DeviceArrayBase,) # def test_vmap(): # def test_jit(): # def test_autograd(): # def test_vmap_jit_autograd():
40
417
24
a3abba71345244f25abf2db265ca12f65a90aec3
7,214
py
Python
postfix.py
ashraf1lastbreath/Postfix
1fd23ae4029b26577782f2a732b55b4cc30125a7
[ "MIT" ]
null
null
null
postfix.py
ashraf1lastbreath/Postfix
1fd23ae4029b26577782f2a732b55b4cc30125a7
[ "MIT" ]
null
null
null
postfix.py
ashraf1lastbreath/Postfix
1fd23ae4029b26577782f2a732b55b4cc30125a7
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Function to evaluate Post Fix expression #Calculation function for different opeartors #Printing the Menu print "" print "" print "" print "" menu = {} menu['1']="What are infix postfix and prefix notations?" menu['2']="Infix to Postfix Expression Conversion" menu['3']="Evaluation of Postfix expression" menu['4']="Exit" while True: options=menu.keys() options.sort() print"" print " MENU" print"=============================================" for entry in options: print entry, menu[entry] print"" selection=raw_input("Please Select:") print"" print "" if selection =='1': print "Infix notation : X + Y - Operators are written in-between their operands. " print "Postfix notation : X Y + - Operators are written after their operands. " print "Prefix notation : + X Y - Operators are written before their operands. " print "" print "" elif selection == '2' : print "" print "" print "" print " Infix to Postfix Convertor" print " ------------------------------------" print " Enter your In-Fix expression to be converted " infix = raw_input( " Example of In-Fix exprtession could be (2 + 3) - 7 / 9 :") print " ----------------------------------------------------------" postfix = infixtopostfix(infix) print "" print " Post Fix expression of ",infix, " is : "+' '.join(postfix) #to convert list into string print "" print "" print "" choice = raw_input(" Do you want to evaluate the value of your Post Fix expression (Y/N) : ") if choice == 'Y' or 'y' : result = evalPostfix(' '.join(postfix)) print " Value of Post Fix expression is :",result print " ----------------------------------------------------------------------------" print "" print "" else : continue elif selection == '3' : print "" print "" print "" print " Postfix Value Convertor" print " ------------------------------------" print " Enter your Post-Fix expression to be converted " postfix = raw_input( " Example of Post-Fix exprtession could be 2 3 + 7 9 / - :") print " ----------------------------------------------------------------------------" result = evalPostfix(' '.join(postfix)) #print "Value of Post Fix expression ",postfix," is :"+' '.join(result) print " Value of Post Fix expression is :",result print " " print "" elif selection == '4': break else: print "Unknown Option Selected!" print "--------------------------" print "" print "" print ""
41.45977
154
0.497366
# -*- coding: utf-8 -*- class Stack: def __init__(self, itemlist=[ ] ): self.items=itemlist def isEmpty(self) : if self.items == []: return True else: return False def push(self, item): self.items.append(item) return 0 def pop(self): return self.items.pop( ) def peek(self): # same as pop, only doesnt modify the stack return self.items[-1:][0] def infixtopostfix(infixexpr): import re stack =Stack( ) postfix = [ ] prec = { '(' : 1 , '+' : 2, '-' : 2, '*' : 3, '/' :3, } # operator precedance ( > ^ > + - > * / #tokenList = infixexpr.split( ) #create a comma separated list of tokens from the Infix Expression passed tokenList = re.split("([()+-/* ])", infixexpr.replace(" ", "")) # split the list of tokens with delimiters as any mathematical operator...split( ) doesnt take mor ethan one delimiter #print "Split tokenList :",tokenList #eg : infix expression A * B + C * D" gives tokenList ['A', '*', 'B', '+', 'C', '*', 'D'] for token in tokenList: if token in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' or token in '0123456789' : postfix.append(token) # Algo : lf Entered Character is Alphabet or Digit, Print Alphabet as Output elif token == '(': # Algo : If Entered Character is Opening Bracket then Push ‘(‘ Onto Stack stack.push(token) elif token == ')': topToken=stack.pop() # Algo : If Corresponding ‘)’ bracket appears then Start Removing Elements while topToken != '(' : # Algo : If any Operator Appears before ‘)’ then Push it onto Stack. postfix.append(topToken) topToken=stack.pop( ) # Algo : Pop from Stack till ‘(‘ is removed else : while (not stack.isEmpty( )) and ( prec[stack.peek( )] >= prec[token]) : #Check Whether There is any Operator Already present in Stack # If Present check Whether Priority of Incoming Operator is greater than Priority of Topmost Stack Operator postfix.append(stack.pop( )) #Algo : If not present on Stack then Push Operator Onto Stack. stack.push(token) # Algo : If Priority of Incoming Operator is Greater , then Push Incoming Operator Onto Stack. while not stack.isEmpty( ): #Algo : Else Pop Operator From Stack again repeat steps opToken=stack.pop() postfix.append(opToken) return postfix # Function to evaluate Post Fix expression def evalPostfix(infixexpr) : stack =Stack( ) tokenList = infixexpr.split( ) #create a comma separated list of tokens from the Infix Expression passed #print "Split tokenList :",tokenList #eg : infix expression A * B + C * D" gives tokenList ['A', '*', 'B', '+', 'C', '*', 'D'] for token in tokenList: if token in "0123456789" : stack.push(int(token)) #Algo : If the token is an operand, convert it from a string to an integer and push the value onto stack else : #Algo : If token is an operator, pop two next operands, and perform the operations operand2 = stack.pop( ) operand1 = stack.pop( ) result = evaluate(token, operand1, operand2) # Perform the operation stack.push(result) # Push the result back on the stack. return stack.pop( ) #Calculation function for different opeartors def evaluate(operator, operand1, operand2 ) : if operator == '+' : return operand1 + operand2 elif operator == '-': return operand1 - operand2 elif operator == '*': return operand1 * operand2 elif operator == '/': return operand1 / operand2 #Printing the Menu print "" print "" print "" print "" menu = {} menu['1']="What are infix postfix and prefix notations?" menu['2']="Infix to Postfix Expression Conversion" menu['3']="Evaluation of Postfix expression" menu['4']="Exit" while True: options=menu.keys() options.sort() print"" print " MENU" print"=============================================" for entry in options: print entry, menu[entry] print"" selection=raw_input("Please Select:") print"" print "" if selection =='1': print "Infix notation : X + Y - Operators are written in-between their operands. " print "Postfix notation : X Y + - Operators are written after their operands. " print "Prefix notation : + X Y - Operators are written before their operands. " print "" print "" elif selection == '2' : print "" print "" print "" print " Infix to Postfix Convertor" print " ------------------------------------" print " Enter your In-Fix expression to be converted " infix = raw_input( " Example of In-Fix exprtession could be (2 + 3) - 7 / 9 :") print " ----------------------------------------------------------" postfix = infixtopostfix(infix) print "" print " Post Fix expression of ",infix, " is : "+' '.join(postfix) #to convert list into string print "" print "" print "" choice = raw_input(" Do you want to evaluate the value of your Post Fix expression (Y/N) : ") if choice == 'Y' or 'y' : result = evalPostfix(' '.join(postfix)) print " Value of Post Fix expression is :",result print " ----------------------------------------------------------------------------" print "" print "" else : continue elif selection == '3' : print "" print "" print "" print " Postfix Value Convertor" print " ------------------------------------" print " Enter your Post-Fix expression to be converted " postfix = raw_input( " Example of Post-Fix exprtession could be 2 3 + 7 9 / - :") print " ----------------------------------------------------------------------------" result = evalPostfix(' '.join(postfix)) #print "Value of Post Fix expression ",postfix," is :"+' '.join(result) print " Value of Post Fix expression is :",result print " " print "" elif selection == '4': break else: print "Unknown Option Selected!" print "--------------------------" print "" print "" print ""
3,859
-9
231
86890a1939c19529ab88515e3f1b07a44f7afd78
6,850
py
Python
train.py
ZYH111/SelfSupervisedQE
ee7dd8d75e062b0bed6b1b54c4d9d4d6950268c9
[ "BSD-3-Clause" ]
4
2021-11-09T04:58:29.000Z
2022-01-27T09:03:34.000Z
train.py
ZYH111/SelfSupervisedQE
ee7dd8d75e062b0bed6b1b54c4d9d4d6950268c9
[ "BSD-3-Clause" ]
3
2021-11-24T08:05:00.000Z
2022-03-29T14:13:57.000Z
train.py
ZYH111/SelfSupervisedQE
ee7dd8d75e062b0bed6b1b54c4d9d4d6950268c9
[ "BSD-3-Clause" ]
1
2021-09-09T13:39:47.000Z
2021-09-09T13:39:47.000Z
import argparse import numpy as np import os import pandas as pd import time import torch from data import ( eval_collate_fn, EvalDataset, TrainCollator, TrainDataset, ) from evaluate import predict, make_word_outputs_final from transformers import ( AdamW, AutoConfig, AutoModelWithLMHead, AutoTokenizer, get_linear_schedule_with_warmup, set_seed, ) from torch.utils.data import DataLoader parser = argparse.ArgumentParser() parser.add_argument('--train-src', type=str, required=True) parser.add_argument('--train-tgt', type=str, required=True) parser.add_argument('--dev-src', type=str, required=True) parser.add_argument('--dev-tgt', type=str, required=True) parser.add_argument('--dev-hter', type=str) parser.add_argument('--dev-tags', type=str) parser.add_argument('--block-size', type=int, default=256) parser.add_argument('--eval-block-size', type=int, default=512) parser.add_argument('--wwm', action='store_true') parser.add_argument('--mlm-probability', type=float, default=0.15) parser.add_argument('--batch-size', type=int, default=16) parser.add_argument('--update-cycle', type=int, default=8) parser.add_argument('--eval-batch-size', type=int, default=8) parser.add_argument('--train-steps', type=int, default=100000) parser.add_argument('--eval-steps', type=int, default=1000) parser.add_argument('--learning-rate', type=float, default=5e-5) parser.add_argument('--pretrained-model-path', type=str, required=True) parser.add_argument('--save-model-path', type=str, required=True) parser.add_argument('--seed', type=int, default=42) args = parser.parse_args() print(args) set_seed(args.seed) device = torch.device('cuda') torch.cuda.set_device(0) config = AutoConfig.from_pretrained(args.pretrained_model_path, cache_dir=None) tokenizer = AutoTokenizer.from_pretrained(args.pretrained_model_path, cache_dir=None, use_fast=False, do_lower_case=False) model = AutoModelWithLMHead.from_pretrained(args.pretrained_model_path, config=config, cache_dir=None) model.resize_token_embeddings(len(tokenizer)) model.to(device) train_dataset = TrainDataset( src_path=args.train_src, tgt_path=args.train_tgt, tokenizer=tokenizer, block_size=args.block_size, wwm=args.wwm, ) train_dataloader = DataLoader( dataset=train_dataset, batch_size=args.batch_size, shuffle=True, collate_fn=TrainCollator(tokenizer=tokenizer, mlm_probability=args.mlm_probability), ) dev_dataset = EvalDataset( src_path=args.dev_src, tgt_path=args.dev_tgt, tokenizer=tokenizer, block_size=args.eval_block_size, wwm=args.wwm, N=7, M=1, ) dev_dataloader = DataLoader( dataset=dev_dataset, batch_size=args.eval_batch_size, shuffle=False, collate_fn=eval_collate_fn, ) param_optimizer = list(model.named_parameters()) no_decay = ['bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ { 'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01 }, { 'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0 }] optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate) lr_scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=0, num_training_steps=args.train_steps) dirs = ['checkpoint_best', 'checkpoint_last'] files_to_copy = ['config.json', 'tokenizer.json', 'tokenizer_config.json', 'vocab.txt'] for d in dirs: os.system('mkdir -p %s' % os.path.join(args.save_model_path, d)) for f in files_to_copy: os.system('cp %s %s' % ( os.path.join(args.pretrained_model_path, f), os.path.join(args.save_model_path, d, f) )) print('Configuration files copied') total_minibatches = len(train_dataloader) best_score = 0.0 num_steps = 1 model.train() model.zero_grad() epoch = 1 total_loss = 0.0 current_time = time.time() while True: for i, inputs in enumerate(train_dataloader): n_minibatches = i + 1 output = model( input_ids=inputs['input_ids'].to(device), token_type_ids=inputs['token_type_ids'].to(device), attention_mask=inputs['attention_mask'].to(device), labels=inputs['labels'].to(device), ) loss = output.loss / float(args.update_cycle) total_loss += float(loss) loss.backward() if (n_minibatches == total_minibatches) or (n_minibatches % args.update_cycle == 0): optimizer.step() lr_scheduler.step() model.zero_grad() old_time = current_time current_time = time.time() print('epoch = %d, step = %d, loss = %.6f (%.3fs)' % (epoch, num_steps, total_loss, current_time - old_time)) if (num_steps == args.train_steps) or (num_steps % args.eval_steps == 0): print('Evaluating...') preds, preds_prob = predict( eval_dataloader=dev_dataloader, model=model, device=device, tokenizer=tokenizer, N=7, M=1, mc_dropout=False, ) eval_score = make_word_outputs_final(preds, args.dev_tgt, tokenizer, threshold_tune=args.dev_tags)[-1] word_scores_prob = make_word_outputs_final(preds_prob, args.dev_tgt, tokenizer, threshold=0.5)[0] sent_outputs = pd.Series([float(np.mean(w)) for w in word_scores_prob]) fhter = open(args.dev_hter, 'r', encoding='utf-8') hter = pd.Series([float(x.strip()) for x in fhter]) fhter.close() pearson = float(sent_outputs.corr(hter)) print('Pearson: %.6f' % pearson) eval_score += pearson print('Validation Score: %.6f, Previous Best Score: %.6f' % (eval_score, best_score)) if eval_score > best_score: save_model(model, os.path.join(args.save_model_path, 'checkpoint_best/pytorch_model.bin')) best_score = eval_score save_model(model, os.path.join(args.save_model_path, 'checkpoint_last/pytorch_model.bin')) if num_steps >= args.train_steps: exit(0) num_steps += 1 total_loss = 0.0 epoch += 1
34.771574
122
0.653577
import argparse import numpy as np import os import pandas as pd import time import torch from data import ( eval_collate_fn, EvalDataset, TrainCollator, TrainDataset, ) from evaluate import predict, make_word_outputs_final from transformers import ( AdamW, AutoConfig, AutoModelWithLMHead, AutoTokenizer, get_linear_schedule_with_warmup, set_seed, ) from torch.utils.data import DataLoader parser = argparse.ArgumentParser() parser.add_argument('--train-src', type=str, required=True) parser.add_argument('--train-tgt', type=str, required=True) parser.add_argument('--dev-src', type=str, required=True) parser.add_argument('--dev-tgt', type=str, required=True) parser.add_argument('--dev-hter', type=str) parser.add_argument('--dev-tags', type=str) parser.add_argument('--block-size', type=int, default=256) parser.add_argument('--eval-block-size', type=int, default=512) parser.add_argument('--wwm', action='store_true') parser.add_argument('--mlm-probability', type=float, default=0.15) parser.add_argument('--batch-size', type=int, default=16) parser.add_argument('--update-cycle', type=int, default=8) parser.add_argument('--eval-batch-size', type=int, default=8) parser.add_argument('--train-steps', type=int, default=100000) parser.add_argument('--eval-steps', type=int, default=1000) parser.add_argument('--learning-rate', type=float, default=5e-5) parser.add_argument('--pretrained-model-path', type=str, required=True) parser.add_argument('--save-model-path', type=str, required=True) parser.add_argument('--seed', type=int, default=42) args = parser.parse_args() print(args) set_seed(args.seed) device = torch.device('cuda') torch.cuda.set_device(0) config = AutoConfig.from_pretrained(args.pretrained_model_path, cache_dir=None) tokenizer = AutoTokenizer.from_pretrained(args.pretrained_model_path, cache_dir=None, use_fast=False, do_lower_case=False) model = AutoModelWithLMHead.from_pretrained(args.pretrained_model_path, config=config, cache_dir=None) model.resize_token_embeddings(len(tokenizer)) model.to(device) train_dataset = TrainDataset( src_path=args.train_src, tgt_path=args.train_tgt, tokenizer=tokenizer, block_size=args.block_size, wwm=args.wwm, ) train_dataloader = DataLoader( dataset=train_dataset, batch_size=args.batch_size, shuffle=True, collate_fn=TrainCollator(tokenizer=tokenizer, mlm_probability=args.mlm_probability), ) dev_dataset = EvalDataset( src_path=args.dev_src, tgt_path=args.dev_tgt, tokenizer=tokenizer, block_size=args.eval_block_size, wwm=args.wwm, N=7, M=1, ) dev_dataloader = DataLoader( dataset=dev_dataset, batch_size=args.eval_batch_size, shuffle=False, collate_fn=eval_collate_fn, ) param_optimizer = list(model.named_parameters()) no_decay = ['bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ { 'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01 }, { 'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0 }] optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate) lr_scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=0, num_training_steps=args.train_steps) dirs = ['checkpoint_best', 'checkpoint_last'] files_to_copy = ['config.json', 'tokenizer.json', 'tokenizer_config.json', 'vocab.txt'] for d in dirs: os.system('mkdir -p %s' % os.path.join(args.save_model_path, d)) for f in files_to_copy: os.system('cp %s %s' % ( os.path.join(args.pretrained_model_path, f), os.path.join(args.save_model_path, d, f) )) print('Configuration files copied') def save_model(model, save_dir): print('Saving Model to', save_dir) if os.path.exists(save_dir): print('%s already exists. Removing it...' % save_dir) os.remove(save_dir) print('%s removed successfully.' % save_dir) torch.save(model.state_dict(), save_dir) print('%s saved successfully.' % save_dir) total_minibatches = len(train_dataloader) best_score = 0.0 num_steps = 1 model.train() model.zero_grad() epoch = 1 total_loss = 0.0 current_time = time.time() while True: for i, inputs in enumerate(train_dataloader): n_minibatches = i + 1 output = model( input_ids=inputs['input_ids'].to(device), token_type_ids=inputs['token_type_ids'].to(device), attention_mask=inputs['attention_mask'].to(device), labels=inputs['labels'].to(device), ) loss = output.loss / float(args.update_cycle) total_loss += float(loss) loss.backward() if (n_minibatches == total_minibatches) or (n_minibatches % args.update_cycle == 0): optimizer.step() lr_scheduler.step() model.zero_grad() old_time = current_time current_time = time.time() print('epoch = %d, step = %d, loss = %.6f (%.3fs)' % (epoch, num_steps, total_loss, current_time - old_time)) if (num_steps == args.train_steps) or (num_steps % args.eval_steps == 0): print('Evaluating...') preds, preds_prob = predict( eval_dataloader=dev_dataloader, model=model, device=device, tokenizer=tokenizer, N=7, M=1, mc_dropout=False, ) eval_score = make_word_outputs_final(preds, args.dev_tgt, tokenizer, threshold_tune=args.dev_tags)[-1] word_scores_prob = make_word_outputs_final(preds_prob, args.dev_tgt, tokenizer, threshold=0.5)[0] sent_outputs = pd.Series([float(np.mean(w)) for w in word_scores_prob]) fhter = open(args.dev_hter, 'r', encoding='utf-8') hter = pd.Series([float(x.strip()) for x in fhter]) fhter.close() pearson = float(sent_outputs.corr(hter)) print('Pearson: %.6f' % pearson) eval_score += pearson print('Validation Score: %.6f, Previous Best Score: %.6f' % (eval_score, best_score)) if eval_score > best_score: save_model(model, os.path.join(args.save_model_path, 'checkpoint_best/pytorch_model.bin')) best_score = eval_score save_model(model, os.path.join(args.save_model_path, 'checkpoint_last/pytorch_model.bin')) if num_steps >= args.train_steps: exit(0) num_steps += 1 total_loss = 0.0 epoch += 1
318
0
23
c1c9484b15c0c371600ef37dcc8f1eb81ebafc83
1,164
py
Python
scrapeSRApy/scrapeSRA.py
mmrmas/SRAMicrobiomeCategoryPipeline
75786cf79f770758602ee70d945e1d7ef297ca6d
[ "MIT" ]
null
null
null
scrapeSRApy/scrapeSRA.py
mmrmas/SRAMicrobiomeCategoryPipeline
75786cf79f770758602ee70d945e1d7ef297ca6d
[ "MIT" ]
null
null
null
scrapeSRApy/scrapeSRA.py
mmrmas/SRAMicrobiomeCategoryPipeline
75786cf79f770758602ee70d945e1d7ef297ca6d
[ "MIT" ]
null
null
null
import modules.open_file as of # read in the file downloaded from the run archive, in this partcular case https://www.ncbi.nlm.nih.gov/Traces/study/?query_key=1&WebEnv=MCID_6178e8ee92f0234b8354c36f&o=acc_s%3Aa (may not be functional) # SraRunTable.txt # Contains Metadata for all samples # check for each line if it contains "HMP_" -> that is the tissue # Check is_affected or is_tumor for extra subcategories in later versions of this script (but initially ignore these) # we select the first element from each line except the first line: the Run identifier # we select the element HMP_ which represnets the category # we ignore all lines that do not contain HMP_ # then we load teh file https://trace.ncbi.nlm.nih.gov/Traces/sra/?run= >>Run identifier here << # a basic frequency table is stored in the function "oTaxAnalysisData" # From this function we collect "name" and "percent" # This is stored as a file RunIdentifier.txt in the directory that carries the name of the category #main if __name__ == '__main__': main()
40.137931
202
0.756014
import modules.open_file as of # read in the file downloaded from the run archive, in this partcular case https://www.ncbi.nlm.nih.gov/Traces/study/?query_key=1&WebEnv=MCID_6178e8ee92f0234b8354c36f&o=acc_s%3Aa (may not be functional) # SraRunTable.txt # Contains Metadata for all samples # check for each line if it contains "HMP_" -> that is the tissue # Check is_affected or is_tumor for extra subcategories in later versions of this script (but initially ignore these) # we select the first element from each line except the first line: the Run identifier # we select the element HMP_ which represnets the category # we ignore all lines that do not contain HMP_ # then we load teh file https://trace.ncbi.nlm.nih.gov/Traces/sra/?run= >>Run identifier here << # a basic frequency table is stored in the function "oTaxAnalysisData" # From this function we collect "name" and "percent" # This is stored as a file RunIdentifier.txt in the directory that carries the name of the category def main(): #open the SRARunTable and store all relevant information downloadInfo = of.SRARunTable() #main if __name__ == '__main__': main()
87
0
23
689bb80283d50dcc36af84761266697add064c7b
418
py
Python
taxjar/data/region.py
danpalmer/taxjar-python
f22867bede037970970394d4c2a7635e9ec28ae9
[ "MIT" ]
24
2015-06-22T19:32:18.000Z
2022-03-28T17:51:47.000Z
taxjar/data/region.py
danpalmer/taxjar-python
f22867bede037970970394d4c2a7635e9ec28ae9
[ "MIT" ]
14
2017-05-16T15:26:15.000Z
2022-03-17T08:06:51.000Z
taxjar/data/region.py
danpalmer/taxjar-python
f22867bede037970970394d4c2a7635e9ec28ae9
[ "MIT" ]
15
2017-05-04T13:42:23.000Z
2022-03-12T18:14:36.000Z
from jsonobject import JsonObject, StringProperty from taxjar.data.iterable import TaxJarIterable
29.857143
55
0.746411
from jsonobject import JsonObject, StringProperty from taxjar.data.iterable import TaxJarIterable class TaxJarRegion(JsonObject): country_code = StringProperty() country = StringProperty() region_code = StringProperty() region = StringProperty() class TaxJarRegions(TaxJarIterable): def handle_response(self, response): self.data = [TaxJarRegion(r) for r in response] return self
91
157
72
ffa15f12fdc894d4532cf7e57ab348a7964a55f0
542
py
Python
tests/test_registrar.py
123joshuawu/orca
741856dc264ffd38a7de8c2da1847543fd8c84d1
[ "0BSD" ]
6
2020-12-09T01:53:40.000Z
2021-04-12T16:05:45.000Z
tests/test_registrar.py
123joshuawu/orca
741856dc264ffd38a7de8c2da1847543fd8c84d1
[ "0BSD" ]
13
2020-12-04T20:42:33.000Z
2021-04-17T20:15:11.000Z
tests/test_registrar.py
123joshuawu/orca
741856dc264ffd38a7de8c2da1847543fd8c84d1
[ "0BSD" ]
1
2020-12-28T01:31:28.000Z
2020-12-28T01:31:28.000Z
from api.models import ClassTypeEnum from api.parser.registrar import Registrar
49.272727
64
0.680812
from api.models import ClassTypeEnum from api.parser.registrar import Registrar def test_parse_period_types(): types = Registrar.parse_period_types("202101") assert types[('40432', 3, '21:05')] == ClassTypeEnum.TEST assert types[('44040', 4, '12:20')] == ClassTypeEnum.LECTURE assert types[('41340', 1, '12:20')] == ClassTypeEnum.LECTURE assert types[('41340', 4, '12:20')] == ClassTypeEnum.LECTURE assert types[('41536', 1, '09:05')] == ClassTypeEnum.TEST assert types[('41536', 3, '12:20')] == ClassTypeEnum.LAB
440
0
23
4760c00a445e7386fb0a28901582ad20ccac9772
2,398
py
Python
app.py
parryc/thevoid
0a79a2ed534bc8b33fdb73774ed2984836fe2cce
[ "MIT" ]
1
2015-12-22T19:33:21.000Z
2015-12-22T19:33:21.000Z
app.py
parryc/thevoid
0a79a2ed534bc8b33fdb73774ed2984836fe2cce
[ "MIT" ]
26
2015-09-07T04:29:10.000Z
2021-10-19T13:10:46.000Z
app.py
parryc/thevoid
0a79a2ed534bc8b33fdb73774ed2984836fe2cce
[ "MIT" ]
null
null
null
from flask import render_template from flask_assets import Environment, Bundle from flask_compress import Compress from factory import create_app app = create_app(__name__) app.config.from_object("config.DevelopmentConfig") assets = Environment(app) Compress(app) testing_site = app.config["TESTING_SITE"] app.jinja_env.filters["circle_num"] = circle_num_from_jinja_loop app.jinja_env.filters["taste"] = taste app.jinja_env.filters["price"] = price @app.errorhandler(404) @app.after_request # Define static asset bundles to be minimized and deployed bundles = { "parryc_css": Bundle( "css/marx.min.css", "css/style_parryc.css", "css/fonts/ptsans/fonts.css", filters="cssmin", output="gen/parryc.css", ), "khachapuri_css": Bundle( "css/marx.min.css", "css/style_khachapuri.css", "css/fonts/ptsans/fonts.css", filters="cssmin", output="gen/khachapuri.css", ), "corbin_css": Bundle( "css/marx.min.css", "css/style_corbin.css", "css/fonts/cormorant/fonts.css", filters="cssmin", output="gen/corbin.css", ), "leflan_css": Bundle( "css/marx.min.css", "css/style_leflan.css", "css/fonts/source-code-pro/source-code-pro.css", "css/fonts/cmu/fonts.css", "css/fonts/bpg-ingiri/bpg-ingiri.css", "css/fonts/mayan/fonts.css", filters="cssmin", output="gen/leflan.css", ), } assets.register(bundles) from mod_parryc.controllers import mod_parryc app.register_blueprint(mod_parryc) from mod_leflan.controllers import mod_leflan app.register_blueprint(mod_leflan) from mod_corbin.controllers import mod_corbin app.register_blueprint(mod_corbin) from mod_khachapuri.controllers import mod_khachapuri app.register_blueprint(mod_khachapuri) from avar_rocks.flask.controllers import mod_avar app.register_blueprint(mod_avar) from mod_zmnebi.controllers import mod_zmnebi app.register_blueprint(mod_zmnebi)
24.979167
64
0.705171
from flask import render_template from flask_assets import Environment, Bundle from flask_compress import Compress from factory import create_app app = create_app(__name__) app.config.from_object("config.DevelopmentConfig") assets = Environment(app) Compress(app) testing_site = app.config["TESTING_SITE"] def circle_num_from_jinja_loop(num): return "①②③④⑤⑥⑦⑧⑨⑩"[num - 1] def taste(taste_rating): return int(taste_rating) * "💛" def price(price_rating): return int(price_rating) * "💰" app.jinja_env.filters["circle_num"] = circle_num_from_jinja_loop app.jinja_env.filters["taste"] = taste app.jinja_env.filters["price"] = price @app.errorhandler(404) def not_found(error): return render_template("404.html"), 404 @app.after_request def add_header(response): # set cache to 2 weeks response.cache_control.max_age = 1209600 return response # Define static asset bundles to be minimized and deployed bundles = { "parryc_css": Bundle( "css/marx.min.css", "css/style_parryc.css", "css/fonts/ptsans/fonts.css", filters="cssmin", output="gen/parryc.css", ), "khachapuri_css": Bundle( "css/marx.min.css", "css/style_khachapuri.css", "css/fonts/ptsans/fonts.css", filters="cssmin", output="gen/khachapuri.css", ), "corbin_css": Bundle( "css/marx.min.css", "css/style_corbin.css", "css/fonts/cormorant/fonts.css", filters="cssmin", output="gen/corbin.css", ), "leflan_css": Bundle( "css/marx.min.css", "css/style_leflan.css", "css/fonts/source-code-pro/source-code-pro.css", "css/fonts/cmu/fonts.css", "css/fonts/bpg-ingiri/bpg-ingiri.css", "css/fonts/mayan/fonts.css", filters="cssmin", output="gen/leflan.css", ), } assets.register(bundles) from mod_parryc.controllers import mod_parryc app.register_blueprint(mod_parryc) from mod_leflan.controllers import mod_leflan app.register_blueprint(mod_leflan) from mod_corbin.controllers import mod_corbin app.register_blueprint(mod_corbin) from mod_khachapuri.controllers import mod_khachapuri app.register_blueprint(mod_khachapuri) from avar_rocks.flask.controllers import mod_avar app.register_blueprint(mod_avar) from mod_zmnebi.controllers import mod_zmnebi app.register_blueprint(mod_zmnebi)
290
0
113
77bc995fe7637ad166c11dd6cefa5ce2739e50b7
14,017
py
Python
bin/ADFRsuite/CCSBpckgs/PmvApp/deleteCmds.py
AngelRuizMoreno/Jupyter_Dock_devel
6d23bc174d5294d1e9909a0a1f9da0713042339e
[ "MIT" ]
null
null
null
bin/ADFRsuite/CCSBpckgs/PmvApp/deleteCmds.py
AngelRuizMoreno/Jupyter_Dock_devel
6d23bc174d5294d1e9909a0a1f9da0713042339e
[ "MIT" ]
null
null
null
bin/ADFRsuite/CCSBpckgs/PmvApp/deleteCmds.py
AngelRuizMoreno/Jupyter_Dock_devel
6d23bc174d5294d1e9909a0a1f9da0713042339e
[ "MIT" ]
1
2021-11-04T21:48:14.000Z
2021-11-04T21:48:14.000Z
################################################################################ ## ## This library is free software; you can redistribute it and/or ## modify it under the terms of the GNU Lesser General Public ## License as published by the Free Software Foundation; either ## version 2.1 of the License, or (at your option) any later version. ## ## This library is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public ## License along with this library; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ## ## (C) Copyrights Dr. Michel F. Sanner and TSRI 2016 ## ################################################################################ ############################################################################# # # Author: Ruth Huey, Michel F. SANNER # # Copyright: M. Sanner TSRI 2014 # ############################################################################# # # $Header: /mnt/raid/services/cvs/PmvApp/deleteCmds.py,v 1.8.4.1 2017/07/13 20:55:28 annao Exp $ # # $Id: deleteCmds.py,v 1.8.4.1 2017/07/13 20:55:28 annao Exp $ # """ This Module implements commands to delete items from the MoleculeViewer: for examples: Delete Molecule """ from PmvApp.Pmv import Event, AfterDeleteAtomsEvent, DeleteAtomsEvent, \ BeforeDeleteMoleculeEvent, AfterDeleteMoleculeEvent, RefreshDisplayEvent from PmvApp.Pmv import BeforeDeleteMoleculeEvent, AfterDeleteMoleculeEvent from PmvApp.selectionCmds import SelectionEvent from PmvApp.Pmv import MVCommand from AppFramework.App import DeleteObjectEvent from MolKit2.selection import Selection, SelectionSet from MolKit2.molecule import Molecule, MoleculeSet from PmvApp.selectionCmds import SelectionEvent class DeleteMolecule(MVCommand): """Command to delete molecule from the MoleculeViewer \n Package : PmvApp \n Module : deleteCmds \n Class : DeleteMolecule \n Command : deleteMolecule \n Synopsis:\n None<---deleteMolecule(molSel, **kw) \n """ def checkArguments(self, molSel): """None <- deleteMolecules(nodes, **kw) \n nodes: TreeNodeSet holding the current selection. """ assert molSel return (molSel,), {} class DeleteAtoms(MVCommand): """ Command to remove an AtomSet from the MoleculeViewer \n Package : PmvApp \n Module : deleteCmds \n Class : DeleteAtoms \n Command : deleteAtoms \n Synopsis:\n None<---deleteAtoms(atoms)\n Required Arguments:\n atoms --- AtomSet to be deleted.\n """ def checkArguments(self, selection): """None <- deleteAtoms(atoms) \n atoms: AtomSet to be deleted.""" assert selection return (selection,), {} def doit(self, selection): """ Function to delete all the references to each atom of a AtomSet.""" # Remove the atoms of the molecule you are deleting from the # the AtomSet self.app().allAtoms mol = selection.getAtomGroup().getMolecule() app = self.app() if len(selection)==len(mol._ag): app.deleteMolecule(mol) return # delete the atoms mol.deleteAtoms(selection) event = DeleteAtomsEvent(deletedAtoms=selection) self.app().eventHandler.dispatchEvent(event) event = RefreshDisplayEvent(molecule=mol) self.app().eventHandler.dispatchEvent(event) class DeleteCurrentSelection(DeleteAtoms): """ Command to remove an AtomSet from the MoleculeViewer \n Package : PmvApp \n Module : deleteCmds \n Class : DeleteCurrentSelection \n Command : deleteCurrentSelection \n Synopsis:\n None<---deleteCurrentSelection()\n Required Arguments:\n None """ def checkArguments(self): """None <- deleteCurrentSelection() """ return (), {} def doit(self): """ Function to delete all the references to each atom of a the currentSelection.""" atoms = old = self.app().activeSelection.get()[:] # make copy of selection ats = self.app().expandNodes(atoms) if not len(ats): return ats = ats.findType(Atom) self.app().clearSelection(log=0) DeleteAtoms.doit(self, ats) class DeleteHydrogens(DeleteAtoms): """ Command to remove hydrogen atoms from the MoleculeViewer \n Package : PmvApp Module : deleteCmds \n Class : DeleteHydrogens \n Command : deleteHydrogens \n Synopsis:\n None<---deleteHydrogens(atoms)\n Required Arguments:\n atoms --- Hydrogens found in this atom set are deleted.\n """ def checkArguments(self, atoms): """None <- deleteHydrogents(atoms) \n atoms: set of atoms, from which hydrogens are to be deleted.""" if isinstance(atoms, str): self.nodeLogString = "'"+atoms+"'" ats = self.app().expandNodes(atoms) assert ats return (ats,), {} commandClassFromName = { 'deleteMolecule' : [DeleteMolecule, None], 'deleteAtoms' : [DeleteAtoms, None ], #'deleteMolecules' : [DeleteMolecules, None], #'deleteAllMolecules' : [DeleteAllMolecules, None], #'deleteCurrentSelection' : [DeleteCurrentSelection, None ], #'deleteHydrogens' : [DeleteHydrogens, None], #'restoreMol' : [RestoreMolecule, None], }
40.394813
119
0.552829
################################################################################ ## ## This library is free software; you can redistribute it and/or ## modify it under the terms of the GNU Lesser General Public ## License as published by the Free Software Foundation; either ## version 2.1 of the License, or (at your option) any later version. ## ## This library is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public ## License along with this library; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ## ## (C) Copyrights Dr. Michel F. Sanner and TSRI 2016 ## ################################################################################ ############################################################################# # # Author: Ruth Huey, Michel F. SANNER # # Copyright: M. Sanner TSRI 2014 # ############################################################################# # # $Header: /mnt/raid/services/cvs/PmvApp/deleteCmds.py,v 1.8.4.1 2017/07/13 20:55:28 annao Exp $ # # $Id: deleteCmds.py,v 1.8.4.1 2017/07/13 20:55:28 annao Exp $ # """ This Module implements commands to delete items from the MoleculeViewer: for examples: Delete Molecule """ from PmvApp.Pmv import Event, AfterDeleteAtomsEvent, DeleteAtomsEvent, \ BeforeDeleteMoleculeEvent, AfterDeleteMoleculeEvent, RefreshDisplayEvent from PmvApp.Pmv import BeforeDeleteMoleculeEvent, AfterDeleteMoleculeEvent from PmvApp.selectionCmds import SelectionEvent from PmvApp.Pmv import MVCommand from AppFramework.App import DeleteObjectEvent from MolKit2.selection import Selection, SelectionSet from MolKit2.molecule import Molecule, MoleculeSet from PmvApp.selectionCmds import SelectionEvent class DeleteMolecule(MVCommand): """Command to delete molecule from the MoleculeViewer \n Package : PmvApp \n Module : deleteCmds \n Class : DeleteMolecule \n Command : deleteMolecule \n Synopsis:\n None<---deleteMolecule(molSel, **kw) \n """ def checkArguments(self, molSel): """None <- deleteMolecules(nodes, **kw) \n nodes: TreeNodeSet holding the current selection. """ assert molSel return (molSel,), {} def doit(self, molSel): mol = molSel.getAtomGroup().getMolecule() # manage selection if self.app().activeSelection.nbAtoms(): curSel = self.app().activeSelection for sele in curSel: if sele.getAtomGroup() == mol._ag: self.app().select(sele, negate=True, setupUndo=False) # we do not need to create undo for this command self.app().clearTopUndoCmds() # this is to prevent adding the contents # of app()._topUndoCmds list to the undo stack by the top command (deleteCommand) break #molSel = SelectionSet([mol.select()]) #molSel = SelectionSet([molSel]) #newcursel = curSel - molSel for name, selSet in self.app().namedSelections.items(): newselSet = selSet - SelectionSet([molSel]) self.app().namedSelections[name] = newselSet # self.app().removeObject(mol, "Molecule") event = DeleteObjectEvent(object=mol, objectType='Molecule') self.app().eventHandler.dispatchEvent(event) self.updateUndoRedoCmdStack(mol, self.app().undo) self.updateUndoRedoCmdStack(mol, self.app().redo) mol._treeItems = {} del mol def updateUndoRedoCmdStack(self, molecule, command): # cmd is either undo or redo # remove all entries form the undo or redo command stack that contain the deleted molecule remove = [] for i, cmdlist in enumerate(command.cmdStack): # loop over undo/redo items in the stack. Each item is a tuple containing a list of # commands to execute an undo/redo action and a string describing the action: # ( [ (cmd, (args,) {kw}), (cmd, (args,) {kw}), ... ], "undo/redo name" ) #import pdb; pdb.set_trace() newName = cmdlist[1].split(" ")[0] ncmds = len(cmdlist[0]) for j in xrange(len(cmdlist[0])-1, -1, -1): # loop backwards over the list of commands in undo/redo action cmd, args, kw = cmdlist[0][j] if len(args): newargs0 = [] # this list will contain updated atom selections newargs = [] # this list will contain other arguments that are not atomsets or molecules for arg in args: if isinstance(arg, list) and len(arg) and isinstance(arg[0], Molecule): mollist = [] for mol in arg: if mol != molecule: mollist.append(mol) if len(mollist): newargs0.append(MoleculeSet("molset", mollist)) elif isinstance(arg, Selection): if arg.getAtomGroup() != molecule._ag: newargs0.append(arg) elif isinstance(arg, Molecule): if arg == molecule: newargs0.append(arg) else: newargs.append(arg) if len(newargs0): cmdlist[0][j] = (cmd, tuple(newargs0+newargs), kw) name = self.getName(newargs0, kw) ind = name.find(" ") # "deleteMolecule " + "...." if ind and len(name)>ind+1: newName = newName+name[ind:] else: #remove this command from the list del cmdlist[0][j] if len(cmdlist[0]) == 0: remove.append(i) else: if ncmds != len(cmdlist[0]): command.cmdStack[i] = (cmdlist[0], newName) n = 0 for i in remove: command.cmdStack.pop(i-n) n = n+1 from AppFramework.notOptionalCommands import AfterUndoEvent event = AfterUndoEvent(objects=command.cmdStack, command=command) self.app().eventHandler.dispatchEvent(event) class DeleteAtoms(MVCommand): """ Command to remove an AtomSet from the MoleculeViewer \n Package : PmvApp \n Module : deleteCmds \n Class : DeleteAtoms \n Command : deleteAtoms \n Synopsis:\n None<---deleteAtoms(atoms)\n Required Arguments:\n atoms --- AtomSet to be deleted.\n """ def __init__(self): MVCommand.__init__(self) def onAddCmdToApp(self): if not self.app().commands.has_key('deleteMolecule'): self.app().lazyLoad("deleteCmds", commands=["deleteMolecule"], package="PmvApp") self.app().lazyLoad("selectionCmds", commands=[ "select", "clearSelection"], package="PmvApp") def checkArguments(self, selection): """None <- deleteAtoms(atoms) \n atoms: AtomSet to be deleted.""" assert selection return (selection,), {} def doit(self, selection): """ Function to delete all the references to each atom of a AtomSet.""" # Remove the atoms of the molecule you are deleting from the # the AtomSet self.app().allAtoms mol = selection.getAtomGroup().getMolecule() app = self.app() if len(selection)==len(mol._ag): app.deleteMolecule(mol) return # delete the atoms mol.deleteAtoms(selection) event = DeleteAtomsEvent(deletedAtoms=selection) self.app().eventHandler.dispatchEvent(event) event = RefreshDisplayEvent(molecule=mol) self.app().eventHandler.dispatchEvent(event) def updateUndoRedoCmdStack(self, oldAg, mol, indMap, command): remove = [] for i, cmdlist in enumerate(command.cmdStack): # loop over undo/redo items in the stack. Each item is a tuple containing a list of # commands to execute an undo/redo action and a string describing the action: # ( [ (cmd, (args,) {kw}), (cmd, (args,) {kw}), ... ], "undo/redo name" ) #import pdb; pdb.set_trace() cmdName = cmdlist[1].split(" ")[0]# name of the undo command without the string representing its arguments newName = "" ncmds = len(cmdlist[0]) for j in xrange(len(cmdlist[0])-1, -1, -1): # loop backwards over the list of commands in undo/redo action cmd, args, kw = cmdlist[0][j] if len(args): newargs0 = [] # this list will contain new atom selections newargs = [] # this list will contain arguments that are not Molecules ar atom selections for arg in args: if isinstance(arg, Selection): if arg.getAtomGroup() == oldAg: inds = arg.getIndices() import numpy _newinds = numpy.where(indMap[inds]> -1)[0] if len (_newinds): newinds = indMap[inds][_newinds] # create a selection string: stformat = "index " + "%s " *len(newinds) selstr = stformat%tuple(newinds) newAt = mol.select(selstr) newargs0.append(SelectionSet([newAt], "")) elif isinstance(arg, list) and isinstance(arg[0], Molecule): newargs0.append(arg) elif isinstance(arg, Molecule): newargs0.append(arg) else: newargs.append(arg) if len(newargs0): cmdlist[0][j] = (cmd, tuple(newargs0+newargs), kw) # create string representing selection. Can not use cmd.getName() # since cmd can be a commandLoader if newName == "": name = self.getName(newargs0, kw) #this returns "deleteAtoms " + "...." ind = name.find(" ") # get name after the " " if ind and len(name)>ind+1: newName = name[ind:] else: #remove this command from the list del cmdlist[0][j] if len(cmdlist[0]) == 0: remove.append(i) else: if newName != "": command.cmdStack[i] = (cmdlist[0], cmdName + " " + newName) n = 0 for i in remove: command.cmdStack.pop(i-n) n = n+1 from AppFramework.notOptionalCommands import AfterUndoEvent event = AfterUndoEvent(objects=command.cmdStack, command=command) self.app().eventHandler.dispatchEvent(event) class DeleteCurrentSelection(DeleteAtoms): """ Command to remove an AtomSet from the MoleculeViewer \n Package : PmvApp \n Module : deleteCmds \n Class : DeleteCurrentSelection \n Command : deleteCurrentSelection \n Synopsis:\n None<---deleteCurrentSelection()\n Required Arguments:\n None """ def checkArguments(self): """None <- deleteCurrentSelection() """ return (), {} def doit(self): """ Function to delete all the references to each atom of a the currentSelection.""" atoms = old = self.app().activeSelection.get()[:] # make copy of selection ats = self.app().expandNodes(atoms) if not len(ats): return ats = ats.findType(Atom) self.app().clearSelection(log=0) DeleteAtoms.doit(self, ats) class DeleteHydrogens(DeleteAtoms): """ Command to remove hydrogen atoms from the MoleculeViewer \n Package : PmvApp Module : deleteCmds \n Class : DeleteHydrogens \n Command : deleteHydrogens \n Synopsis:\n None<---deleteHydrogens(atoms)\n Required Arguments:\n atoms --- Hydrogens found in this atom set are deleted.\n """ def checkArguments(self, atoms): """None <- deleteHydrogents(atoms) \n atoms: set of atoms, from which hydrogens are to be deleted.""" if isinstance(atoms, str): self.nodeLogString = "'"+atoms+"'" ats = self.app().expandNodes(atoms) assert ats return (ats,), {} def doit(self, ats): hatoms = ats.get(lambda x: x.element=='H') if not len(hatoms): self.app().warningMsg("No hydrogens to delete.") return DeleteAtoms.doit(self, hatoms) commandClassFromName = { 'deleteMolecule' : [DeleteMolecule, None], 'deleteAtoms' : [DeleteAtoms, None ], #'deleteMolecules' : [DeleteMolecules, None], #'deleteAllMolecules' : [DeleteAllMolecules, None], #'deleteCurrentSelection' : [DeleteCurrentSelection, None ], #'deleteHydrogens' : [DeleteHydrogens, None], #'restoreMol' : [RestoreMolecule, None], } def initModule(viewer, gui=True): for cmdName, values in commandClassFromName.items(): cmdClass, guiInstance = values if gui: viewer.addCommand(cmdClass(), cmdName, guiInstance) else: viewer.addCommand(cmdClass(), cmdName, None)
8,091
0
200
f6abf36fab026dc8c66346673a0155293ab0a86a
2,053
py
Python
tests/integrations/test_fastapi.py
meadsteve/lagom
025993f42fa23547e333d81373523ced1baf4854
[ "MIT" ]
109
2019-06-02T13:40:38.000Z
2022-03-08T18:35:17.000Z
tests/integrations/test_fastapi.py
meadsteve/lagom
025993f42fa23547e333d81373523ced1baf4854
[ "MIT" ]
152
2019-06-03T11:54:13.000Z
2022-03-30T11:31:03.000Z
tests/integrations/test_fastapi.py
meadsteve/lagom
025993f42fa23547e333d81373523ced1baf4854
[ "MIT" ]
5
2020-02-05T09:44:12.000Z
2022-01-31T08:41:38.000Z
import pytest from starlette.testclient import TestClient from .fastapi_app import app, deps, Inner, ContextLoaded @pytest.fixture
30.641791
68
0.692645
import pytest from starlette.testclient import TestClient from .fastapi_app import app, deps, Inner, ContextLoaded def test_request_singletons_are_the_same_within_a_request_context(): client = TestClient(app) response = client.get("/") data = response.json() assert data["outer_one"] == data["outer_two"] def test_request_singletons_are_different_for_new_requests(): client = TestClient(app) data_one = client.get("/").json() data_two = client.get("/").json() assert data_one["outer_one"] != data_two["outer_one"] def test_deps_can_be_overridden_during_test(): client = TestClient(app) with deps.override_for_test() as c: c[Inner] = Inner("test_message") call_under_test = client.get("/inner").json() call_after_test = client.get("/inner").json() assert call_under_test["data"] == "test_message" assert call_after_test["data"] != "test_message" @pytest.fixture def fixture_fake_deps(): with deps.override_for_test() as test_container: test_container[Inner] = Inner("fixture_deps") yield test_container def test_overriding_with_fixtures_works(fixture_fake_deps): client = TestClient(app) resp = client.get("/inner").json() assert resp["data"] == "fixture_deps" def test_deps_can_be_overridden_during_test_multiple_times(): client = TestClient(app) with deps.override_for_test() as c1: with deps.override_for_test() as c2: c1[Inner] = Inner("first_level") c2[Inner] = Inner("second_level") second = client.get("/inner").json() first = client.get("/inner").json() outer = client.get("/inner").json() assert outer["data"] is None assert first["data"] == "first_level" assert second["data"] == "second_level" def test_deps_can_use_contexts_for_cleanup_tasks(): ContextLoaded.cleaned_up = False client = TestClient(app) response = client.get("with_some_context") assert response.json() == {"cleaned_up": "False"} assert ContextLoaded.cleaned_up
1,753
0
160
13ca52f0845f2699344120b85794e42025335b5a
421
py
Python
MapReduce_WordOccurence/reducer_WordOccurence.py
allendaniel1993/Data-Pipeline-Bigdata-Analysis-and-Data-Product
3b08311017dc9324c9eae5eec2c3a4bf5ecd60c1
[ "MIT" ]
null
null
null
MapReduce_WordOccurence/reducer_WordOccurence.py
allendaniel1993/Data-Pipeline-Bigdata-Analysis-and-Data-Product
3b08311017dc9324c9eae5eec2c3a4bf5ecd60c1
[ "MIT" ]
null
null
null
MapReduce_WordOccurence/reducer_WordOccurence.py
allendaniel1993/Data-Pipeline-Bigdata-Analysis-and-Data-Product
3b08311017dc9324c9eae5eec2c3a4bf5ecd60c1
[ "MIT" ]
null
null
null
#!/usr/bin/python # Allen Daniel Yesa # Aditya Subramanian Muralidaran import sys curr_key = None curr_val = 0 for key_val in sys.stdin: key,str_val = key_val.split("\t",1) try: val = int(str_val) except: continue if(curr_key==key): curr_val=curr_val+val; else: if(curr_key is not None): print(curr_key+"\t"+str(curr_val)) curr_key=key; curr_val=val; print(curr_key+"\t"+str(curr_val))
13.580645
37
0.679335
#!/usr/bin/python # Allen Daniel Yesa # Aditya Subramanian Muralidaran import sys curr_key = None curr_val = 0 for key_val in sys.stdin: key,str_val = key_val.split("\t",1) try: val = int(str_val) except: continue if(curr_key==key): curr_val=curr_val+val; else: if(curr_key is not None): print(curr_key+"\t"+str(curr_val)) curr_key=key; curr_val=val; print(curr_key+"\t"+str(curr_val))
0
0
0
e655ecc572f6e31570edbe354b4228217469c323
78
py
Python
haravan/resources/country.py
vivekpatel111/HaravanAPI
bec18d43b485c966e1396ce990c7b0fd40c96de0
[ "MIT" ]
null
null
null
haravan/resources/country.py
vivekpatel111/HaravanAPI
bec18d43b485c966e1396ce990c7b0fd40c96de0
[ "MIT" ]
null
null
null
haravan/resources/country.py
vivekpatel111/HaravanAPI
bec18d43b485c966e1396ce990c7b0fd40c96de0
[ "MIT" ]
1
2019-03-08T06:28:48.000Z
2019-03-08T06:28:48.000Z
from ..base import HaravanResource
13
34
0.769231
from ..base import HaravanResource class Country(HaravanResource): pass
0
19
23
bec8b9f8126e49a538afae87a8175e1c10752f3f
3,274
py
Python
provider/execution_context.py
elifesciences/elife-bot
d3a102c8030e4b7ec83cbd45e5f839dba4f9ffd9
[ "MIT" ]
17
2015-02-10T07:10:29.000Z
2021-05-14T22:24:45.000Z
provider/execution_context.py
elifesciences/elife-bot
d3a102c8030e4b7ec83cbd45e5f839dba4f9ffd9
[ "MIT" ]
459
2015-03-31T18:24:23.000Z
2022-03-30T19:44:40.000Z
provider/execution_context.py
elifesciences/elife-bot
d3a102c8030e4b7ec83cbd45e5f839dba4f9ffd9
[ "MIT" ]
9
2015-04-18T16:57:31.000Z
2020-10-30T11:49:13.000Z
from boto.s3.connection import S3Connection from boto.s3.key import Key from boto.exception import S3ResponseError from pydoc import locate import json import redis from provider.utils import unicode_encode # TODO : replace with better implementation - e.g. use Redis/Elasticache
29.763636
87
0.653635
from boto.s3.connection import S3Connection from boto.s3.key import Key from boto.exception import S3ResponseError from pydoc import locate import json import redis from provider.utils import unicode_encode def get_session(settings, input_data, session_key): settings_session_class = "RedisSession" # Default if hasattr(settings, "session_class"): settings_session_class = settings.session_class session_class = locate("provider.execution_context." + settings_session_class) return session_class(settings, input_data, session_key) class FileSession: # TODO : replace with better implementation - e.g. use Redis/Elasticache def __init__(self, settings, input_data, session_key): self.settings = settings self.input_data = input_data self.session_key = session_key def store_value(self, key, value): value = json.dumps(value) f = open(self.settings.workflow_context_path + self.get_full_key(key), "w") f.write(value) def get_value(self, key): value = None try: f = open(self.settings.workflow_context_path + self.get_full_key(key), "r") value = json.loads(f.readline()) except: if self.input_data is not None and key in self.input_data: value = self.input_data[key] return value def get_full_key(self, key): return self.session_key + "__" + key class RedisSession: def __init__(self, settings, input_data, session_key): self.input_data = input_data self.expire_key = settings.redis_expire_key self.session_key = session_key self.r = redis.StrictRedis( host=settings.redis_host, port=settings.redis_port, db=settings.redis_db ) def store_value(self, key, value): value = json.dumps(value) self.r.hset(self.session_key, key, value) self.r.expire(self.session_key, self.expire_key) def get_value(self, key): value = self.r.hget(self.session_key, key) if value is None: if key in self.input_data: value = self.input_data[key] else: value = json.loads(value) return value class S3Session: def __init__(self, settings, input_data, session_key): self.input_data = input_data self.conn = S3Connection( settings.aws_access_key_id, settings.aws_secret_access_key ) self.bucket = self.conn.get_bucket(settings.s3_session_bucket) self.session_key = session_key def store_value(self, key, value): value = json.dumps(value) s3_key = Key(self.bucket) s3_key.key = self.get_full_key(key) s3_key.set_contents_from_string(str(value)) def get_value(self, key): s3_key = Key(self.bucket) s3_key.key = self.get_full_key(key) value = None try: value = s3_key.get_contents_as_string() value = json.loads(unicode_encode(value)) except S3ResponseError: if self.input_data is not None and key in self.input_data: value = self.input_data[key] return value def get_full_key(self, key): return self.session_key + "/" + key
2,608
-10
387
641048b7ee5b4154f532187dc6c902516b5fdc15
2,632
py
Python
third-party/llvm/llvm-src/utils/lint/common_lint.py
jhh67/chapel
f041470e9b88b5fc4914c75aa5a37efcb46aa08f
[ "ECL-2.0", "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
third-party/llvm/llvm-src/utils/lint/common_lint.py
jhh67/chapel
f041470e9b88b5fc4914c75aa5a37efcb46aa08f
[ "ECL-2.0", "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
third-party/llvm/llvm-src/utils/lint/common_lint.py
jhh67/chapel
f041470e9b88b5fc4914c75aa5a37efcb46aa08f
[ "ECL-2.0", "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
#!/usr/bin/env python # # Common lint functions applicable to multiple types of files. from __future__ import print_function import re def VerifyLineLength(filename, lines, max_length): """Checks to make sure the file has no lines with lines exceeding the length limit. Args: filename: the file under consideration as string lines: contents of the file as string array max_length: maximum acceptable line length as number Returns: A list of tuples with format [(filename, line number, msg), ...] with any violations found. """ lint = [] line_num = 1 for line in lines: length = len(line.rstrip('\n')) if length > max_length: lint.append((filename, line_num, 'Line exceeds %d chars (%d)' % (max_length, length))) line_num += 1 return lint def VerifyTabs(filename, lines): """Checks to make sure the file has no tab characters. Args: filename: the file under consideration as string lines: contents of the file as string array Returns: A list of tuples with format [(line_number, msg), ...] with any violations found. """ lint = [] tab_re = re.compile(r'\t') line_num = 1 for line in lines: if tab_re.match(line.rstrip('\n')): lint.append((filename, line_num, 'Tab found instead of whitespace')) line_num += 1 return lint def VerifyTrailingWhitespace(filename, lines): """Checks to make sure the file has no lines with trailing whitespace. Args: filename: the file under consideration as string lines: contents of the file as string array Returns: A list of tuples with format [(filename, line number, msg), ...] with any violations found. """ lint = [] trailing_whitespace_re = re.compile(r'\s+$') line_num = 1 for line in lines: if trailing_whitespace_re.match(line.rstrip('\n')): lint.append((filename, line_num, 'Trailing whitespace')) line_num += 1 return lint def RunLintOverAllFiles(linter, filenames): """Runs linter over the contents of all files. Args: lint: subclass of BaseLint, implementing RunOnFile() filenames: list of all files whose contents will be linted Returns: A list of tuples with format [(filename, line number, msg), ...] with any violations found. """ lint = [] for filename in filenames: file = open(filename, 'r') if not file: print('Cound not open %s' % filename) continue lines = file.readlines() lint.extend(linter.RunOnFile(filename, lines)) return lint
26.585859
78
0.678951
#!/usr/bin/env python # # Common lint functions applicable to multiple types of files. from __future__ import print_function import re def VerifyLineLength(filename, lines, max_length): """Checks to make sure the file has no lines with lines exceeding the length limit. Args: filename: the file under consideration as string lines: contents of the file as string array max_length: maximum acceptable line length as number Returns: A list of tuples with format [(filename, line number, msg), ...] with any violations found. """ lint = [] line_num = 1 for line in lines: length = len(line.rstrip('\n')) if length > max_length: lint.append((filename, line_num, 'Line exceeds %d chars (%d)' % (max_length, length))) line_num += 1 return lint def VerifyTabs(filename, lines): """Checks to make sure the file has no tab characters. Args: filename: the file under consideration as string lines: contents of the file as string array Returns: A list of tuples with format [(line_number, msg), ...] with any violations found. """ lint = [] tab_re = re.compile(r'\t') line_num = 1 for line in lines: if tab_re.match(line.rstrip('\n')): lint.append((filename, line_num, 'Tab found instead of whitespace')) line_num += 1 return lint def VerifyTrailingWhitespace(filename, lines): """Checks to make sure the file has no lines with trailing whitespace. Args: filename: the file under consideration as string lines: contents of the file as string array Returns: A list of tuples with format [(filename, line number, msg), ...] with any violations found. """ lint = [] trailing_whitespace_re = re.compile(r'\s+$') line_num = 1 for line in lines: if trailing_whitespace_re.match(line.rstrip('\n')): lint.append((filename, line_num, 'Trailing whitespace')) line_num += 1 return lint class BaseLint: def RunOnFile(filename, lines): raise Exception('RunOnFile() unimplemented') def RunLintOverAllFiles(linter, filenames): """Runs linter over the contents of all files. Args: lint: subclass of BaseLint, implementing RunOnFile() filenames: list of all files whose contents will be linted Returns: A list of tuples with format [(filename, line number, msg), ...] with any violations found. """ lint = [] for filename in filenames: file = open(filename, 'r') if not file: print('Cound not open %s' % filename) continue lines = file.readlines() lint.extend(linter.RunOnFile(filename, lines)) return lint
59
-6
47
dbf0aa6f0035f2a4bbcaa8ab366fe3cf0e95ae17
3,742
py
Python
ProgrammingLanguages/Python/UsefulScripts/doc_docx_pdf_txt_converter.py
ldsands/UsefulCodeSnippits
69d578c163e6912d1b960b606a8fd80c2c059427
[ "MIT" ]
null
null
null
ProgrammingLanguages/Python/UsefulScripts/doc_docx_pdf_txt_converter.py
ldsands/UsefulCodeSnippits
69d578c163e6912d1b960b606a8fd80c2c059427
[ "MIT" ]
2
2020-03-17T21:45:41.000Z
2020-11-27T18:51:26.000Z
ProgrammingLanguages/Python/UsefulScripts/doc_docx_pdf_txt_converter.py
ldsands/UsefulCodeSnippits
69d578c163e6912d1b960b606a8fd80c2c059427
[ "MIT" ]
null
null
null
# pip install pdfminer.six docx2txt # to install win32com use the pywin32install.py script import shutil import sys from pathlib import Path from pprint import pprint import docx2txt from pdfminer.high_level import extract_text if sys.platform == "win32": import win32com.client as win32 from win32com.client import constants filenames, parent_path = collect_all_document_files() convert_to_txt(parent_path)
39.389474
264
0.621593
# pip install pdfminer.six docx2txt # to install win32com use the pywin32install.py script import shutil import sys from pathlib import Path from pprint import pprint import docx2txt from pdfminer.high_level import extract_text if sys.platform == "win32": import win32com.client as win32 from win32com.client import constants def collect_all_document_files(): path = Path(__file__).parent.resolve() files = list(path.glob("*")) files = [file for file in files if file.suffix in [".doc", ".docx", ".pdf"]] return files, path def convert_doc_to_docx(file, text_directory): # Opening MS Word # print(f"{file.name} converting from doc to docx") # TESTCODE: word = win32.gencache.EnsureDispatch("Word.Application") doc = word.Documents.Open(str(file)) doc.Activate() new_path = file.parent / f"{file.stem}.docx" word.ActiveDocument.SaveAs(str(new_path), FileFormat=constants.wdFormatXMLDocument) doc.Close(False) # print("Finished docx conversion") # TESTCODE: return new_path def convert_docx_to_txt(file, text_directory): try: text = docx2txt.process(file) text = text.replace("\t", "") file_txt = text_directory / f"{file.stem}.txt" file_txt.touch() with open(file_txt, "w", encoding="utf-8") as file: file.write(text) except KeyError: print( f"The file {file.name} could not be converted. \n Option 1: Open this in word and save again. \n Option 2: Copy everything from the document having issues and paste it into a new word document. Save that document as a new file." ) def convert_to_txt(parent_path): text_directory = parent_path / "converted_text_files" text_directory.mkdir(parents=True, exist_ok=True) files = list(parent_path.glob("*")) # files = files[0:30] # TESTCODE: for file in files: if file.suffix == ".docx": convert_docx_to_txt(file, text_directory) elif file.suffix == ".doc": if sys.platform == "win32": try: docx_path = convert_doc_to_docx(file, text_directory) convert_docx_to_txt(docx_path, text_directory) except AttributeError: import win32com print( f"""There was an issue while converting a .doc document. To help with this issue do the following: navigate to this location {win32com.__gen_path__} and delete any folders that are contained inside then run the script again""" ) except: print( f"{file.name} encountered an error while trying to convert the file to docx. You can try and open this file manually in Microsoft Word and then save as a .docx file then you can run the script again to convert this file to a text document." ) else: print( f".doc files cannot be converted unless you are using Windows. {file.name} will not be converted" ) elif file.suffix == ".pdf": text = extract_text(str(file)) if len(text.strip()) == 0: print(f"{file.name} has no text in the pdf and was probably scanned") else: file_txt = text_directory / f"{file.stem}.txt" file_txt.touch() with open(file_txt, "w", encoding="utf-8") as file: file.write(text) # else: # TESTCODE: # print(f"{file.name} is not a .doc, .docx, or .pdf file. It will not be converted.") filenames, parent_path = collect_all_document_files() convert_to_txt(parent_path)
3,224
0
92
4dc30f46f6281aa719bfe6afc4b5aa02e7ee3395
5,243
py
Python
earth_enterprise/src/fusion/portableglobe/servers/portable_server_base.py
ezeeyahoo/earthenterprise
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
[ "Apache-2.0" ]
2,661
2017-03-20T22:12:50.000Z
2022-03-30T09:43:19.000Z
earth_enterprise/src/fusion/portableglobe/servers/portable_server_base.py
ezeeyahoo/earthenterprise
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
[ "Apache-2.0" ]
1,531
2017-03-24T17:20:32.000Z
2022-03-16T18:11:14.000Z
earth_enterprise/src/fusion/portableglobe/servers/portable_server_base.py
ezeeyahoo/earthenterprise
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
[ "Apache-2.0" ]
990
2017-03-24T11:54:28.000Z
2022-03-22T11:51:47.000Z
#!/usr/bin/env python2.7 # # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Base class for the handlers used in the portable server.""" import os import sys import traceback import tornado.web import portable_globe class BaseHandler(tornado.web.RequestHandler): """Historically, the base class for local and remote servers. Remote servers are no longer supported. """ def WriteFile(self, path): """Return a simple file as content.""" # If local override is on, return the local file if it exists. if (tornado.web.globe_.config_.LocalOverride() and os.path.isfile("./local/%s" % path)): print "Using local file:", path return self.WriteLocalFile(path) # Write the file from the package. try: self.write(tornado.web.globe_.ReadFile(path)) return True except portable_globe.UnableToFindException as e: return False def WriteLocalFile(self, path): """Return a simple local file as content.""" path = path.replace("..", "__") # Write the file from the package. try: fp = open("./local/%s" % path, "rb") self.write(fp.read()) fp.close() return True except portable_globe.UnableToFindException as e: print e.message return False def ShowUri(self, host): """Show the uri that was requested.""" # Comment out next line to increase performance. if tornado.web.globe_.config_.Debug(): print "Host: %s Request: %s" % (host, self.request.uri) def IsLocalhost(self): """Checks if request is from localhost.""" host = self.request.headers["Host"] try: (server, server_port) = host.split(":") except: server = host # Accept localhost requests if server == "localhost" or server == "127.0.0.1": return True return False def IsValidLocalRequest(self): """Make sure that the request looks good before processing. Returns: Whether request should be processed. """ host = self.request.headers["Host"] try: (caller_host, _) = host.split(":") except: caller_host = host # Accept all localhost requests if caller_host == "localhost" or caller_host == "127.0.0.1": self.ShowUri(host) return True return False def IsValidRequest(self): """Makes sure that the request looks valid. Returns: Whether request should be processed. """ return self.IsBroadcasting() or self.IsValidLocalRequest() class LocalDocsHandler(BaseHandler): """Class for returning the content of files directly from disk.""" def get(self, path): """Handle GET request for some local file. For example it is used for setup pages. Args: path: Path to file to be returned. """ if not self.IsValidRequest(): raise tornado.web.HTTPError(404) if path[-3:].lower() == "gif": self.set_header("Content-Type", "image/gif") elif path[-3:].lower() == "png": self.set_header("Content-Type", "image/png") elif path[-3:].lower() == "css": self.set_header("Content-Type", "text/css") else: self.set_header("Content-Type", "text/html") self.WriteLocalFile(path) class ExtHandler(BaseHandler): """Class for passing control to externally defined routines.""" def get(self, path): """Handle GET request for some external request. Args: path: Path relative to the ext directory. """ try: tornado.web.local_server_.ext_service_.ExtGetHandler(self, path) except: if self.get_argument("debug", "") or tornado.web.globe_.config_.Debug(): e = sys.exc_info() self.set_header("Content-Type", "text/html") self.write("<pre>%s</pre>" % "".join( traceback.format_exception(e[0], e[1], e[2]) )) else: self.set_header("Content-Type", "text/html") self.write("GET service failed or is undefined.") def post(self, path): """Handle POST request for some external request. Args: path: Path relative to the ext directory. """ try: tornado.web.local_server_.ext_service_.ExtPostHandler(self, path) except: if self.get_argument("debug", "") or tornado.web.globe_.config_.Debug(): e = sys.exc_info() self.set_header("Content-Type", "text/html") self.write("<pre>%s</pre>" % "".join( traceback.format_exception(e[0], e[1], e[2]) )) else: self.set_header("Content-Type", "text/html") self.write("POST service failed or is undefined.")
28.340541
78
0.651726
#!/usr/bin/env python2.7 # # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Base class for the handlers used in the portable server.""" import os import sys import traceback import tornado.web import portable_globe class BaseHandler(tornado.web.RequestHandler): """Historically, the base class for local and remote servers. Remote servers are no longer supported. """ def WriteFile(self, path): """Return a simple file as content.""" # If local override is on, return the local file if it exists. if (tornado.web.globe_.config_.LocalOverride() and os.path.isfile("./local/%s" % path)): print "Using local file:", path return self.WriteLocalFile(path) # Write the file from the package. try: self.write(tornado.web.globe_.ReadFile(path)) return True except portable_globe.UnableToFindException as e: return False def WriteLocalFile(self, path): """Return a simple local file as content.""" path = path.replace("..", "__") # Write the file from the package. try: fp = open("./local/%s" % path, "rb") self.write(fp.read()) fp.close() return True except portable_globe.UnableToFindException as e: print e.message return False def ShowUri(self, host): """Show the uri that was requested.""" # Comment out next line to increase performance. if tornado.web.globe_.config_.Debug(): print "Host: %s Request: %s" % (host, self.request.uri) def IsLocalhost(self): """Checks if request is from localhost.""" host = self.request.headers["Host"] try: (server, server_port) = host.split(":") except: server = host # Accept localhost requests if server == "localhost" or server == "127.0.0.1": return True return False def IsValidLocalRequest(self): """Make sure that the request looks good before processing. Returns: Whether request should be processed. """ host = self.request.headers["Host"] try: (caller_host, _) = host.split(":") except: caller_host = host # Accept all localhost requests if caller_host == "localhost" or caller_host == "127.0.0.1": self.ShowUri(host) return True return False def IsBroadcasting(self): return (not tornado.web.globe_.config_.disable_broadcasting_ and tornado.web.globe_.config_.accept_all_requests_) def IsValidRequest(self): """Makes sure that the request looks valid. Returns: Whether request should be processed. """ return self.IsBroadcasting() or self.IsValidLocalRequest() class LocalDocsHandler(BaseHandler): """Class for returning the content of files directly from disk.""" def get(self, path): """Handle GET request for some local file. For example it is used for setup pages. Args: path: Path to file to be returned. """ if not self.IsValidRequest(): raise tornado.web.HTTPError(404) if path[-3:].lower() == "gif": self.set_header("Content-Type", "image/gif") elif path[-3:].lower() == "png": self.set_header("Content-Type", "image/png") elif path[-3:].lower() == "css": self.set_header("Content-Type", "text/css") else: self.set_header("Content-Type", "text/html") self.WriteLocalFile(path) class ExtHandler(BaseHandler): """Class for passing control to externally defined routines.""" def get(self, path): """Handle GET request for some external request. Args: path: Path relative to the ext directory. """ try: tornado.web.local_server_.ext_service_.ExtGetHandler(self, path) except: if self.get_argument("debug", "") or tornado.web.globe_.config_.Debug(): e = sys.exc_info() self.set_header("Content-Type", "text/html") self.write("<pre>%s</pre>" % "".join( traceback.format_exception(e[0], e[1], e[2]) )) else: self.set_header("Content-Type", "text/html") self.write("GET service failed or is undefined.") def post(self, path): """Handle POST request for some external request. Args: path: Path relative to the ext directory. """ try: tornado.web.local_server_.ext_service_.ExtPostHandler(self, path) except: if self.get_argument("debug", "") or tornado.web.globe_.config_.Debug(): e = sys.exc_info() self.set_header("Content-Type", "text/html") self.write("<pre>%s</pre>" % "".join( traceback.format_exception(e[0], e[1], e[2]) )) else: self.set_header("Content-Type", "text/html") self.write("POST service failed or is undefined.")
134
0
25
e0533f32c2ede3632169eeba54908e1eda97b429
718
py
Python
Scripts/start.py
sporiyano/graphiti
56d85e5262b76dc6ce4f213a4d80486e015de1b7
[ "BSD-2-Clause" ]
93
2015-01-01T17:49:53.000Z
2022-02-24T21:25:15.000Z
Scripts/start.py
sporiyano/graphiti
56d85e5262b76dc6ce4f213a4d80486e015de1b7
[ "BSD-2-Clause" ]
13
2015-03-30T18:01:05.000Z
2018-05-28T03:47:33.000Z
Scripts/start.py
ThibaultReuille/graphiti
56d85e5262b76dc6ce4f213a4d80486e015de1b7
[ "BSD-2-Clause" ]
31
2015-01-14T12:16:13.000Z
2022-02-24T21:25:16.000Z
import sys sys.path.insert(0, "./") import os from Scripts import * if __name__ == "__main__": if len(sys.argv) <= 1: usage() else: module = "Scripts." + sys.argv[1] if module in sys.modules: sys.modules[module].start() else: print("No module named {}".format("Scripts." + sys.argv[1])) usage()
25.642857
72
0.513928
import sys sys.path.insert(0, "./") import os from Scripts import * def usage(): exclude = ['__init__.py', 'start.py', 'standard.py'] print("") print("Usage: " + sys.argv[0] + " <view>") print(" Available views : {}".format( " ".join([file.split('.')[0] for file in os.listdir('Scripts') if file.split('.')[-1] == "py" and file not in exclude]))) print("") if __name__ == "__main__": if len(sys.argv) <= 1: usage() else: module = "Scripts." + sys.argv[1] if module in sys.modules: sys.modules[module].start() else: print("No module named {}".format("Scripts." + sys.argv[1])) usage()
321
0
23
078cd45b4695b13f5ab288c33e4c06fbd0040f24
74,995
py
Python
lib/python/treadmill/tests/scheduler_test.py
krcooke/treadmill
613008fee88a150f983ab12d8ef2e118fb77bb51
[ "Apache-2.0" ]
133
2016-09-15T13:36:12.000Z
2021-01-18T06:29:13.000Z
lib/python/treadmill/tests/scheduler_test.py
krcooke/treadmill
613008fee88a150f983ab12d8ef2e118fb77bb51
[ "Apache-2.0" ]
108
2016-12-28T23:41:27.000Z
2020-03-05T21:20:37.000Z
lib/python/treadmill/tests/scheduler_test.py
krcooke/treadmill
613008fee88a150f983ab12d8ef2e118fb77bb51
[ "Apache-2.0" ]
69
2016-09-23T20:38:58.000Z
2020-11-11T02:31:21.000Z
"""Unit test for treadmill.scheduler. """ # Disable too many lines in module warning. # # pylint: disable=C0302 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import datetime import itertools import sys import time import unittest import mock import numpy as np import six # Disable W0611: Unused import import treadmill.tests.treadmill_test_skip_windows # pylint: disable=W0611 from treadmill import scheduler from treadmill import utils _TRAITS = dict() # Helper functions to convert user readable traits to bit mask. def app_list(count, name, *args, **kwargs): """Return list of apps.""" return [scheduler.Application(name + '-' + str(idx), *args, affinity=name, **kwargs) for idx in range(0, count)] class OpsTest(unittest.TestCase): """Test comparison operators.""" # Disable warning accessing protected members. # # pylint: disable=W0212 def test_ops(self): """Test comparison operators.""" self.assertTrue(scheduler._all_gt([3, 3], [2, 2])) self.assertTrue(scheduler._any_gt([3, 2], [2, 2])) self.assertFalse(scheduler._all_gt([3, 2], [2, 2])) self.assertTrue(scheduler._all_lt([2, 2], [3, 3])) class AllocationTest(unittest.TestCase): """treadmill.scheduler.Allocation tests.""" def test_utilization(self): """Test utilization calculation.""" alloc = scheduler.Allocation([10, 10]) alloc.add(scheduler.Application('app1', 100, [1, 1], 'app1')) alloc.add(scheduler.Application('app2', 100, [2, 2], 'app1')) alloc.add(scheduler.Application('app3', 100, [3, 3], 'app1')) # First element is rank. util_q = list(alloc.utilization_queue([20, 20])) self.assertEqual(100, util_q[0][0]) self.assertEqual(100, util_q[1][0]) self.assertEqual(100, util_q[2][0]) # Second and third elememts is before / after utilization. self.assertEqual(-10 / (10. + 20), util_q[0][1]) self.assertEqual(-9 / (10. + 20), util_q[0][2]) self.assertEqual(-7 / (10. + 20), util_q[1][2]) self.assertEqual(-9 / (10. + 20), util_q[1][1]) self.assertEqual(-4 / (10. + 20), util_q[2][2]) self.assertEqual(-7 / (10. + 20), util_q[2][1]) # Applications are sorted by priority. alloc = scheduler.Allocation([10, 10]) alloc.add(scheduler.Application('app1', 10, [1, 1], 'app1')) alloc.add(scheduler.Application('app2', 50, [2, 2], 'app1')) alloc.add(scheduler.Application('app3', 100, [3, 3], 'app1')) util_q = list(alloc.utilization_queue([20., 20.])) self.assertEqual(-10 / (10. + 20), util_q[0][1]) self.assertEqual(-7 / (10. + 20), util_q[0][2]) self.assertEqual(-7 / (10. + 20), util_q[1][1]) self.assertEqual(-5 / (10. + 20), util_q[1][2]) self.assertEqual(-5 / (10. + 20), util_q[2][1]) self.assertEqual(-4 / (10. + 20), util_q[2][2]) def test_running_order(self): """Test apps are ordered by status (running first) for same prio.""" alloc = scheduler.Allocation([10, 10]) alloc.add(scheduler.Application('app1', 5, [1, 1], 'app1')) alloc.add(scheduler.Application('app2', 5, [2, 2], 'app1')) alloc.add(scheduler.Application('app3', 5, [3, 3], 'app1')) queue = list(alloc.utilization_queue([20., 20.])) self.assertEqual(alloc.apps['app1'], queue[0][-1]) alloc.apps['app2'].server = 'abc' queue = list(alloc.utilization_queue([20., 20.])) self.assertEqual(alloc.apps['app2'], queue[0][-1]) def test_utilization_max(self): """Tests max utilization cap on the allocation.""" alloc = scheduler.Allocation([3, 3]) alloc.add(scheduler.Application('app1', 1, [1, 1], 'app1')) alloc.add(scheduler.Application('app2', 1, [2, 2], 'app1')) alloc.add(scheduler.Application('app3', 1, [3, 3], 'app1')) self.assertEqual(3, len(list(alloc.utilization_queue([20., 20.])))) # Now set max_utilization to 1 alloc.max_utilization = 1 # XXX: Broken test. Needs upgrade to V3 # XXX: # XXX: self.assertEqual( # XXX: 2, # XXX: len(list(alloc.utilization_queue([20., 20.]))) # XXX: ) alloc.set_max_utilization(None) self.assertEqual(3, len(list(alloc.utilization_queue([20., 20.])))) def test_priority_zero(self): """Tests priority zero apps.""" alloc = scheduler.Allocation([3, 3]) alloc.add(scheduler.Application('app1', 1, [1, 1], 'app1')) alloc.add(scheduler.Application('app2', 0, [2, 2], 'app1')) # default max_utilization still lets prio 0 apps through queue = alloc.utilization_queue([20., 20.]) self.assertEqual([100, 100], [item[0] for item in queue]) alloc.set_max_utilization(100) # setting max_utilization will cut off prio 0 apps queue = alloc.utilization_queue([20., 20.]) self.assertEqual( [100, sys.maxsize], [item[0] for item in queue] ) def test_rank_adjustment(self): """Test rank adjustment""" alloc = scheduler.Allocation() alloc.update([3, 3], 100, 10) alloc.add(scheduler.Application('app1', 1, [1, 1], 'app1')) alloc.add(scheduler.Application('app2', 1, [2, 2], 'app1')) alloc.add(scheduler.Application('app3', 1, [3, 3], 'app1')) queue = list(alloc.utilization_queue([20., 20.])) self.assertEqual(90, queue[0][0]) self.assertEqual(90, queue[1][0]) self.assertEqual(100, queue[2][0]) def test_zerovector(self): """Test updating allocation with allocation vector containing 0's""" alloc = scheduler.Allocation(None) alloc.update([1, 0], None, None) self.assertEqual(1.0, alloc.reserved[0]) self.assertEqual(0, alloc.reserved[1]) def test_utilization_no_reservation(self): """Checks that any utilization without reservation is VERY large.""" alloc = scheduler.Allocation(None) alloc.add(scheduler.Application('app1', 1, [1., 1.], 'app1')) queue = list(alloc.utilization_queue(np.array([10., 10.]))) self.assertEqual(0 / 10, queue[0][1]) self.assertEqual(1 / 10, queue[0][2]) def test_duplicate(self): """Checks behavior when adding duplicate app.""" alloc = scheduler.Allocation(None) alloc.add(scheduler.Application('app1', 0, [1, 1], 'app1')) self.assertEqual( 1, len(list(alloc.utilization_queue(np.array([5., 5.]))))) alloc.add(scheduler.Application('app1', 0, [1, 1], 'app1')) self.assertEqual( 1, len(list(alloc.utilization_queue(np.array([5., 5.]))))) def test_sub_allocs(self): """Test utilization calculation with sub-allocs.""" alloc = scheduler.Allocation([3, 3]) self.assertEqual(3, alloc.total_reserved()[0]) queue = list(alloc.utilization_queue([20., 20.])) sub_alloc_a = scheduler.Allocation([5, 5]) alloc.add_sub_alloc('a1/a', sub_alloc_a) self.assertEqual(8, alloc.total_reserved()[0]) sub_alloc_a.add(scheduler.Application('1a', 3, [2, 2], 'app1')) sub_alloc_a.add(scheduler.Application('2a', 2, [3, 3], 'app1')) sub_alloc_a.add(scheduler.Application('3a', 1, [5, 5], 'app1')) queue = list(alloc.utilization_queue([20., 20.])) _rank, _util_b, util_a, _pending, _order, app = queue[0] self.assertEqual('1a', app.name) self.assertEqual((2 - (5 + 3)) / (20 + (5 + 3)), util_a) sub_alloc_b = scheduler.Allocation([10, 10]) alloc.add_sub_alloc('a1/b', sub_alloc_b) sub_alloc_b.add(scheduler.Application('1b', 3, [2, 2], 'app1')) sub_alloc_b.add(scheduler.Application('2b', 2, [3, 3], 'app1')) sub_alloc_b.add(scheduler.Application('3b', 1, [5, 5], 'app1')) queue = list(alloc.utilization_queue([20., 20.])) self.assertEqual(6, len(queue)) self.assertEqual(18, alloc.total_reserved()[0]) # For each sub-alloc (and self) the least utilized app is 1. # The sub_allloc_b is largest, so utilization smallest, 1b will be # first. _rank, _util_b, util_a, _pending, _order, app = queue[0] self.assertEqual('1b', app.name) self.assertEqual((2 - 18) / (20 + 18), util_a) # Add prio 0 app to each, make sure they all end up last. alloc.add(scheduler.Application('1-zero', 0, [2, 2], 'app1')) sub_alloc_b.add(scheduler.Application('b-zero', 0, [5, 5], 'app1')) sub_alloc_a.add(scheduler.Application('a-zero', 0, [5, 5], 'app1')) queue = list(alloc.utilization_queue([20., 20.])) self.assertIn('1-zero', [item[-1].name for item in queue[-3:]]) self.assertIn('a-zero', [item[-1].name for item in queue[-3:]]) self.assertIn('b-zero', [item[-1].name for item in queue[-3:]]) # Check that utilization of prio 0 apps is always max float. self.assertEqual( [float('inf')] * 3, [ util_b for (_rank, util_b, _util_a, _pending, _order, _app) in queue[-3:] ] ) def test_sub_alloc_reservation(self): """Test utilization calculation is fair between sub-allocs.""" alloc = scheduler.Allocation() sub_alloc_poor = scheduler.Allocation() alloc.add_sub_alloc('poor', sub_alloc_poor) sub_alloc_poor.add(scheduler.Application('p1', 1, [1, 1], 'app1')) sub_alloc_rich = scheduler.Allocation([5, 5]) sub_alloc_rich.add(scheduler.Application('r1', 1, [5, 5], 'app1')) sub_alloc_rich.add(scheduler.Application('r2', 1, [5, 5], 'app1')) alloc.add_sub_alloc('rich', sub_alloc_rich) queue = list(alloc.utilization_queue([20., 20.])) self.assertEqual('r1', queue[0][-1].name) self.assertEqual('p1', queue[1][-1].name) self.assertEqual('r2', queue[2][-1].name) def test_visitor(self): """Test queue visitor""" alloc = scheduler.Allocation() sub_alloc_a = scheduler.Allocation() sub_alloc_a.add(scheduler.Application('a1', 1, [1, 1], 'app1')) alloc.add_sub_alloc('a', sub_alloc_a) sub_alloc_b = scheduler.Allocation() sub_alloc_b.add(scheduler.Application('b1', 1, [5, 5], 'app1')) sub_alloc_b.add(scheduler.Application('b2', 1, [5, 5], 'app1')) alloc.add_sub_alloc('b', sub_alloc_b) result = [] list(alloc.utilization_queue([20., 20.], visitor=_visitor)) self.assertEqual(6, len(result)) class TraitSetTest(unittest.TestCase): """treadmill.scheduler.TraitSet tests.""" def test_traits(self): """Test trait inheritance.""" trait_a = int('0b0000001', 2) trait_x = int('0b0000100', 2) trait_y = int('0b0001000', 2) trait_z = int('0b0010000', 2) fset_a = scheduler.TraitSet(trait_a) fset_xz = scheduler.TraitSet(trait_x | trait_z) fset_xy = scheduler.TraitSet(trait_x | trait_y) self.assertTrue(fset_a.has(trait_a)) fset_a.add('xy', fset_xy.traits) self.assertTrue(fset_a.has(trait_a)) self.assertTrue(fset_a.has(trait_x)) self.assertTrue(fset_a.has(trait_y)) fset_a.add('xz', fset_xz.traits) self.assertTrue(fset_a.has(trait_x)) self.assertTrue(fset_a.has(trait_y)) self.assertTrue(fset_a.has(trait_z)) fset_a.remove('xy') self.assertTrue(fset_a.has(trait_x)) self.assertFalse(fset_a.has(trait_y)) self.assertTrue(fset_a.has(trait_z)) fset_a.remove('xz') self.assertFalse(fset_a.has(trait_x)) self.assertFalse(fset_a.has(trait_y)) self.assertFalse(fset_a.has(trait_z)) class NodeTest(unittest.TestCase): """treadmill.scheduler.Allocation tests.""" def test_bucket_capacity(self): """Tests adjustment of bucket capacity up and down.""" parent = scheduler.Bucket('top') bucket = scheduler.Bucket('b') parent.add_node(bucket) srv1 = scheduler.Server('n1', [10, 5], valid_until=500) bucket.add_node(srv1) self.assertTrue(np.array_equal(bucket.free_capacity, np.array([10., 5.]))) self.assertTrue(np.array_equal(parent.free_capacity, np.array([10., 5.]))) srv2 = scheduler.Server('n2', [5, 10], valid_until=500) bucket.add_node(srv2) self.assertTrue(np.array_equal(bucket.free_capacity, np.array([10., 10.]))) self.assertTrue(np.array_equal(parent.free_capacity, np.array([10., 10.]))) srv3 = scheduler.Server('n3', [3, 3], valid_until=500) bucket.add_node(srv3) self.assertTrue(np.array_equal(bucket.free_capacity, np.array([10., 10.]))) self.assertTrue(np.array_equal(parent.free_capacity, np.array([10., 10.]))) bucket.remove_node_by_name('n3') self.assertTrue(np.array_equal(bucket.free_capacity, np.array([10., 10.]))) self.assertTrue(np.array_equal(parent.free_capacity, np.array([10., 10.]))) bucket.remove_node_by_name('n1') self.assertTrue(np.array_equal(bucket.free_capacity, np.array([5., 10.]))) self.assertTrue(np.array_equal(parent.free_capacity, np.array([5., 10.]))) def test_app_node_placement(self): """Tests capacity adjustments for app placement.""" parent = scheduler.Bucket('top') bucket = scheduler.Bucket('a_bucket') parent.add_node(bucket) srv1 = scheduler.Server('n1', [10, 5], valid_until=500) bucket.add_node(srv1) srv2 = scheduler.Server('n2', [10, 5], valid_until=500) bucket.add_node(srv2) self.assertTrue(np.array_equal(bucket.free_capacity, np.array([10., 5.]))) self.assertTrue(np.array_equal(parent.free_capacity, np.array([10., 5.]))) self.assertTrue(np.array_equal(bucket.size(None), np.array([20., 10.]))) # Create 10 identical apps. apps = app_list(10, 'app', 50, [1, 2]) self.assertTrue(srv1.put(apps[0])) # Capacity of buckets should not change, other node is intact. self.assertTrue(np.array_equal(bucket.free_capacity, np.array([10., 5.]))) self.assertTrue(np.array_equal(parent.free_capacity, np.array([10., 5.]))) self.assertTrue(srv1.put(apps[1])) self.assertTrue(srv2.put(apps[2])) self.assertTrue(np.array_equal(bucket.free_capacity, np.array([9., 3.]))) self.assertTrue(np.array_equal(parent.free_capacity, np.array([9., 3.]))) def test_bucket_placement(self): """Tests placement strategies.""" top = scheduler.Bucket('top') a_bucket = scheduler.Bucket('a_bucket') top.add_node(a_bucket) b_bucket = scheduler.Bucket('b_bucket') top.add_node(b_bucket) a1_srv = scheduler.Server('a1_srv', [10, 10], valid_until=500) a_bucket.add_node(a1_srv) a2_srv = scheduler.Server('a2_srv', [10, 10], valid_until=500) a_bucket.add_node(a2_srv) b1_srv = scheduler.Server('b1_srv', [10, 10], valid_until=500) b_bucket.add_node(b1_srv) b2_srv = scheduler.Server('b2_srv', [10, 10], valid_until=500) b_bucket.add_node(b2_srv) # bunch of apps with the same affinity apps1 = app_list(10, 'app1', 50, [1, 1]) apps2 = app_list(10, 'app2', 50, [1, 1]) # Default strategy is spread, so placing 4 apps1 will result in each # node having one app. self.assertTrue(top.put(apps1[0])) self.assertTrue(top.put(apps1[1])) self.assertTrue(top.put(apps1[2])) self.assertTrue(top.put(apps1[3])) # from top level, it will spread between a and b buckets, so first # two apps go to a1_srv, b1_srv respectively. # # 3rd app - buckets rotate, and a bucket is preferred again. Inside the # bucket, next node is chosed. Same for 4th app. # # Result is the after 4 placements they are spread evenly. # self.assertEqual(1, len(a1_srv.apps)) self.assertEqual(1, len(a2_srv.apps)) self.assertEqual(1, len(b1_srv.apps)) self.assertEqual(1, len(b2_srv.apps)) a_bucket.set_affinity_strategy('app2', scheduler.PackStrategy) self.assertTrue(top.put(apps2[0])) self.assertTrue(top.put(apps2[1])) self.assertTrue(top.put(apps2[2])) self.assertTrue(top.put(apps2[3])) # B bucket still uses spread strategy. self.assertEqual(2, len(b1_srv.apps)) self.assertEqual(2, len(b2_srv.apps)) # Without predicting exact placement, apps will be placed on one of # the servers in A bucket but not the other, as they use pack strateg. self.assertNotEqual(len(a1_srv.apps), len(a2_srv.apps)) def test_valid_times(self): """Tests node valid_until calculation.""" top = scheduler.Bucket('top', traits=_traits2int(['top'])) left = scheduler.Bucket('left', traits=_traits2int(['left'])) right = scheduler.Bucket('right', traits=_traits2int(['right'])) srv_a = scheduler.Server('a', [10, 10], traits=_traits2int(['a', '0']), valid_until=1) srv_b = scheduler.Server('b', [10, 10], traits=_traits2int(['b', '0']), valid_until=2) srv_y = scheduler.Server('y', [10, 10], traits=_traits2int(['y', '1']), valid_until=3) srv_z = scheduler.Server('z', [10, 10], traits=_traits2int(['z', '1']), valid_until=4) top.add_node(left) top.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) self.assertEqual(top.valid_until, 4) self.assertEqual(left.valid_until, 2) self.assertEqual(right.valid_until, 4) left.remove_node_by_name('a') self.assertEqual(top.valid_until, 4) self.assertEqual(left.valid_until, 2) self.assertEqual(right.valid_until, 4) right.remove_node_by_name('z') self.assertEqual(top.valid_until, 3) self.assertEqual(left.valid_until, 2) self.assertEqual(right.valid_until, 3) def test_node_traits(self): """Tests node trait inheritance.""" top = scheduler.Bucket('top', traits=_traits2int(['top'])) left = scheduler.Bucket('left', traits=_traits2int(['left'])) right = scheduler.Bucket('right', traits=_traits2int(['right'])) srv_a = scheduler.Server('a', [10, 10], traits=_traits2int(['a', '0']), valid_until=500) srv_b = scheduler.Server('b', [10, 10], traits=_traits2int(['b', '0']), valid_until=500) srv_y = scheduler.Server('y', [10, 10], traits=_traits2int(['y', '1']), valid_until=500) srv_z = scheduler.Server('z', [10, 10], traits=_traits2int(['z', '1']), valid_until=500) top.add_node(left) top.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) self.assertTrue(top.traits.has(_trait2int('a'))) self.assertTrue(top.traits.has(_trait2int('b'))) self.assertTrue(top.traits.has(_trait2int('0'))) self.assertTrue(top.traits.has(_trait2int('y'))) self.assertTrue(top.traits.has(_trait2int('z'))) self.assertTrue(top.traits.has(_trait2int('1'))) self.assertTrue(left.traits.has(_trait2int('a'))) self.assertTrue(left.traits.has(_trait2int('b'))) self.assertTrue(left.traits.has(_trait2int('0'))) self.assertFalse(left.traits.has(_trait2int('y'))) self.assertFalse(left.traits.has(_trait2int('z'))) self.assertFalse(left.traits.has(_trait2int('1'))) left.remove_node_by_name('a') self.assertFalse(left.traits.has(_trait2int('a'))) self.assertTrue(left.traits.has(_trait2int('b'))) self.assertTrue(left.traits.has(_trait2int('0'))) self.assertFalse(top.traits.has(_trait2int('a'))) self.assertTrue(top.traits.has(_trait2int('b'))) self.assertTrue(top.traits.has(_trait2int('0'))) left.remove_node_by_name('b') self.assertFalse(left.traits.has(_trait2int('b'))) self.assertFalse(left.traits.has(_trait2int('0'))) self.assertFalse(top.traits.has(_trait2int('b'))) self.assertFalse(top.traits.has(_trait2int('0'))) def test_app_trait_placement(self): """Tests placement of app with traits.""" top = scheduler.Bucket('top', traits=_traits2int(['top'])) left = scheduler.Bucket('left', traits=_traits2int(['left'])) right = scheduler.Bucket('right', traits=_traits2int(['right'])) srv_a = scheduler.Server('a', [10, 10], traits=_traits2int(['a', '0']), valid_until=500) srv_b = scheduler.Server('b', [10, 10], traits=_traits2int(['b', '0']), valid_until=500) srv_y = scheduler.Server('y', [10, 10], traits=_traits2int(['y', '1']), valid_until=500) srv_z = scheduler.Server('z', [10, 10], traits=_traits2int(['z', '1']), valid_until=500) top.add_node(left) top.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) alloc_a = scheduler.Allocation(traits=_traits2int(['a'])) apps_a = app_list(10, 'app_a', 50, [2, 2]) for app in apps_a: alloc_a.add(app) # srv_a is the only one with trait 'a'. self.assertTrue(top.put(apps_a[0])) self.assertTrue(top.put(apps_a[1])) self.assertIn(apps_a[0].name, srv_a.apps) self.assertIn(apps_a[1].name, srv_a.apps) apps_b = app_list(10, 'app_b', 50, [2, 2], traits=_traits2int(['b'])) # srv_b is the only one with trait 'b'. self.assertTrue(top.put(apps_b[0])) self.assertTrue(top.put(apps_b[1])) self.assertIn(apps_b[0].name, srv_b.apps) self.assertIn(apps_b[1].name, srv_b.apps) apps_ab = app_list(10, 'app_ab', 50, [2, 2], traits=_traits2int(['b'])) for app in apps_ab: alloc_a.add(app) # there is no server with both 'a' and 'b' traits. self.assertFalse(top.put(apps_ab[0])) self.assertFalse(top.put(apps_ab[1])) alloc_0 = scheduler.Allocation(traits=_traits2int(['0'])) apps_0 = app_list(10, 'app_0', 50, [2, 2]) for app in apps_0: alloc_0.add(app) # '0' trait - two servers, will spread by default. self.assertTrue(top.put(apps_0[0])) self.assertTrue(top.put(apps_0[1])) self.assertIn(apps_0[0].name, srv_a.apps) self.assertIn(apps_0[1].name, srv_b.apps) apps_a0 = app_list(10, 'app_a0', 50, [2, 2], traits=_traits2int(['a'])) for app in apps_a0: alloc_0.add(app) # srv_a is the only one with traits 'a' and '0'. self.assertTrue(top.put(apps_a0[0])) self.assertTrue(top.put(apps_a0[1])) self.assertIn(apps_a0[0].name, srv_a.apps) self.assertIn(apps_a0[1].name, srv_a.apps) # Prev implementation propagated traits from parent to children, # so "right" trait propagated to leaf servers. # # This behavior is removed, so placing app with "right" trait will # fail. # # alloc_r1 = scheduler.Allocation(traits=_traits2int(['right', '1'])) # apps_r1 = app_list(10, 'app_r1', 50, [2, 2]) # for app in apps_r1: # alloc_r1.add(app) # self.assertTrue(top.put(apps_r1[0])) # self.assertTrue(top.put(apps_r1[1])) # self.assertIn(apps_r1[0].name, srv_y.apps) # self.assertIn(apps_r1[1].name, srv_z.apps) apps_nothing = app_list(10, 'apps_nothing', 50, [1, 1]) # All nodes fit. Spead first between buckets, then between nodes. # top # left right # a b y z self.assertTrue(top.put(apps_nothing[0])) self.assertTrue(top.put(apps_nothing[1])) self.assertTrue( ( apps_nothing[0].server in ['a', 'b'] and apps_nothing[1].server in ['y', 'z'] ) or ( apps_nothing[0].server in ['y', 'z'] and apps_nothing[1].server in ['a', 'b'] ) ) self.assertTrue(top.put(apps_nothing[2])) self.assertTrue(top.put(apps_nothing[3])) self.assertTrue( ( apps_nothing[2].server in ['a', 'b'] and apps_nothing[3].server in ['y', 'z'] ) or ( apps_nothing[2].server in ['y', 'z'] and apps_nothing[3].server in ['a', 'b'] ) ) def test_size_and_members(self): """Tests recursive size calculation.""" top = scheduler.Bucket('top', traits=_traits2int(['top'])) left = scheduler.Bucket('left', traits=_traits2int(['left'])) right = scheduler.Bucket('right', traits=_traits2int(['right'])) srv_a = scheduler.Server('a', [1, 1], traits=_traits2int(['a', '0']), valid_until=500) srv_b = scheduler.Server('b', [1, 1], traits=_traits2int(['b', '0']), valid_until=500) srv_y = scheduler.Server('y', [1, 1], traits=_traits2int(['y', '1']), valid_until=500) srv_z = scheduler.Server('z', [1, 1], traits=_traits2int(['z', '1']), valid_until=500) top.add_node(left) top.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) # pylint: disable=W0212 self.assertTrue(scheduler._all_isclose(srv_a.size(None), [1, 1])) self.assertTrue(scheduler._all_isclose(left.size(None), [2, 2])) self.assertTrue(scheduler._all_isclose(top.size(None), [4, 4])) self.assertEqual( { 'a': srv_a, 'b': srv_b, 'y': srv_y, 'z': srv_z }, top.members() ) def test_affinity_counters(self): """Tests affinity counters.""" top = scheduler.Bucket('top', traits=_traits2int(['top'])) left = scheduler.Bucket('left', traits=_traits2int(['left'])) right = scheduler.Bucket('right', traits=_traits2int(['right'])) srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500) srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500) srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500) srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500) top.add_node(left) top.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) apps_a = app_list(10, 'app_a', 50, [1, 1]) self.assertTrue(srv_a.put(apps_a[0])) self.assertEqual(1, srv_a.affinity_counters['app_a']) self.assertEqual(1, left.affinity_counters['app_a']) self.assertEqual(1, top.affinity_counters['app_a']) srv_z.put(apps_a[0]) self.assertEqual(1, srv_z.affinity_counters['app_a']) self.assertEqual(1, left.affinity_counters['app_a']) self.assertEqual(2, top.affinity_counters['app_a']) srv_a.remove(apps_a[0].name) self.assertEqual(0, srv_a.affinity_counters['app_a']) self.assertEqual(0, left.affinity_counters['app_a']) self.assertEqual(1, top.affinity_counters['app_a']) class CellTest(unittest.TestCase): """treadmill.scheduler.Cell tests.""" def test_emtpy(self): """Simple test to test empty bucket""" cell = scheduler.Cell('top') empty = scheduler.Bucket('empty', traits=0) cell.add_node(empty) bucket = scheduler.Bucket('bucket', traits=0) srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500) bucket.add_node(srv_a) cell.add_node(bucket) cell.schedule() def test_labels(self): """Test scheduling with labels.""" cell = scheduler.Cell('top') left = scheduler.Bucket('left', traits=0) right = scheduler.Bucket('right', traits=0) srv_a = scheduler.Server('a_xx', [10, 10], valid_until=500, label='xx') srv_b = scheduler.Server('b', [10, 10], valid_until=500) srv_y = scheduler.Server('y_xx', [10, 10], valid_until=500, label='xx') srv_z = scheduler.Server('z', [10, 10], valid_until=500) cell.add_node(left) cell.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) app1 = scheduler.Application('app1', 4, [1, 1], 'app') app2 = scheduler.Application('app2', 3, [2, 2], 'app') app3 = scheduler.Application('app_xx_3', 2, [3, 3], 'app') app4 = scheduler.Application('app_xx_4', 1, [4, 4], 'app') cell.partitions[None].allocation.add(app1) cell.partitions[None].allocation.add(app2) cell.partitions['xx'].allocation.add(app3) cell.partitions['xx'].allocation.add(app4) cell.schedule() self.assertIn(app1.server, ['b', 'z']) self.assertIn(app2.server, ['b', 'z']) self.assertIn(app3.server, ['a_xx', 'y_xx']) self.assertIn(app4.server, ['a_xx', 'y_xx']) def test_simple(self): """Simple placement test.""" # pylint - too many lines. # # pylint: disable=R0915 cell = scheduler.Cell('top') left = scheduler.Bucket('left', traits=0) right = scheduler.Bucket('right', traits=0) srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500) srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500) srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500) srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500) cell.add_node(left) cell.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) app1 = scheduler.Application('app1', 4, [1, 1], 'app') app2 = scheduler.Application('app2', 3, [2, 2], 'app') app3 = scheduler.Application('app3', 2, [3, 3], 'app') app4 = scheduler.Application('app4', 1, [4, 4], 'app') cell.partitions[None].allocation.add(app1) cell.partitions[None].allocation.add(app2) cell.partitions[None].allocation.add(app3) cell.partitions[None].allocation.add(app4) cell.schedule() self.assertEqual( set([app1.server, app2.server, app3.server, app4.server]), set(['a', 'y', 'b', 'z']) ) srv1 = app1.server srv2 = app2.server srv3 = app3.server srv4 = app4.server # Add high priority app that needs entire cell app_prio50 = scheduler.Application('prio50', 50, [10, 10], 'app') cell.partitions[None].allocation.add(app_prio50) cell.schedule() # The queue is ordered by priority: # - prio50, app1, app2, app3, app4 # # As placement not found for prio50, app4 will be evicted first. # # As result, prio50 will be placed on 'z', and app4 (evicted) will be # placed on "next" server, which is 'a'. self.assertEqual(app_prio50.server, srv4) self.assertEqual(app4.server, srv1) app_prio51 = scheduler.Application('prio51', 51, [10, 10], 'app') cell.partitions[None].allocation.add(app_prio51) cell.schedule() # app4 is now colocated with app1. app4 will still be evicted first, # then app3, at which point there will be enough capacity to place # large app. # # app3 will be rescheduled to run on "next" server - 'y', and app4 will # be restored to 'a'. self.assertEqual(app_prio51.server, srv3) self.assertEqual(app_prio50.server, srv4) self.assertEqual(app4.server, srv1) app_prio49_1 = scheduler.Application('prio49_1', 49, [10, 10], 'app') app_prio49_2 = scheduler.Application('prio49_2', 49, [9, 9], 'app') cell.partitions[None].allocation.add(app_prio49_1) cell.partitions[None].allocation.add(app_prio49_2) cell.schedule() # 50/51 not moved. from the end of the queue, self.assertEqual(app_prio51.server, srv3) self.assertEqual(app_prio50.server, srv4) self.assertEqual( set([app_prio49_1.server, app_prio49_2.server]), set([srv1, srv2]) ) # Only capacity left for small [1, 1] app. self.assertIsNotNone(app1.server) self.assertIsNone(app2.server) self.assertIsNone(app3.server) self.assertIsNone(app4.server) def test_max_utilization(self): """Test max-utilization is handled properly when priorities change""" cell = scheduler.Cell('top') left = scheduler.Bucket('left', traits=0) right = scheduler.Bucket('right', traits=0) srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500) srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500) srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500) srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500) cell.add_node(left) cell.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) app1 = scheduler.Application('app1', 4, [1, 1], 'app') app2 = scheduler.Application('app2', 3, [2, 2], 'app') app3 = scheduler.Application('app3', 2, [3, 3], 'app') app4 = scheduler.Application('app4', 1, [4, 4], 'app') cell.partitions[None].allocation.add(app1) cell.partitions[None].allocation.add(app2) cell.partitions[None].allocation.add(app3) cell.partitions[None].allocation.add(app4) cell.partitions[None].allocation.set_reserved([6, 6]) cell.partitions[None].allocation.set_max_utilization(1) cell.schedule() self.assertIsNotNone(app1.server) self.assertIsNotNone(app2.server) self.assertIsNotNone(app3.server) self.assertIsNone(app4.server) app4.priority = 5 cell.schedule() self.assertIsNotNone(app1.server) self.assertIsNone(app2.server) self.assertIsNone(app3.server) self.assertIsNotNone(app4.server) def test_affinity_limits_bunker(self): """Simple placement test with bunker in level""" cell = scheduler.Cell('top') bunker1 = scheduler.Bucket('bunker1', traits=0) bunker2 = scheduler.Bucket('bunker2', traits=0) b1_left = scheduler.Bucket('b1_left', traits=0) b1_right = scheduler.Bucket('b1_right', traits=0) b2 = scheduler.Bucket('b2', traits=0) srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500) srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500) srv_c = scheduler.Server('c', [10, 10], traits=0, valid_until=500) srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500) srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500) cell.add_node(bunker1) cell.add_node(bunker2) bunker1.add_node(b1_left) bunker1.add_node(b1_right) bunker2.add_node(b2) b1_left.add_node(srv_a) b1_left.add_node(srv_b) b1_right.add_node(srv_c) b2.add_node(srv_y) b2.add_node(srv_z) bunker1.level = 'bunker' bunker2.level = 'bunker' b1_left.level = 'rack' b1_right.level = 'rack' b2.level = 'rack' apps = app_list(10, 'app', 50, [1, 1], affinity_limits={'server': 1, 'bunker': 1}) cell.add_app(cell.partitions[None].allocation, apps[0]) cell.add_app(cell.partitions[None].allocation, apps[1]) cell.add_app(cell.partitions[None].allocation, apps[2]) cell.add_app(cell.partitions[None].allocation, apps[3]) cell.schedule() self.assertIsNotNone(apps[0].server) self.assertIsNotNone(apps[1].server) self.assertIsNone(apps[2].server) self.assertIsNone(apps[3].server) apps = app_list(10, 'app', 50, [1, 1], affinity_limits={'server': 1, 'rack': 1, 'bunker': 2}) for app in apps: cell.remove_app(app.name) cell.add_app(cell.partitions[None].allocation, apps[0]) cell.add_app(cell.partitions[None].allocation, apps[1]) cell.add_app(cell.partitions[None].allocation, apps[2]) cell.add_app(cell.partitions[None].allocation, apps[3]) cell.schedule() self.assertIsNotNone(apps[0].server) self.assertIsNotNone(apps[1].server) self.assertIsNotNone(apps[2].server) self.assertIsNone(apps[3].server) def test_affinity_limits_levels(self): """Simple placement test with 2 layer of bucket""" # pylint: disable=too-many-statements cell = scheduler.Cell('top') group1 = scheduler.Bucket('group1', traits=0) group2 = scheduler.Bucket('group2', traits=0) g1_left = scheduler.Bucket('g1_left', traits=0) g1_right = scheduler.Bucket('g1_right', traits=0) g2_left = scheduler.Bucket('g2_left', traits=0) g2_right = scheduler.Bucket('g2_right', traits=0) srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500) srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500) srv_c = scheduler.Server('c', [10, 10], traits=0, valid_until=500) srv_x = scheduler.Server('x', [10, 10], traits=0, valid_until=500) srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500) srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500) cell.add_node(group1) cell.add_node(group2) group1.add_node(g1_left) group1.add_node(g1_right) group2.add_node(g2_left) group2.add_node(g2_right) g1_left.add_node(srv_a) g1_left.add_node(srv_b) g1_right.add_node(srv_c) g2_left.add_node(srv_x) g2_right.add_node(srv_y) g2_right.add_node(srv_z) g1_left.level = 'rack' g1_right.level = 'rack' g2_left.level = 'rack' g2_right.level = 'rack' apps = app_list(10, 'app', 50, [1, 1], affinity_limits={'server': 1}) cell.add_app(cell.partitions[None].allocation, apps[0]) cell.add_app(cell.partitions[None].allocation, apps[1]) cell.add_app(cell.partitions[None].allocation, apps[2]) cell.add_app(cell.partitions[None].allocation, apps[3]) cell.add_app(cell.partitions[None].allocation, apps[4]) cell.add_app(cell.partitions[None].allocation, apps[5]) cell.add_app(cell.partitions[None].allocation, apps[6]) cell.schedule() self.assertIsNotNone(apps[0].server) self.assertIsNotNone(apps[1].server) self.assertIsNotNone(apps[2].server) self.assertIsNotNone(apps[3].server) self.assertIsNotNone(apps[4].server) self.assertIsNotNone(apps[5].server) self.assertIsNone(apps[6].server) for app in apps: cell.remove_app(app.name) apps = app_list(10, 'app', 50, [1, 1], affinity_limits={'server': 1, 'rack': 1}) cell.add_app(cell.partitions[None].allocation, apps[0]) cell.add_app(cell.partitions[None].allocation, apps[1]) cell.add_app(cell.partitions[None].allocation, apps[2]) cell.add_app(cell.partitions[None].allocation, apps[3]) cell.add_app(cell.partitions[None].allocation, apps[4]) cell.add_app(cell.partitions[None].allocation, apps[5]) cell.schedule() self.assertIsNotNone(apps[0].server) self.assertIsNotNone(apps[1].server) self.assertIsNotNone(apps[2].server) self.assertIsNotNone(apps[3].server) self.assertIsNone(apps[4].server) self.assertIsNone(apps[5].server) apps = app_list(10, 'app', 50, [1, 1], affinity_limits={'server': 1, 'rack': 2, 'cell': 3}) for app in apps: cell.remove_app(app.name) cell.add_app(cell.partitions[None].allocation, apps[0]) cell.add_app(cell.partitions[None].allocation, apps[1]) cell.add_app(cell.partitions[None].allocation, apps[2]) cell.add_app(cell.partitions[None].allocation, apps[3]) cell.schedule() self.assertIsNotNone(apps[0].server) self.assertIsNotNone(apps[1].server) self.assertIsNotNone(apps[2].server) self.assertIsNone(apps[3].server) def test_affinity_limits(self): """Simple placement test.""" cell = scheduler.Cell('top') left = scheduler.Bucket('left', traits=0) right = scheduler.Bucket('right', traits=0) srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500) srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500) srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500) srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500) cell.add_node(left) cell.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) left.level = 'rack' right.level = 'rack' apps = app_list(10, 'app', 50, [1, 1], affinity_limits={'server': 1}) cell.add_app(cell.partitions[None].allocation, apps[0]) cell.add_app(cell.partitions[None].allocation, apps[1]) cell.add_app(cell.partitions[None].allocation, apps[2]) cell.add_app(cell.partitions[None].allocation, apps[3]) cell.add_app(cell.partitions[None].allocation, apps[4]) cell.schedule() self.assertIsNotNone(apps[0].server) self.assertIsNotNone(apps[1].server) self.assertIsNotNone(apps[2].server) self.assertIsNotNone(apps[3].server) self.assertIsNone(apps[4].server) for app in apps: cell.remove_app(app.name) apps = app_list(10, 'app', 50, [1, 1], affinity_limits={'server': 1, 'rack': 1}) cell.add_app(cell.partitions[None].allocation, apps[0]) cell.add_app(cell.partitions[None].allocation, apps[1]) cell.add_app(cell.partitions[None].allocation, apps[2]) cell.add_app(cell.partitions[None].allocation, apps[3]) cell.schedule() self.assertIsNotNone(apps[0].server) self.assertIsNotNone(apps[1].server) self.assertIsNone(apps[2].server) self.assertIsNone(apps[3].server) for app in apps: cell.remove_app(app.name) apps = app_list(10, 'app', 50, [1, 1], affinity_limits={'server': 1, 'rack': 2, 'cell': 3}) cell.add_app(cell.partitions[None].allocation, apps[0]) cell.add_app(cell.partitions[None].allocation, apps[1]) cell.add_app(cell.partitions[None].allocation, apps[2]) cell.add_app(cell.partitions[None].allocation, apps[3]) cell.schedule() self.assertIsNotNone(apps[0].server) self.assertIsNotNone(apps[1].server) self.assertIsNotNone(apps[2].server) self.assertIsNone(apps[3].server) @mock.patch('time.time', mock.Mock(return_value=0)) def test_data_retention_levels(self): """Tests data retention.""" cell = scheduler.Cell('top') group1 = scheduler.Bucket('group1', traits=0) group2 = scheduler.Bucket('group2', traits=0) g1_left = scheduler.Bucket('g1_left', traits=0) g1_right = scheduler.Bucket('g1_right', traits=0) g2 = scheduler.Bucket('g2', traits=0) srvs = { 'a': scheduler.Server('a', [10, 10], traits=0, valid_until=500), 'b': scheduler.Server('b', [10, 10], traits=0, valid_until=500), 'c': scheduler.Server('c', [10, 10], traits=0, valid_until=500), 'y': scheduler.Server('y', [10, 10], traits=0, valid_until=500), 'z': scheduler.Server('z', [10, 10], traits=0, valid_until=500), } cell.add_node(group1) cell.add_node(group2) group1.add_node(g1_left) group1.add_node(g1_right) group2.add_node(g2) g1_left.add_node(srvs['a']) g1_left.add_node(srvs['b']) g1_right.add_node(srvs['c']) g2.add_node(srvs['y']) g2.add_node(srvs['z']) g1_left.level = 'rack' g1_right.level = 'rack' g2.level = 'rack' time.time.return_value = 100 sticky_apps = app_list(10, 'sticky', 50, [1, 1], affinity_limits={'server': 1, 'rack': 1}, data_retention_timeout=30) unsticky_app = scheduler.Application('unsticky', 10, [1., 1.], 'unsticky', data_retention_timeout=0) cell.partitions[None].allocation.add(sticky_apps[0]) cell.partitions[None].allocation.add(unsticky_app) cell.schedule() # Both apps having different affinity, will be on same node. first_srv = sticky_apps[0].server self.assertEqual(sticky_apps[0].server, unsticky_app.server) # Mark srv_a as down, unsticky app migrates right away, # sticky stays. srvs[first_srv].state = scheduler.State.down cell.schedule() self.assertEqual(sticky_apps[0].server, first_srv) self.assertNotEqual(unsticky_app.server, first_srv) self.assertEqual(cell.next_event_at, 130) time.time.return_value = 110 cell.schedule() self.assertEqual(sticky_apps[0].server, first_srv) self.assertNotEqual(unsticky_app.server, first_srv) self.assertEqual(cell.next_event_at, 130) time.time.return_value = 130 cell.schedule() self.assertNotEqual(sticky_apps[0].server, first_srv) self.assertNotEqual(unsticky_app.server, first_srv) self.assertEqual(cell.next_event_at, np.inf) @mock.patch('time.time', mock.Mock(return_value=0)) def test_data_retention(self): """Tests data retention.""" # Disable pylint's too many statements warning. # # pylint: disable=R0915 cell = scheduler.Cell('top') left = scheduler.Bucket('left', traits=0) right = scheduler.Bucket('right', traits=0) srvs = { 'a': scheduler.Server('a', [10, 10], traits=0, valid_until=500), 'b': scheduler.Server('b', [10, 10], traits=0, valid_until=500), 'y': scheduler.Server('y', [10, 10], traits=0, valid_until=500), 'z': scheduler.Server('z', [10, 10], traits=0, valid_until=500), } cell.add_node(left) cell.add_node(right) left.add_node(srvs['a']) left.add_node(srvs['b']) right.add_node(srvs['y']) right.add_node(srvs['z']) left.level = 'rack' right.level = 'rack' time.time.return_value = 100 sticky_apps = app_list(10, 'sticky', 50, [1, 1], affinity_limits={'server': 1, 'rack': 1}, data_retention_timeout=30) unsticky_app = scheduler.Application('unsticky', 10, [1., 1.], 'unsticky', data_retention_timeout=0) cell.partitions[None].allocation.add(sticky_apps[0]) cell.partitions[None].allocation.add(unsticky_app) cell.schedule() # Both apps having different affinity, will be on same node. first_srv = sticky_apps[0].server self.assertEqual(sticky_apps[0].server, unsticky_app.server) # Mark srv_a as down, unsticky app migrates right away, # sticky stays. srvs[first_srv].state = scheduler.State.down cell.schedule() self.assertEqual(sticky_apps[0].server, first_srv) self.assertNotEqual(unsticky_app.server, first_srv) self.assertEqual(cell.next_event_at, 130) time.time.return_value = 110 cell.schedule() self.assertEqual(sticky_apps[0].server, first_srv) self.assertNotEqual(unsticky_app.server, first_srv) self.assertEqual(cell.next_event_at, 130) time.time.return_value = 130 cell.schedule() self.assertNotEqual(sticky_apps[0].server, first_srv) self.assertNotEqual(unsticky_app.server, first_srv) self.assertEqual(cell.next_event_at, np.inf) second_srv = sticky_apps[0].server # Mark srv_a as up, srv_y as down. srvs[first_srv].state = scheduler.State.up srvs[second_srv].state = scheduler.State.down cell.schedule() self.assertEqual(sticky_apps[0].server, second_srv) self.assertNotEqual(unsticky_app.server, second_srv) self.assertEqual(cell.next_event_at, 160) # Schedule one more sticky app. As it has rack affinity limit 1, it # can't to to right (x,y) rack, rather will end up in left (a,b) rack. # # Other sticky apps will be pending. time.time.return_value = 135 cell.partitions[None].allocation.add(sticky_apps[1]) cell.partitions[None].allocation.add(sticky_apps[2]) cell.schedule() # Original app still on 'y', timeout did not expire self.assertEqual(sticky_apps[0].server, second_srv) # next sticky app is on (a,b) rack. # self.assertIn(sticky_apps[1].server, ['a', 'b']) # The 3rd sticky app pending, as rack affinity taken by currently # down node y. self.assertIsNone(sticky_apps[2].server) srvs[second_srv].state = scheduler.State.up cell.schedule() # Original app still on 'y', timeout did not expire self.assertEqual(sticky_apps[0].server, second_srv) # next sticky app is on (a,b) rack. # self.assertIn(sticky_apps[1].server, ['a', 'b']) # The 3rd sticky app pending, as rack affinity taken by currently # app[0] on node y. self.assertIsNone(sticky_apps[2].server) def test_serialization(self): """Tests cell serialization.""" # Disable pylint's too many statements warning. # # pylint: disable=R0915 cell = scheduler.Cell('top') left = scheduler.Bucket('left', traits=0) right = scheduler.Bucket('right', traits=0) srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500) srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500) srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500) srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500) cell.add_node(left) cell.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) left.level = 'rack' right.level = 'rack' apps = app_list(10, 'app', 50, [1, 1], affinity_limits={'server': 1, 'rack': 1}) cell.add_app(cell.partitions[None].allocation, apps[0]) cell.add_app(cell.partitions[None].allocation, apps[1]) cell.add_app(cell.partitions[None].allocation, apps[2]) cell.add_app(cell.partitions[None].allocation, apps[3]) cell.schedule() # TODO: need to implement serialization. # # data = scheduler.dumps(cell) # cell1 = scheduler.loads(data) def test_identity(self): """Tests scheduling apps with identity.""" cell = scheduler.Cell('top') for idx in range(0, 10): server = scheduler.Server(str(idx), [10, 10], traits=0, valid_until=time.time() + 1000) cell.add_node(server) cell.configure_identity_group('ident1', 3) apps = app_list(10, 'app', 50, [1, 1], identity_group='ident1') for app in apps: cell.add_app(cell.partitions[None].allocation, app) self.assertTrue(apps[0].acquire_identity()) self.assertEqual(set([1, 2]), apps[0].identity_group_ref.available) self.assertEqual(set([1, 2]), apps[1].identity_group_ref.available) cell.schedule() self.assertEqual(apps[0].identity, 0) self.assertEqual(apps[1].identity, 1) self.assertEqual(apps[2].identity, 2) for idx in range(3, 10): self.assertIsNone(apps[idx].identity, None) # Removing app will release the identity, and it will be aquired by # next app in the group. cell.remove_app('app-2') cell.schedule() self.assertEqual(apps[3].identity, 2) # Increase ideneity group count to 5, expect 5 placed apps. cell.configure_identity_group('ident1', 5) cell.schedule() self.assertEqual( 5, len([app for app in apps if app.server is not None]) ) cell.configure_identity_group('ident1', 3) cell.schedule() self.assertEqual( 3, len([app for app in apps if app.server is not None]) ) def test_schedule_once(self): """Tests schedule once trait on server down.""" cell = scheduler.Cell('top') for idx in range(0, 10): server = scheduler.Server(str(idx), [10, 10], traits=0, valid_until=time.time() + 1000) cell.add_node(server) apps = app_list(2, 'app', 50, [6, 6], schedule_once=True) for app in apps: cell.add_app(cell.partitions[None].allocation, app) cell.schedule() self.assertNotEqual(apps[0].server, apps[1].server) self.assertFalse(apps[0].evicted) self.assertFalse(apps[0].evicted) cell.children_by_name[apps[0].server].state = scheduler.State.down cell.remove_node_by_name(apps[1].server) cell.schedule() self.assertIsNone(apps[0].server) self.assertTrue(apps[0].evicted) self.assertIsNone(apps[1].server) self.assertTrue(apps[1].evicted) def test_schedule_once_eviction(self): """Tests schedule once trait with eviction.""" cell = scheduler.Cell('top') for idx in range(0, 10): server = scheduler.Server(str(idx), [10, 10], traits=0, valid_until=time.time() + 1000) cell.add_node(server) # Each server has capacity 10. # # Place two apps - capacity 1, capacity 8, they will occupy entire # server. # # Try and place app with demand of 2. First it will try to evict # small app, but it will not be enough, so it will evict large app. # # Check that evicted flag is set only for large app, and small app # will be restored. small_apps = app_list(10, 'small', 50, [1, 1], schedule_once=True) for app in small_apps: cell.add_app(cell.partitions[None].allocation, app) large_apps = app_list(10, 'large', 60, [8, 8], schedule_once=True) for app in large_apps: cell.add_app(cell.partitions[None].allocation, app) placement = cell.schedule() # Check that all apps are placed. app2server = {app: after for app, _, _, after, _ in placement if after is not None} self.assertEqual(len(app2server), 20) # Add one app, higher priority than rest, will force eviction. medium_apps = app_list(1, 'medium', 70, [5, 5]) for app in medium_apps: cell.add_app(cell.partitions[None].allocation, app) cell.schedule() self.assertEqual(len([app for app in small_apps if app.evicted]), 0) self.assertEqual(len([app for app in small_apps if app.server]), 10) self.assertEqual(len([app for app in large_apps if app.evicted]), 1) self.assertEqual(len([app for app in large_apps if app.server]), 9) # Remove app, make sure the evicted app is not placed again. cell.remove_app(medium_apps[0].name) cell.schedule() self.assertEqual(len([app for app in small_apps if app.evicted]), 0) self.assertEqual(len([app for app in small_apps if app.server]), 10) self.assertEqual(len([app for app in large_apps if app.evicted]), 1) self.assertEqual(len([app for app in large_apps if app.server]), 9) @mock.patch('time.time', mock.Mock(return_value=100)) def test_eviction_server_down(self): """Tests app restore.""" cell = scheduler.Cell('top') large_server = scheduler.Server('large', [10, 10], traits=0, valid_until=10000) cell.add_node(large_server) small_server = scheduler.Server('small', [3, 3], traits=0, valid_until=10000) cell.add_node(small_server) # Create two apps one with retention other without. Set priority # so that app with retention is on the right of the queue, when # placement not found for app without retention, it will try to # evict app with retention. app_no_retention = scheduler.Application('a1', 100, [4, 4], 'app') app_with_retention = scheduler.Application('a2', 1, [4, 4], 'app', data_retention_timeout=3000) cell.add_app(cell.partitions[None].allocation, app_no_retention) cell.add_app(cell.partitions[None].allocation, app_with_retention) cell.schedule() # At this point, both apps are on large server, as small server does # not have capacity. self.assertEqual('large', app_no_retention.server) self.assertEqual('large', app_with_retention.server) # Mark large server down. App with retention will remain on the server. # App without retention should be pending. large_server.state = scheduler.State.down cell.schedule() self.assertEqual(None, app_no_retention.server) self.assertEqual('large', app_with_retention.server) @mock.patch('time.time', mock.Mock(return_value=100)) def test_restore(self): """Tests app restore.""" cell = scheduler.Cell('top') large_server = scheduler.Server('large', [10, 10], traits=0, valid_until=200) cell.add_node(large_server) small_server = scheduler.Server('small', [3, 3], traits=0, valid_until=1000) cell.add_node(small_server) apps = app_list(1, 'app', 50, [6, 6], lease=50) for app in apps: cell.add_app(cell.partitions[None].allocation, app) # 100 sec left, app lease is 50, should fit. time.time.return_value = 100 cell.schedule() self.assertEqual(apps[0].server, 'large') time.time.return_value = 190 apps_not_fit = app_list(1, 'app-not-fit', 90, [6, 6], lease=50) for app in apps_not_fit: cell.add_app(cell.partitions[None].allocation, app) cell.schedule() self.assertIsNone(apps_not_fit[0].server) self.assertEqual(apps[0].server, 'large') @mock.patch('time.time', mock.Mock(return_value=10)) def test_renew(self): """Tests app restore.""" cell = scheduler.Cell('top') server_a = scheduler.Server('a', [10, 10], traits=0, valid_until=1000) cell.add_node(server_a) apps = app_list(1, 'app', 50, [6, 6], lease=50) for app in apps: cell.add_app(cell.partitions[None].allocation, app) cell.schedule() self.assertEqual(apps[0].server, 'a') self.assertEqual(apps[0].placement_expiry, 60) time.time.return_value = 100 cell.schedule() self.assertEqual(apps[0].server, 'a') self.assertEqual(apps[0].placement_expiry, 60) time.time.return_value = 200 apps[0].renew = True cell.schedule() self.assertEqual(apps[0].server, 'a') self.assertEqual(apps[0].placement_expiry, 250) self.assertFalse(apps[0].renew) # fast forward to 975, close to server 'a' expiration, app will # migratoe to 'b' on renew. server_b = scheduler.Server('b', [10, 10], traits=0, valid_until=2000) cell.add_node(server_b) time.time.return_value = 975 apps[0].renew = True cell.schedule() self.assertEqual(apps[0].server, 'b') self.assertEqual(apps[0].placement_expiry, 1025) self.assertFalse(apps[0].renew) # fast forward to 1975, when app can't be renewed on server b, but # there is not alternative placement. time.time.return_value = 1975 apps[0].renew = True cell.schedule() self.assertEqual(apps[0].server, 'b') # Placement expiry did not change, as placement was not found. self.assertEqual(apps[0].placement_expiry, 1025) # Renew flag is not cleared, as new placement was not found. self.assertTrue(apps[0].renew) def test_partition_server_down(self): """Test placement when server in the partition goes down.""" cell = scheduler.Cell('top') srv_x1 = scheduler.Server('s_x1', [10, 10], valid_until=500, label='x') srv_x2 = scheduler.Server('s_x2', [10, 10], valid_until=500, label='x') srv_y1 = scheduler.Server('s_y1', [10, 10], valid_until=500, label='y') srv_y2 = scheduler.Server('s_y2', [10, 10], valid_until=500, label='y') cell.add_node(srv_x1) cell.add_node(srv_x2) cell.add_node(srv_y1) cell.add_node(srv_y2) app_x1 = scheduler.Application('a_x1', 1, [1, 1], 'app') app_x2 = scheduler.Application('a_x2', 1, [1, 1], 'app') app_y1 = scheduler.Application('a_y1', 1, [1, 1], 'app') app_y2 = scheduler.Application('a_y2', 1, [1, 1], 'app') cell.partitions['x'].allocation.add(app_x1) cell.partitions['x'].allocation.add(app_x2) cell.partitions['y'].allocation.add(app_y1) cell.partitions['y'].allocation.add(app_y2) placement = cell.schedule() self.assertEqual(len(placement), 4) # Default strategy will distribute two apps on each of the servers # in the partition. # # For future test it is important that each server has an app, so # we assert on that. self.assertEqual(len(srv_x1.apps), 1) self.assertEqual(len(srv_x2.apps), 1) self.assertEqual(len(srv_y1.apps), 1) self.assertEqual(len(srv_y2.apps), 1) # Verify that all apps are placed in the returned placement. for (_app, before, _exp_before, after, _exp_after) in placement: self.assertIsNone(before) self.assertIsNotNone(after) # Bring server down in each partition. srv_x1.state = scheduler.State.down srv_y1.state = scheduler.State.down placement = cell.schedule() self.assertEqual(len(placement), 4) # Check that in the updated placement before and after are not None. for (_app, before, _exp_before, after, _exp_after) in placement: self.assertIsNotNone(before) self.assertIsNotNone(after) def test_placement_shortcut(self): """Test no placement tracker.""" cell = scheduler.Cell('top') srv_1 = scheduler.Server('s1', [10, 10], valid_until=500, label='x') srv_2 = scheduler.Server('s2', [10, 10], valid_until=500, label='x') cell.add_node(srv_1) cell.add_node(srv_2) app_large_dim1 = scheduler.Application('large-1', 100, [7, 1], 'app') app_large_dim2 = scheduler.Application('large-2', 100, [1, 7], 'app') cell.partitions['x'].allocation.add(app_large_dim1) cell.partitions['x'].allocation.add(app_large_dim2) cell.schedule() self.assertIsNotNone(app_large_dim1.server) self.assertIsNotNone(app_large_dim2.server) # Add lower priority apps - can't be scheduled. # # As free size of top level node is 9x9, placement attempt will be # made. medium_apps = [] for appid in range(1, 10): app_med = scheduler.Application( 'medium-%s' % appid, 90, [4, 4], 'app') cell.partitions['x'].allocation.add(app_med) medium_apps.append(app_med) cell.schedule() for app in medium_apps: self.assertIsNone(app.server) class IdentityGroupTest(unittest.TestCase): """scheduler IdentityGroup test.""" def test_basic(self): """Test basic acquire/release ops.""" ident_group = scheduler.IdentityGroup(3) self.assertEqual(0, ident_group.acquire()) self.assertEqual(1, ident_group.acquire()) self.assertEqual(2, ident_group.acquire()) self.assertEqual(None, ident_group.acquire()) ident_group.release(1) self.assertEqual(1, ident_group.acquire()) def test_adjust(self): """Test identity group count adjustement.""" ident_group = scheduler.IdentityGroup(5) ident_group.available = set([1, 3]) ident_group.adjust(7) self.assertEqual(set([1, 3, 5, 6]), ident_group.available) ident_group.adjust(3) self.assertEqual(set([1]), ident_group.available) def test_adjust_relese(self): """Test releasing identity when identity exceeds the count.""" ident_group = scheduler.IdentityGroup(1) self.assertEqual(0, ident_group.acquire()) self.assertEqual(len(ident_group.available), 0) ident_group.adjust(0) ident_group.release(0) self.assertEqual(len(ident_group.available), 0) def _time(string): """Convert a formatted datetime to a timestamp.""" return time.mktime(time.strptime(string, '%Y-%m-%d %H:%M:%S')) class RebootSchedulerTest(unittest.TestCase): """reboot scheduler test.""" def test_bucket(self): """Test RebootBucket.""" bucket = scheduler.RebootBucket(_time('2000-01-03 00:00:00')) # cost of inserting into empty bucket is zero server1 = scheduler.Server('s1', [10, 10], up_since=_time('2000-01-01 00:00:00')) self.assertEqual(0, bucket.cost(server1)) # insert server into a bucket bucket.add(server1) self.assertEqual(bucket.servers, set([server1])) self.assertTrue(server1.valid_until > 0) # inserting server into a bucket is idempotent valid_until = server1.valid_until bucket.add(server1) self.assertEqual(bucket.servers, set([server1])) self.assertEqual(server1.valid_until, valid_until) # cost of inserting into non-empty bucket is size of bucket server2 = scheduler.Server('s2', [10, 10], up_since=_time('2000-01-01 00:00:00')) self.assertEqual(1, bucket.cost(server2)) # when server would be too old, cost is prohibitive server3 = scheduler.Server('s3', [10, 10], up_since=_time('1999-01-01 00:00:00')) self.assertEqual(float('inf'), bucket.cost(server3)) # when server is too close to reboot date, cost is prohibitive server4 = scheduler.Server('s1', [10, 10], up_since=_time('2000-01-02 10:00:00')) self.assertEqual(float('inf'), bucket.cost(server4)) # remove server from a bucket bucket.remove(server1) self.assertEqual(bucket.servers, set([])) # removing server from a bucket is idempotent bucket.remove(server1) def test_reboots(self): """Test RebootScheduler.""" partition = scheduler.Partition(now=_time('2000-01-01 00:00:00')) server1 = scheduler.Server('s1', [10, 10], up_since=_time('2000-01-01 00:00:00')) server2 = scheduler.Server('s2', [10, 10], up_since=_time('2000-01-01 00:00:00')) server3 = scheduler.Server('s3', [10, 10], up_since=_time('2000-01-01 00:00:00')) server4 = scheduler.Server('s4', [10, 10], up_since=_time('1999-12-24 00:00:00')) # adding to existing bucket # pylint: disable=W0212 timestamp = partition._reboot_buckets[0].timestamp partition.add(server1, timestamp) self.assertEqual(timestamp, server1.valid_until) # adding to non-existsing bucket, results in finding a more # appropriate bucket partition.add(server2, timestamp + 600) self.assertNotEqual(timestamp + 600, server2.valid_until) # will get into different bucket than server2, so bucket sizes # stay low partition.add(server3) self.assertNotEqual(server2.valid_until, server3.valid_until) # server max_lifetime is respected partition.add(server4) self.assertTrue( server4.valid_until < server4.up_since + scheduler.DEFAULT_SERVER_UPTIME ) def test_reboot_dates(self): """Test reboot dates generator.""" # Note: 2018/01/01 is a Monday start_date = datetime.date(2018, 1, 1) schedule = utils.reboot_schedule('sat,sun') dates_gen = scheduler.reboot_dates(schedule, start_date) self.assertEqual( list(itertools.islice(dates_gen, 2)), [ _time('2018-01-06 23:59:59'), _time('2018-01-07 23:59:59'), ] ) schedule = utils.reboot_schedule('sat,sun/10:30:00') dates_gen = scheduler.reboot_dates(schedule, start_date) self.assertEqual( list(itertools.islice(dates_gen, 2)), [ _time('2018-01-06 23:59:59'), _time('2018-01-07 10:30:00'), ] ) class ShapeTest(unittest.TestCase): """App shape test cases.""" def test_affinity_constraints(self): """Test affinity constraints.""" aff = scheduler.Affinity('foo', {}) self.assertEqual(('foo',), aff.constraints) aff = scheduler.Affinity('foo', {'server': 1}) self.assertEqual(('foo', 1,), aff.constraints) def test_app_shape(self): """Test application shape.""" app = scheduler.Application('foo', 11, [1, 1, 1], 'bar') self.assertEqual(('bar', 0,), app.shape()[0]) app.lease = 5 self.assertEqual(('bar', 5,), app.shape()[0]) app = scheduler.Application('foo', 11, [1, 1, 1], 'bar', affinity_limits={'server': 1, 'rack': 2}) # Values of the dict return ordered by key, (rack, server). self.assertEqual(('bar', 1, 2, 0,), app.shape()[0]) app.lease = 5 self.assertEqual(('bar', 1, 2, 5,), app.shape()[0]) def test_placement_tracker(self): """Tests placement tracker.""" app = scheduler.Application('foo', 11, [2, 2, 2], 'bar') placement_tracker = scheduler.PlacementFeasibilityTracker() placement_tracker.adjust(app) # Same app. self.assertFalse(placement_tracker.feasible(app)) # Larger app, same shape. app = scheduler.Application('foo', 11, [3, 3, 3], 'bar') self.assertFalse(placement_tracker.feasible(app)) # Smaller app, same shape. app = scheduler.Application('foo', 11, [1, 1, 1], 'bar') self.assertTrue(placement_tracker.feasible(app)) # Different affinity. app = scheduler.Application('foo', 11, [5, 5, 5], 'bar1') self.assertTrue(placement_tracker.feasible(app)) if __name__ == '__main__': unittest.main()
38.478707
79
0.591546
"""Unit test for treadmill.scheduler. """ # Disable too many lines in module warning. # # pylint: disable=C0302 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import datetime import itertools import sys import time import unittest import mock import numpy as np import six # Disable W0611: Unused import import treadmill.tests.treadmill_test_skip_windows # pylint: disable=W0611 from treadmill import scheduler from treadmill import utils _TRAITS = dict() # Helper functions to convert user readable traits to bit mask. def _trait2int(trait): if trait not in _TRAITS: _TRAITS[trait] = len(_TRAITS) + 1 return 2 ** _TRAITS[trait] def _traits2int(traits): return six.moves.reduce( lambda acc, t: acc | _trait2int(t), traits, 0 ) def app_list(count, name, *args, **kwargs): """Return list of apps.""" return [scheduler.Application(name + '-' + str(idx), *args, affinity=name, **kwargs) for idx in range(0, count)] class OpsTest(unittest.TestCase): """Test comparison operators.""" # Disable warning accessing protected members. # # pylint: disable=W0212 def test_ops(self): """Test comparison operators.""" self.assertTrue(scheduler._all_gt([3, 3], [2, 2])) self.assertTrue(scheduler._any_gt([3, 2], [2, 2])) self.assertFalse(scheduler._all_gt([3, 2], [2, 2])) self.assertTrue(scheduler._all_lt([2, 2], [3, 3])) class AllocationTest(unittest.TestCase): """treadmill.scheduler.Allocation tests.""" def setUp(self): scheduler.DIMENSION_COUNT = 2 super(AllocationTest, self).setUp() def test_utilization(self): """Test utilization calculation.""" alloc = scheduler.Allocation([10, 10]) alloc.add(scheduler.Application('app1', 100, [1, 1], 'app1')) alloc.add(scheduler.Application('app2', 100, [2, 2], 'app1')) alloc.add(scheduler.Application('app3', 100, [3, 3], 'app1')) # First element is rank. util_q = list(alloc.utilization_queue([20, 20])) self.assertEqual(100, util_q[0][0]) self.assertEqual(100, util_q[1][0]) self.assertEqual(100, util_q[2][0]) # Second and third elememts is before / after utilization. self.assertEqual(-10 / (10. + 20), util_q[0][1]) self.assertEqual(-9 / (10. + 20), util_q[0][2]) self.assertEqual(-7 / (10. + 20), util_q[1][2]) self.assertEqual(-9 / (10. + 20), util_q[1][1]) self.assertEqual(-4 / (10. + 20), util_q[2][2]) self.assertEqual(-7 / (10. + 20), util_q[2][1]) # Applications are sorted by priority. alloc = scheduler.Allocation([10, 10]) alloc.add(scheduler.Application('app1', 10, [1, 1], 'app1')) alloc.add(scheduler.Application('app2', 50, [2, 2], 'app1')) alloc.add(scheduler.Application('app3', 100, [3, 3], 'app1')) util_q = list(alloc.utilization_queue([20., 20.])) self.assertEqual(-10 / (10. + 20), util_q[0][1]) self.assertEqual(-7 / (10. + 20), util_q[0][2]) self.assertEqual(-7 / (10. + 20), util_q[1][1]) self.assertEqual(-5 / (10. + 20), util_q[1][2]) self.assertEqual(-5 / (10. + 20), util_q[2][1]) self.assertEqual(-4 / (10. + 20), util_q[2][2]) def test_running_order(self): """Test apps are ordered by status (running first) for same prio.""" alloc = scheduler.Allocation([10, 10]) alloc.add(scheduler.Application('app1', 5, [1, 1], 'app1')) alloc.add(scheduler.Application('app2', 5, [2, 2], 'app1')) alloc.add(scheduler.Application('app3', 5, [3, 3], 'app1')) queue = list(alloc.utilization_queue([20., 20.])) self.assertEqual(alloc.apps['app1'], queue[0][-1]) alloc.apps['app2'].server = 'abc' queue = list(alloc.utilization_queue([20., 20.])) self.assertEqual(alloc.apps['app2'], queue[0][-1]) def test_utilization_max(self): """Tests max utilization cap on the allocation.""" alloc = scheduler.Allocation([3, 3]) alloc.add(scheduler.Application('app1', 1, [1, 1], 'app1')) alloc.add(scheduler.Application('app2', 1, [2, 2], 'app1')) alloc.add(scheduler.Application('app3', 1, [3, 3], 'app1')) self.assertEqual(3, len(list(alloc.utilization_queue([20., 20.])))) # Now set max_utilization to 1 alloc.max_utilization = 1 # XXX: Broken test. Needs upgrade to V3 # XXX: # XXX: self.assertEqual( # XXX: 2, # XXX: len(list(alloc.utilization_queue([20., 20.]))) # XXX: ) alloc.set_max_utilization(None) self.assertEqual(3, len(list(alloc.utilization_queue([20., 20.])))) def test_priority_zero(self): """Tests priority zero apps.""" alloc = scheduler.Allocation([3, 3]) alloc.add(scheduler.Application('app1', 1, [1, 1], 'app1')) alloc.add(scheduler.Application('app2', 0, [2, 2], 'app1')) # default max_utilization still lets prio 0 apps through queue = alloc.utilization_queue([20., 20.]) self.assertEqual([100, 100], [item[0] for item in queue]) alloc.set_max_utilization(100) # setting max_utilization will cut off prio 0 apps queue = alloc.utilization_queue([20., 20.]) self.assertEqual( [100, sys.maxsize], [item[0] for item in queue] ) def test_rank_adjustment(self): """Test rank adjustment""" alloc = scheduler.Allocation() alloc.update([3, 3], 100, 10) alloc.add(scheduler.Application('app1', 1, [1, 1], 'app1')) alloc.add(scheduler.Application('app2', 1, [2, 2], 'app1')) alloc.add(scheduler.Application('app3', 1, [3, 3], 'app1')) queue = list(alloc.utilization_queue([20., 20.])) self.assertEqual(90, queue[0][0]) self.assertEqual(90, queue[1][0]) self.assertEqual(100, queue[2][0]) def test_zerovector(self): """Test updating allocation with allocation vector containing 0's""" alloc = scheduler.Allocation(None) alloc.update([1, 0], None, None) self.assertEqual(1.0, alloc.reserved[0]) self.assertEqual(0, alloc.reserved[1]) def test_utilization_no_reservation(self): """Checks that any utilization without reservation is VERY large.""" alloc = scheduler.Allocation(None) alloc.add(scheduler.Application('app1', 1, [1., 1.], 'app1')) queue = list(alloc.utilization_queue(np.array([10., 10.]))) self.assertEqual(0 / 10, queue[0][1]) self.assertEqual(1 / 10, queue[0][2]) def test_duplicate(self): """Checks behavior when adding duplicate app.""" alloc = scheduler.Allocation(None) alloc.add(scheduler.Application('app1', 0, [1, 1], 'app1')) self.assertEqual( 1, len(list(alloc.utilization_queue(np.array([5., 5.]))))) alloc.add(scheduler.Application('app1', 0, [1, 1], 'app1')) self.assertEqual( 1, len(list(alloc.utilization_queue(np.array([5., 5.]))))) def test_sub_allocs(self): """Test utilization calculation with sub-allocs.""" alloc = scheduler.Allocation([3, 3]) self.assertEqual(3, alloc.total_reserved()[0]) queue = list(alloc.utilization_queue([20., 20.])) sub_alloc_a = scheduler.Allocation([5, 5]) alloc.add_sub_alloc('a1/a', sub_alloc_a) self.assertEqual(8, alloc.total_reserved()[0]) sub_alloc_a.add(scheduler.Application('1a', 3, [2, 2], 'app1')) sub_alloc_a.add(scheduler.Application('2a', 2, [3, 3], 'app1')) sub_alloc_a.add(scheduler.Application('3a', 1, [5, 5], 'app1')) queue = list(alloc.utilization_queue([20., 20.])) _rank, _util_b, util_a, _pending, _order, app = queue[0] self.assertEqual('1a', app.name) self.assertEqual((2 - (5 + 3)) / (20 + (5 + 3)), util_a) sub_alloc_b = scheduler.Allocation([10, 10]) alloc.add_sub_alloc('a1/b', sub_alloc_b) sub_alloc_b.add(scheduler.Application('1b', 3, [2, 2], 'app1')) sub_alloc_b.add(scheduler.Application('2b', 2, [3, 3], 'app1')) sub_alloc_b.add(scheduler.Application('3b', 1, [5, 5], 'app1')) queue = list(alloc.utilization_queue([20., 20.])) self.assertEqual(6, len(queue)) self.assertEqual(18, alloc.total_reserved()[0]) # For each sub-alloc (and self) the least utilized app is 1. # The sub_allloc_b is largest, so utilization smallest, 1b will be # first. _rank, _util_b, util_a, _pending, _order, app = queue[0] self.assertEqual('1b', app.name) self.assertEqual((2 - 18) / (20 + 18), util_a) # Add prio 0 app to each, make sure they all end up last. alloc.add(scheduler.Application('1-zero', 0, [2, 2], 'app1')) sub_alloc_b.add(scheduler.Application('b-zero', 0, [5, 5], 'app1')) sub_alloc_a.add(scheduler.Application('a-zero', 0, [5, 5], 'app1')) queue = list(alloc.utilization_queue([20., 20.])) self.assertIn('1-zero', [item[-1].name for item in queue[-3:]]) self.assertIn('a-zero', [item[-1].name for item in queue[-3:]]) self.assertIn('b-zero', [item[-1].name for item in queue[-3:]]) # Check that utilization of prio 0 apps is always max float. self.assertEqual( [float('inf')] * 3, [ util_b for (_rank, util_b, _util_a, _pending, _order, _app) in queue[-3:] ] ) def test_sub_alloc_reservation(self): """Test utilization calculation is fair between sub-allocs.""" alloc = scheduler.Allocation() sub_alloc_poor = scheduler.Allocation() alloc.add_sub_alloc('poor', sub_alloc_poor) sub_alloc_poor.add(scheduler.Application('p1', 1, [1, 1], 'app1')) sub_alloc_rich = scheduler.Allocation([5, 5]) sub_alloc_rich.add(scheduler.Application('r1', 1, [5, 5], 'app1')) sub_alloc_rich.add(scheduler.Application('r2', 1, [5, 5], 'app1')) alloc.add_sub_alloc('rich', sub_alloc_rich) queue = list(alloc.utilization_queue([20., 20.])) self.assertEqual('r1', queue[0][-1].name) self.assertEqual('p1', queue[1][-1].name) self.assertEqual('r2', queue[2][-1].name) def test_visitor(self): """Test queue visitor""" alloc = scheduler.Allocation() sub_alloc_a = scheduler.Allocation() sub_alloc_a.add(scheduler.Application('a1', 1, [1, 1], 'app1')) alloc.add_sub_alloc('a', sub_alloc_a) sub_alloc_b = scheduler.Allocation() sub_alloc_b.add(scheduler.Application('b1', 1, [5, 5], 'app1')) sub_alloc_b.add(scheduler.Application('b2', 1, [5, 5], 'app1')) alloc.add_sub_alloc('b', sub_alloc_b) result = [] def _visitor(_alloc, entry, _acc_demand): result.append(entry) list(alloc.utilization_queue([20., 20.], visitor=_visitor)) self.assertEqual(6, len(result)) class TraitSetTest(unittest.TestCase): """treadmill.scheduler.TraitSet tests.""" def setUp(self): scheduler.DIMENSION_COUNT = 2 super(TraitSetTest, self).setUp() def test_traits(self): """Test trait inheritance.""" trait_a = int('0b0000001', 2) trait_x = int('0b0000100', 2) trait_y = int('0b0001000', 2) trait_z = int('0b0010000', 2) fset_a = scheduler.TraitSet(trait_a) fset_xz = scheduler.TraitSet(trait_x | trait_z) fset_xy = scheduler.TraitSet(trait_x | trait_y) self.assertTrue(fset_a.has(trait_a)) fset_a.add('xy', fset_xy.traits) self.assertTrue(fset_a.has(trait_a)) self.assertTrue(fset_a.has(trait_x)) self.assertTrue(fset_a.has(trait_y)) fset_a.add('xz', fset_xz.traits) self.assertTrue(fset_a.has(trait_x)) self.assertTrue(fset_a.has(trait_y)) self.assertTrue(fset_a.has(trait_z)) fset_a.remove('xy') self.assertTrue(fset_a.has(trait_x)) self.assertFalse(fset_a.has(trait_y)) self.assertTrue(fset_a.has(trait_z)) fset_a.remove('xz') self.assertFalse(fset_a.has(trait_x)) self.assertFalse(fset_a.has(trait_y)) self.assertFalse(fset_a.has(trait_z)) class NodeTest(unittest.TestCase): """treadmill.scheduler.Allocation tests.""" def setUp(self): scheduler.DIMENSION_COUNT = 2 super(NodeTest, self).setUp() def test_bucket_capacity(self): """Tests adjustment of bucket capacity up and down.""" parent = scheduler.Bucket('top') bucket = scheduler.Bucket('b') parent.add_node(bucket) srv1 = scheduler.Server('n1', [10, 5], valid_until=500) bucket.add_node(srv1) self.assertTrue(np.array_equal(bucket.free_capacity, np.array([10., 5.]))) self.assertTrue(np.array_equal(parent.free_capacity, np.array([10., 5.]))) srv2 = scheduler.Server('n2', [5, 10], valid_until=500) bucket.add_node(srv2) self.assertTrue(np.array_equal(bucket.free_capacity, np.array([10., 10.]))) self.assertTrue(np.array_equal(parent.free_capacity, np.array([10., 10.]))) srv3 = scheduler.Server('n3', [3, 3], valid_until=500) bucket.add_node(srv3) self.assertTrue(np.array_equal(bucket.free_capacity, np.array([10., 10.]))) self.assertTrue(np.array_equal(parent.free_capacity, np.array([10., 10.]))) bucket.remove_node_by_name('n3') self.assertTrue(np.array_equal(bucket.free_capacity, np.array([10., 10.]))) self.assertTrue(np.array_equal(parent.free_capacity, np.array([10., 10.]))) bucket.remove_node_by_name('n1') self.assertTrue(np.array_equal(bucket.free_capacity, np.array([5., 10.]))) self.assertTrue(np.array_equal(parent.free_capacity, np.array([5., 10.]))) def test_app_node_placement(self): """Tests capacity adjustments for app placement.""" parent = scheduler.Bucket('top') bucket = scheduler.Bucket('a_bucket') parent.add_node(bucket) srv1 = scheduler.Server('n1', [10, 5], valid_until=500) bucket.add_node(srv1) srv2 = scheduler.Server('n2', [10, 5], valid_until=500) bucket.add_node(srv2) self.assertTrue(np.array_equal(bucket.free_capacity, np.array([10., 5.]))) self.assertTrue(np.array_equal(parent.free_capacity, np.array([10., 5.]))) self.assertTrue(np.array_equal(bucket.size(None), np.array([20., 10.]))) # Create 10 identical apps. apps = app_list(10, 'app', 50, [1, 2]) self.assertTrue(srv1.put(apps[0])) # Capacity of buckets should not change, other node is intact. self.assertTrue(np.array_equal(bucket.free_capacity, np.array([10., 5.]))) self.assertTrue(np.array_equal(parent.free_capacity, np.array([10., 5.]))) self.assertTrue(srv1.put(apps[1])) self.assertTrue(srv2.put(apps[2])) self.assertTrue(np.array_equal(bucket.free_capacity, np.array([9., 3.]))) self.assertTrue(np.array_equal(parent.free_capacity, np.array([9., 3.]))) def test_bucket_placement(self): """Tests placement strategies.""" top = scheduler.Bucket('top') a_bucket = scheduler.Bucket('a_bucket') top.add_node(a_bucket) b_bucket = scheduler.Bucket('b_bucket') top.add_node(b_bucket) a1_srv = scheduler.Server('a1_srv', [10, 10], valid_until=500) a_bucket.add_node(a1_srv) a2_srv = scheduler.Server('a2_srv', [10, 10], valid_until=500) a_bucket.add_node(a2_srv) b1_srv = scheduler.Server('b1_srv', [10, 10], valid_until=500) b_bucket.add_node(b1_srv) b2_srv = scheduler.Server('b2_srv', [10, 10], valid_until=500) b_bucket.add_node(b2_srv) # bunch of apps with the same affinity apps1 = app_list(10, 'app1', 50, [1, 1]) apps2 = app_list(10, 'app2', 50, [1, 1]) # Default strategy is spread, so placing 4 apps1 will result in each # node having one app. self.assertTrue(top.put(apps1[0])) self.assertTrue(top.put(apps1[1])) self.assertTrue(top.put(apps1[2])) self.assertTrue(top.put(apps1[3])) # from top level, it will spread between a and b buckets, so first # two apps go to a1_srv, b1_srv respectively. # # 3rd app - buckets rotate, and a bucket is preferred again. Inside the # bucket, next node is chosed. Same for 4th app. # # Result is the after 4 placements they are spread evenly. # self.assertEqual(1, len(a1_srv.apps)) self.assertEqual(1, len(a2_srv.apps)) self.assertEqual(1, len(b1_srv.apps)) self.assertEqual(1, len(b2_srv.apps)) a_bucket.set_affinity_strategy('app2', scheduler.PackStrategy) self.assertTrue(top.put(apps2[0])) self.assertTrue(top.put(apps2[1])) self.assertTrue(top.put(apps2[2])) self.assertTrue(top.put(apps2[3])) # B bucket still uses spread strategy. self.assertEqual(2, len(b1_srv.apps)) self.assertEqual(2, len(b2_srv.apps)) # Without predicting exact placement, apps will be placed on one of # the servers in A bucket but not the other, as they use pack strateg. self.assertNotEqual(len(a1_srv.apps), len(a2_srv.apps)) def test_valid_times(self): """Tests node valid_until calculation.""" top = scheduler.Bucket('top', traits=_traits2int(['top'])) left = scheduler.Bucket('left', traits=_traits2int(['left'])) right = scheduler.Bucket('right', traits=_traits2int(['right'])) srv_a = scheduler.Server('a', [10, 10], traits=_traits2int(['a', '0']), valid_until=1) srv_b = scheduler.Server('b', [10, 10], traits=_traits2int(['b', '0']), valid_until=2) srv_y = scheduler.Server('y', [10, 10], traits=_traits2int(['y', '1']), valid_until=3) srv_z = scheduler.Server('z', [10, 10], traits=_traits2int(['z', '1']), valid_until=4) top.add_node(left) top.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) self.assertEqual(top.valid_until, 4) self.assertEqual(left.valid_until, 2) self.assertEqual(right.valid_until, 4) left.remove_node_by_name('a') self.assertEqual(top.valid_until, 4) self.assertEqual(left.valid_until, 2) self.assertEqual(right.valid_until, 4) right.remove_node_by_name('z') self.assertEqual(top.valid_until, 3) self.assertEqual(left.valid_until, 2) self.assertEqual(right.valid_until, 3) def test_node_traits(self): """Tests node trait inheritance.""" top = scheduler.Bucket('top', traits=_traits2int(['top'])) left = scheduler.Bucket('left', traits=_traits2int(['left'])) right = scheduler.Bucket('right', traits=_traits2int(['right'])) srv_a = scheduler.Server('a', [10, 10], traits=_traits2int(['a', '0']), valid_until=500) srv_b = scheduler.Server('b', [10, 10], traits=_traits2int(['b', '0']), valid_until=500) srv_y = scheduler.Server('y', [10, 10], traits=_traits2int(['y', '1']), valid_until=500) srv_z = scheduler.Server('z', [10, 10], traits=_traits2int(['z', '1']), valid_until=500) top.add_node(left) top.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) self.assertTrue(top.traits.has(_trait2int('a'))) self.assertTrue(top.traits.has(_trait2int('b'))) self.assertTrue(top.traits.has(_trait2int('0'))) self.assertTrue(top.traits.has(_trait2int('y'))) self.assertTrue(top.traits.has(_trait2int('z'))) self.assertTrue(top.traits.has(_trait2int('1'))) self.assertTrue(left.traits.has(_trait2int('a'))) self.assertTrue(left.traits.has(_trait2int('b'))) self.assertTrue(left.traits.has(_trait2int('0'))) self.assertFalse(left.traits.has(_trait2int('y'))) self.assertFalse(left.traits.has(_trait2int('z'))) self.assertFalse(left.traits.has(_trait2int('1'))) left.remove_node_by_name('a') self.assertFalse(left.traits.has(_trait2int('a'))) self.assertTrue(left.traits.has(_trait2int('b'))) self.assertTrue(left.traits.has(_trait2int('0'))) self.assertFalse(top.traits.has(_trait2int('a'))) self.assertTrue(top.traits.has(_trait2int('b'))) self.assertTrue(top.traits.has(_trait2int('0'))) left.remove_node_by_name('b') self.assertFalse(left.traits.has(_trait2int('b'))) self.assertFalse(left.traits.has(_trait2int('0'))) self.assertFalse(top.traits.has(_trait2int('b'))) self.assertFalse(top.traits.has(_trait2int('0'))) def test_app_trait_placement(self): """Tests placement of app with traits.""" top = scheduler.Bucket('top', traits=_traits2int(['top'])) left = scheduler.Bucket('left', traits=_traits2int(['left'])) right = scheduler.Bucket('right', traits=_traits2int(['right'])) srv_a = scheduler.Server('a', [10, 10], traits=_traits2int(['a', '0']), valid_until=500) srv_b = scheduler.Server('b', [10, 10], traits=_traits2int(['b', '0']), valid_until=500) srv_y = scheduler.Server('y', [10, 10], traits=_traits2int(['y', '1']), valid_until=500) srv_z = scheduler.Server('z', [10, 10], traits=_traits2int(['z', '1']), valid_until=500) top.add_node(left) top.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) alloc_a = scheduler.Allocation(traits=_traits2int(['a'])) apps_a = app_list(10, 'app_a', 50, [2, 2]) for app in apps_a: alloc_a.add(app) # srv_a is the only one with trait 'a'. self.assertTrue(top.put(apps_a[0])) self.assertTrue(top.put(apps_a[1])) self.assertIn(apps_a[0].name, srv_a.apps) self.assertIn(apps_a[1].name, srv_a.apps) apps_b = app_list(10, 'app_b', 50, [2, 2], traits=_traits2int(['b'])) # srv_b is the only one with trait 'b'. self.assertTrue(top.put(apps_b[0])) self.assertTrue(top.put(apps_b[1])) self.assertIn(apps_b[0].name, srv_b.apps) self.assertIn(apps_b[1].name, srv_b.apps) apps_ab = app_list(10, 'app_ab', 50, [2, 2], traits=_traits2int(['b'])) for app in apps_ab: alloc_a.add(app) # there is no server with both 'a' and 'b' traits. self.assertFalse(top.put(apps_ab[0])) self.assertFalse(top.put(apps_ab[1])) alloc_0 = scheduler.Allocation(traits=_traits2int(['0'])) apps_0 = app_list(10, 'app_0', 50, [2, 2]) for app in apps_0: alloc_0.add(app) # '0' trait - two servers, will spread by default. self.assertTrue(top.put(apps_0[0])) self.assertTrue(top.put(apps_0[1])) self.assertIn(apps_0[0].name, srv_a.apps) self.assertIn(apps_0[1].name, srv_b.apps) apps_a0 = app_list(10, 'app_a0', 50, [2, 2], traits=_traits2int(['a'])) for app in apps_a0: alloc_0.add(app) # srv_a is the only one with traits 'a' and '0'. self.assertTrue(top.put(apps_a0[0])) self.assertTrue(top.put(apps_a0[1])) self.assertIn(apps_a0[0].name, srv_a.apps) self.assertIn(apps_a0[1].name, srv_a.apps) # Prev implementation propagated traits from parent to children, # so "right" trait propagated to leaf servers. # # This behavior is removed, so placing app with "right" trait will # fail. # # alloc_r1 = scheduler.Allocation(traits=_traits2int(['right', '1'])) # apps_r1 = app_list(10, 'app_r1', 50, [2, 2]) # for app in apps_r1: # alloc_r1.add(app) # self.assertTrue(top.put(apps_r1[0])) # self.assertTrue(top.put(apps_r1[1])) # self.assertIn(apps_r1[0].name, srv_y.apps) # self.assertIn(apps_r1[1].name, srv_z.apps) apps_nothing = app_list(10, 'apps_nothing', 50, [1, 1]) # All nodes fit. Spead first between buckets, then between nodes. # top # left right # a b y z self.assertTrue(top.put(apps_nothing[0])) self.assertTrue(top.put(apps_nothing[1])) self.assertTrue( ( apps_nothing[0].server in ['a', 'b'] and apps_nothing[1].server in ['y', 'z'] ) or ( apps_nothing[0].server in ['y', 'z'] and apps_nothing[1].server in ['a', 'b'] ) ) self.assertTrue(top.put(apps_nothing[2])) self.assertTrue(top.put(apps_nothing[3])) self.assertTrue( ( apps_nothing[2].server in ['a', 'b'] and apps_nothing[3].server in ['y', 'z'] ) or ( apps_nothing[2].server in ['y', 'z'] and apps_nothing[3].server in ['a', 'b'] ) ) def test_size_and_members(self): """Tests recursive size calculation.""" top = scheduler.Bucket('top', traits=_traits2int(['top'])) left = scheduler.Bucket('left', traits=_traits2int(['left'])) right = scheduler.Bucket('right', traits=_traits2int(['right'])) srv_a = scheduler.Server('a', [1, 1], traits=_traits2int(['a', '0']), valid_until=500) srv_b = scheduler.Server('b', [1, 1], traits=_traits2int(['b', '0']), valid_until=500) srv_y = scheduler.Server('y', [1, 1], traits=_traits2int(['y', '1']), valid_until=500) srv_z = scheduler.Server('z', [1, 1], traits=_traits2int(['z', '1']), valid_until=500) top.add_node(left) top.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) # pylint: disable=W0212 self.assertTrue(scheduler._all_isclose(srv_a.size(None), [1, 1])) self.assertTrue(scheduler._all_isclose(left.size(None), [2, 2])) self.assertTrue(scheduler._all_isclose(top.size(None), [4, 4])) self.assertEqual( { 'a': srv_a, 'b': srv_b, 'y': srv_y, 'z': srv_z }, top.members() ) def test_affinity_counters(self): """Tests affinity counters.""" top = scheduler.Bucket('top', traits=_traits2int(['top'])) left = scheduler.Bucket('left', traits=_traits2int(['left'])) right = scheduler.Bucket('right', traits=_traits2int(['right'])) srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500) srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500) srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500) srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500) top.add_node(left) top.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) apps_a = app_list(10, 'app_a', 50, [1, 1]) self.assertTrue(srv_a.put(apps_a[0])) self.assertEqual(1, srv_a.affinity_counters['app_a']) self.assertEqual(1, left.affinity_counters['app_a']) self.assertEqual(1, top.affinity_counters['app_a']) srv_z.put(apps_a[0]) self.assertEqual(1, srv_z.affinity_counters['app_a']) self.assertEqual(1, left.affinity_counters['app_a']) self.assertEqual(2, top.affinity_counters['app_a']) srv_a.remove(apps_a[0].name) self.assertEqual(0, srv_a.affinity_counters['app_a']) self.assertEqual(0, left.affinity_counters['app_a']) self.assertEqual(1, top.affinity_counters['app_a']) class CellTest(unittest.TestCase): """treadmill.scheduler.Cell tests.""" def setUp(self): scheduler.DIMENSION_COUNT = 2 super(CellTest, self).setUp() def test_emtpy(self): """Simple test to test empty bucket""" cell = scheduler.Cell('top') empty = scheduler.Bucket('empty', traits=0) cell.add_node(empty) bucket = scheduler.Bucket('bucket', traits=0) srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500) bucket.add_node(srv_a) cell.add_node(bucket) cell.schedule() def test_labels(self): """Test scheduling with labels.""" cell = scheduler.Cell('top') left = scheduler.Bucket('left', traits=0) right = scheduler.Bucket('right', traits=0) srv_a = scheduler.Server('a_xx', [10, 10], valid_until=500, label='xx') srv_b = scheduler.Server('b', [10, 10], valid_until=500) srv_y = scheduler.Server('y_xx', [10, 10], valid_until=500, label='xx') srv_z = scheduler.Server('z', [10, 10], valid_until=500) cell.add_node(left) cell.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) app1 = scheduler.Application('app1', 4, [1, 1], 'app') app2 = scheduler.Application('app2', 3, [2, 2], 'app') app3 = scheduler.Application('app_xx_3', 2, [3, 3], 'app') app4 = scheduler.Application('app_xx_4', 1, [4, 4], 'app') cell.partitions[None].allocation.add(app1) cell.partitions[None].allocation.add(app2) cell.partitions['xx'].allocation.add(app3) cell.partitions['xx'].allocation.add(app4) cell.schedule() self.assertIn(app1.server, ['b', 'z']) self.assertIn(app2.server, ['b', 'z']) self.assertIn(app3.server, ['a_xx', 'y_xx']) self.assertIn(app4.server, ['a_xx', 'y_xx']) def test_simple(self): """Simple placement test.""" # pylint - too many lines. # # pylint: disable=R0915 cell = scheduler.Cell('top') left = scheduler.Bucket('left', traits=0) right = scheduler.Bucket('right', traits=0) srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500) srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500) srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500) srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500) cell.add_node(left) cell.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) app1 = scheduler.Application('app1', 4, [1, 1], 'app') app2 = scheduler.Application('app2', 3, [2, 2], 'app') app3 = scheduler.Application('app3', 2, [3, 3], 'app') app4 = scheduler.Application('app4', 1, [4, 4], 'app') cell.partitions[None].allocation.add(app1) cell.partitions[None].allocation.add(app2) cell.partitions[None].allocation.add(app3) cell.partitions[None].allocation.add(app4) cell.schedule() self.assertEqual( set([app1.server, app2.server, app3.server, app4.server]), set(['a', 'y', 'b', 'z']) ) srv1 = app1.server srv2 = app2.server srv3 = app3.server srv4 = app4.server # Add high priority app that needs entire cell app_prio50 = scheduler.Application('prio50', 50, [10, 10], 'app') cell.partitions[None].allocation.add(app_prio50) cell.schedule() # The queue is ordered by priority: # - prio50, app1, app2, app3, app4 # # As placement not found for prio50, app4 will be evicted first. # # As result, prio50 will be placed on 'z', and app4 (evicted) will be # placed on "next" server, which is 'a'. self.assertEqual(app_prio50.server, srv4) self.assertEqual(app4.server, srv1) app_prio51 = scheduler.Application('prio51', 51, [10, 10], 'app') cell.partitions[None].allocation.add(app_prio51) cell.schedule() # app4 is now colocated with app1. app4 will still be evicted first, # then app3, at which point there will be enough capacity to place # large app. # # app3 will be rescheduled to run on "next" server - 'y', and app4 will # be restored to 'a'. self.assertEqual(app_prio51.server, srv3) self.assertEqual(app_prio50.server, srv4) self.assertEqual(app4.server, srv1) app_prio49_1 = scheduler.Application('prio49_1', 49, [10, 10], 'app') app_prio49_2 = scheduler.Application('prio49_2', 49, [9, 9], 'app') cell.partitions[None].allocation.add(app_prio49_1) cell.partitions[None].allocation.add(app_prio49_2) cell.schedule() # 50/51 not moved. from the end of the queue, self.assertEqual(app_prio51.server, srv3) self.assertEqual(app_prio50.server, srv4) self.assertEqual( set([app_prio49_1.server, app_prio49_2.server]), set([srv1, srv2]) ) # Only capacity left for small [1, 1] app. self.assertIsNotNone(app1.server) self.assertIsNone(app2.server) self.assertIsNone(app3.server) self.assertIsNone(app4.server) def test_max_utilization(self): """Test max-utilization is handled properly when priorities change""" cell = scheduler.Cell('top') left = scheduler.Bucket('left', traits=0) right = scheduler.Bucket('right', traits=0) srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500) srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500) srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500) srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500) cell.add_node(left) cell.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) app1 = scheduler.Application('app1', 4, [1, 1], 'app') app2 = scheduler.Application('app2', 3, [2, 2], 'app') app3 = scheduler.Application('app3', 2, [3, 3], 'app') app4 = scheduler.Application('app4', 1, [4, 4], 'app') cell.partitions[None].allocation.add(app1) cell.partitions[None].allocation.add(app2) cell.partitions[None].allocation.add(app3) cell.partitions[None].allocation.add(app4) cell.partitions[None].allocation.set_reserved([6, 6]) cell.partitions[None].allocation.set_max_utilization(1) cell.schedule() self.assertIsNotNone(app1.server) self.assertIsNotNone(app2.server) self.assertIsNotNone(app3.server) self.assertIsNone(app4.server) app4.priority = 5 cell.schedule() self.assertIsNotNone(app1.server) self.assertIsNone(app2.server) self.assertIsNone(app3.server) self.assertIsNotNone(app4.server) def test_affinity_limits_bunker(self): """Simple placement test with bunker in level""" cell = scheduler.Cell('top') bunker1 = scheduler.Bucket('bunker1', traits=0) bunker2 = scheduler.Bucket('bunker2', traits=0) b1_left = scheduler.Bucket('b1_left', traits=0) b1_right = scheduler.Bucket('b1_right', traits=0) b2 = scheduler.Bucket('b2', traits=0) srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500) srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500) srv_c = scheduler.Server('c', [10, 10], traits=0, valid_until=500) srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500) srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500) cell.add_node(bunker1) cell.add_node(bunker2) bunker1.add_node(b1_left) bunker1.add_node(b1_right) bunker2.add_node(b2) b1_left.add_node(srv_a) b1_left.add_node(srv_b) b1_right.add_node(srv_c) b2.add_node(srv_y) b2.add_node(srv_z) bunker1.level = 'bunker' bunker2.level = 'bunker' b1_left.level = 'rack' b1_right.level = 'rack' b2.level = 'rack' apps = app_list(10, 'app', 50, [1, 1], affinity_limits={'server': 1, 'bunker': 1}) cell.add_app(cell.partitions[None].allocation, apps[0]) cell.add_app(cell.partitions[None].allocation, apps[1]) cell.add_app(cell.partitions[None].allocation, apps[2]) cell.add_app(cell.partitions[None].allocation, apps[3]) cell.schedule() self.assertIsNotNone(apps[0].server) self.assertIsNotNone(apps[1].server) self.assertIsNone(apps[2].server) self.assertIsNone(apps[3].server) apps = app_list(10, 'app', 50, [1, 1], affinity_limits={'server': 1, 'rack': 1, 'bunker': 2}) for app in apps: cell.remove_app(app.name) cell.add_app(cell.partitions[None].allocation, apps[0]) cell.add_app(cell.partitions[None].allocation, apps[1]) cell.add_app(cell.partitions[None].allocation, apps[2]) cell.add_app(cell.partitions[None].allocation, apps[3]) cell.schedule() self.assertIsNotNone(apps[0].server) self.assertIsNotNone(apps[1].server) self.assertIsNotNone(apps[2].server) self.assertIsNone(apps[3].server) def test_affinity_limits_levels(self): """Simple placement test with 2 layer of bucket""" # pylint: disable=too-many-statements cell = scheduler.Cell('top') group1 = scheduler.Bucket('group1', traits=0) group2 = scheduler.Bucket('group2', traits=0) g1_left = scheduler.Bucket('g1_left', traits=0) g1_right = scheduler.Bucket('g1_right', traits=0) g2_left = scheduler.Bucket('g2_left', traits=0) g2_right = scheduler.Bucket('g2_right', traits=0) srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500) srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500) srv_c = scheduler.Server('c', [10, 10], traits=0, valid_until=500) srv_x = scheduler.Server('x', [10, 10], traits=0, valid_until=500) srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500) srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500) cell.add_node(group1) cell.add_node(group2) group1.add_node(g1_left) group1.add_node(g1_right) group2.add_node(g2_left) group2.add_node(g2_right) g1_left.add_node(srv_a) g1_left.add_node(srv_b) g1_right.add_node(srv_c) g2_left.add_node(srv_x) g2_right.add_node(srv_y) g2_right.add_node(srv_z) g1_left.level = 'rack' g1_right.level = 'rack' g2_left.level = 'rack' g2_right.level = 'rack' apps = app_list(10, 'app', 50, [1, 1], affinity_limits={'server': 1}) cell.add_app(cell.partitions[None].allocation, apps[0]) cell.add_app(cell.partitions[None].allocation, apps[1]) cell.add_app(cell.partitions[None].allocation, apps[2]) cell.add_app(cell.partitions[None].allocation, apps[3]) cell.add_app(cell.partitions[None].allocation, apps[4]) cell.add_app(cell.partitions[None].allocation, apps[5]) cell.add_app(cell.partitions[None].allocation, apps[6]) cell.schedule() self.assertIsNotNone(apps[0].server) self.assertIsNotNone(apps[1].server) self.assertIsNotNone(apps[2].server) self.assertIsNotNone(apps[3].server) self.assertIsNotNone(apps[4].server) self.assertIsNotNone(apps[5].server) self.assertIsNone(apps[6].server) for app in apps: cell.remove_app(app.name) apps = app_list(10, 'app', 50, [1, 1], affinity_limits={'server': 1, 'rack': 1}) cell.add_app(cell.partitions[None].allocation, apps[0]) cell.add_app(cell.partitions[None].allocation, apps[1]) cell.add_app(cell.partitions[None].allocation, apps[2]) cell.add_app(cell.partitions[None].allocation, apps[3]) cell.add_app(cell.partitions[None].allocation, apps[4]) cell.add_app(cell.partitions[None].allocation, apps[5]) cell.schedule() self.assertIsNotNone(apps[0].server) self.assertIsNotNone(apps[1].server) self.assertIsNotNone(apps[2].server) self.assertIsNotNone(apps[3].server) self.assertIsNone(apps[4].server) self.assertIsNone(apps[5].server) apps = app_list(10, 'app', 50, [1, 1], affinity_limits={'server': 1, 'rack': 2, 'cell': 3}) for app in apps: cell.remove_app(app.name) cell.add_app(cell.partitions[None].allocation, apps[0]) cell.add_app(cell.partitions[None].allocation, apps[1]) cell.add_app(cell.partitions[None].allocation, apps[2]) cell.add_app(cell.partitions[None].allocation, apps[3]) cell.schedule() self.assertIsNotNone(apps[0].server) self.assertIsNotNone(apps[1].server) self.assertIsNotNone(apps[2].server) self.assertIsNone(apps[3].server) def test_affinity_limits(self): """Simple placement test.""" cell = scheduler.Cell('top') left = scheduler.Bucket('left', traits=0) right = scheduler.Bucket('right', traits=0) srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500) srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500) srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500) srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500) cell.add_node(left) cell.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) left.level = 'rack' right.level = 'rack' apps = app_list(10, 'app', 50, [1, 1], affinity_limits={'server': 1}) cell.add_app(cell.partitions[None].allocation, apps[0]) cell.add_app(cell.partitions[None].allocation, apps[1]) cell.add_app(cell.partitions[None].allocation, apps[2]) cell.add_app(cell.partitions[None].allocation, apps[3]) cell.add_app(cell.partitions[None].allocation, apps[4]) cell.schedule() self.assertIsNotNone(apps[0].server) self.assertIsNotNone(apps[1].server) self.assertIsNotNone(apps[2].server) self.assertIsNotNone(apps[3].server) self.assertIsNone(apps[4].server) for app in apps: cell.remove_app(app.name) apps = app_list(10, 'app', 50, [1, 1], affinity_limits={'server': 1, 'rack': 1}) cell.add_app(cell.partitions[None].allocation, apps[0]) cell.add_app(cell.partitions[None].allocation, apps[1]) cell.add_app(cell.partitions[None].allocation, apps[2]) cell.add_app(cell.partitions[None].allocation, apps[3]) cell.schedule() self.assertIsNotNone(apps[0].server) self.assertIsNotNone(apps[1].server) self.assertIsNone(apps[2].server) self.assertIsNone(apps[3].server) for app in apps: cell.remove_app(app.name) apps = app_list(10, 'app', 50, [1, 1], affinity_limits={'server': 1, 'rack': 2, 'cell': 3}) cell.add_app(cell.partitions[None].allocation, apps[0]) cell.add_app(cell.partitions[None].allocation, apps[1]) cell.add_app(cell.partitions[None].allocation, apps[2]) cell.add_app(cell.partitions[None].allocation, apps[3]) cell.schedule() self.assertIsNotNone(apps[0].server) self.assertIsNotNone(apps[1].server) self.assertIsNotNone(apps[2].server) self.assertIsNone(apps[3].server) @mock.patch('time.time', mock.Mock(return_value=0)) def test_data_retention_levels(self): """Tests data retention.""" cell = scheduler.Cell('top') group1 = scheduler.Bucket('group1', traits=0) group2 = scheduler.Bucket('group2', traits=0) g1_left = scheduler.Bucket('g1_left', traits=0) g1_right = scheduler.Bucket('g1_right', traits=0) g2 = scheduler.Bucket('g2', traits=0) srvs = { 'a': scheduler.Server('a', [10, 10], traits=0, valid_until=500), 'b': scheduler.Server('b', [10, 10], traits=0, valid_until=500), 'c': scheduler.Server('c', [10, 10], traits=0, valid_until=500), 'y': scheduler.Server('y', [10, 10], traits=0, valid_until=500), 'z': scheduler.Server('z', [10, 10], traits=0, valid_until=500), } cell.add_node(group1) cell.add_node(group2) group1.add_node(g1_left) group1.add_node(g1_right) group2.add_node(g2) g1_left.add_node(srvs['a']) g1_left.add_node(srvs['b']) g1_right.add_node(srvs['c']) g2.add_node(srvs['y']) g2.add_node(srvs['z']) g1_left.level = 'rack' g1_right.level = 'rack' g2.level = 'rack' time.time.return_value = 100 sticky_apps = app_list(10, 'sticky', 50, [1, 1], affinity_limits={'server': 1, 'rack': 1}, data_retention_timeout=30) unsticky_app = scheduler.Application('unsticky', 10, [1., 1.], 'unsticky', data_retention_timeout=0) cell.partitions[None].allocation.add(sticky_apps[0]) cell.partitions[None].allocation.add(unsticky_app) cell.schedule() # Both apps having different affinity, will be on same node. first_srv = sticky_apps[0].server self.assertEqual(sticky_apps[0].server, unsticky_app.server) # Mark srv_a as down, unsticky app migrates right away, # sticky stays. srvs[first_srv].state = scheduler.State.down cell.schedule() self.assertEqual(sticky_apps[0].server, first_srv) self.assertNotEqual(unsticky_app.server, first_srv) self.assertEqual(cell.next_event_at, 130) time.time.return_value = 110 cell.schedule() self.assertEqual(sticky_apps[0].server, first_srv) self.assertNotEqual(unsticky_app.server, first_srv) self.assertEqual(cell.next_event_at, 130) time.time.return_value = 130 cell.schedule() self.assertNotEqual(sticky_apps[0].server, first_srv) self.assertNotEqual(unsticky_app.server, first_srv) self.assertEqual(cell.next_event_at, np.inf) @mock.patch('time.time', mock.Mock(return_value=0)) def test_data_retention(self): """Tests data retention.""" # Disable pylint's too many statements warning. # # pylint: disable=R0915 cell = scheduler.Cell('top') left = scheduler.Bucket('left', traits=0) right = scheduler.Bucket('right', traits=0) srvs = { 'a': scheduler.Server('a', [10, 10], traits=0, valid_until=500), 'b': scheduler.Server('b', [10, 10], traits=0, valid_until=500), 'y': scheduler.Server('y', [10, 10], traits=0, valid_until=500), 'z': scheduler.Server('z', [10, 10], traits=0, valid_until=500), } cell.add_node(left) cell.add_node(right) left.add_node(srvs['a']) left.add_node(srvs['b']) right.add_node(srvs['y']) right.add_node(srvs['z']) left.level = 'rack' right.level = 'rack' time.time.return_value = 100 sticky_apps = app_list(10, 'sticky', 50, [1, 1], affinity_limits={'server': 1, 'rack': 1}, data_retention_timeout=30) unsticky_app = scheduler.Application('unsticky', 10, [1., 1.], 'unsticky', data_retention_timeout=0) cell.partitions[None].allocation.add(sticky_apps[0]) cell.partitions[None].allocation.add(unsticky_app) cell.schedule() # Both apps having different affinity, will be on same node. first_srv = sticky_apps[0].server self.assertEqual(sticky_apps[0].server, unsticky_app.server) # Mark srv_a as down, unsticky app migrates right away, # sticky stays. srvs[first_srv].state = scheduler.State.down cell.schedule() self.assertEqual(sticky_apps[0].server, first_srv) self.assertNotEqual(unsticky_app.server, first_srv) self.assertEqual(cell.next_event_at, 130) time.time.return_value = 110 cell.schedule() self.assertEqual(sticky_apps[0].server, first_srv) self.assertNotEqual(unsticky_app.server, first_srv) self.assertEqual(cell.next_event_at, 130) time.time.return_value = 130 cell.schedule() self.assertNotEqual(sticky_apps[0].server, first_srv) self.assertNotEqual(unsticky_app.server, first_srv) self.assertEqual(cell.next_event_at, np.inf) second_srv = sticky_apps[0].server # Mark srv_a as up, srv_y as down. srvs[first_srv].state = scheduler.State.up srvs[second_srv].state = scheduler.State.down cell.schedule() self.assertEqual(sticky_apps[0].server, second_srv) self.assertNotEqual(unsticky_app.server, second_srv) self.assertEqual(cell.next_event_at, 160) # Schedule one more sticky app. As it has rack affinity limit 1, it # can't to to right (x,y) rack, rather will end up in left (a,b) rack. # # Other sticky apps will be pending. time.time.return_value = 135 cell.partitions[None].allocation.add(sticky_apps[1]) cell.partitions[None].allocation.add(sticky_apps[2]) cell.schedule() # Original app still on 'y', timeout did not expire self.assertEqual(sticky_apps[0].server, second_srv) # next sticky app is on (a,b) rack. # self.assertIn(sticky_apps[1].server, ['a', 'b']) # The 3rd sticky app pending, as rack affinity taken by currently # down node y. self.assertIsNone(sticky_apps[2].server) srvs[second_srv].state = scheduler.State.up cell.schedule() # Original app still on 'y', timeout did not expire self.assertEqual(sticky_apps[0].server, second_srv) # next sticky app is on (a,b) rack. # self.assertIn(sticky_apps[1].server, ['a', 'b']) # The 3rd sticky app pending, as rack affinity taken by currently # app[0] on node y. self.assertIsNone(sticky_apps[2].server) def test_serialization(self): """Tests cell serialization.""" # Disable pylint's too many statements warning. # # pylint: disable=R0915 cell = scheduler.Cell('top') left = scheduler.Bucket('left', traits=0) right = scheduler.Bucket('right', traits=0) srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500) srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500) srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500) srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500) cell.add_node(left) cell.add_node(right) left.add_node(srv_a) left.add_node(srv_b) right.add_node(srv_y) right.add_node(srv_z) left.level = 'rack' right.level = 'rack' apps = app_list(10, 'app', 50, [1, 1], affinity_limits={'server': 1, 'rack': 1}) cell.add_app(cell.partitions[None].allocation, apps[0]) cell.add_app(cell.partitions[None].allocation, apps[1]) cell.add_app(cell.partitions[None].allocation, apps[2]) cell.add_app(cell.partitions[None].allocation, apps[3]) cell.schedule() # TODO: need to implement serialization. # # data = scheduler.dumps(cell) # cell1 = scheduler.loads(data) def test_identity(self): """Tests scheduling apps with identity.""" cell = scheduler.Cell('top') for idx in range(0, 10): server = scheduler.Server(str(idx), [10, 10], traits=0, valid_until=time.time() + 1000) cell.add_node(server) cell.configure_identity_group('ident1', 3) apps = app_list(10, 'app', 50, [1, 1], identity_group='ident1') for app in apps: cell.add_app(cell.partitions[None].allocation, app) self.assertTrue(apps[0].acquire_identity()) self.assertEqual(set([1, 2]), apps[0].identity_group_ref.available) self.assertEqual(set([1, 2]), apps[1].identity_group_ref.available) cell.schedule() self.assertEqual(apps[0].identity, 0) self.assertEqual(apps[1].identity, 1) self.assertEqual(apps[2].identity, 2) for idx in range(3, 10): self.assertIsNone(apps[idx].identity, None) # Removing app will release the identity, and it will be aquired by # next app in the group. cell.remove_app('app-2') cell.schedule() self.assertEqual(apps[3].identity, 2) # Increase ideneity group count to 5, expect 5 placed apps. cell.configure_identity_group('ident1', 5) cell.schedule() self.assertEqual( 5, len([app for app in apps if app.server is not None]) ) cell.configure_identity_group('ident1', 3) cell.schedule() self.assertEqual( 3, len([app for app in apps if app.server is not None]) ) def test_schedule_once(self): """Tests schedule once trait on server down.""" cell = scheduler.Cell('top') for idx in range(0, 10): server = scheduler.Server(str(idx), [10, 10], traits=0, valid_until=time.time() + 1000) cell.add_node(server) apps = app_list(2, 'app', 50, [6, 6], schedule_once=True) for app in apps: cell.add_app(cell.partitions[None].allocation, app) cell.schedule() self.assertNotEqual(apps[0].server, apps[1].server) self.assertFalse(apps[0].evicted) self.assertFalse(apps[0].evicted) cell.children_by_name[apps[0].server].state = scheduler.State.down cell.remove_node_by_name(apps[1].server) cell.schedule() self.assertIsNone(apps[0].server) self.assertTrue(apps[0].evicted) self.assertIsNone(apps[1].server) self.assertTrue(apps[1].evicted) def test_schedule_once_eviction(self): """Tests schedule once trait with eviction.""" cell = scheduler.Cell('top') for idx in range(0, 10): server = scheduler.Server(str(idx), [10, 10], traits=0, valid_until=time.time() + 1000) cell.add_node(server) # Each server has capacity 10. # # Place two apps - capacity 1, capacity 8, they will occupy entire # server. # # Try and place app with demand of 2. First it will try to evict # small app, but it will not be enough, so it will evict large app. # # Check that evicted flag is set only for large app, and small app # will be restored. small_apps = app_list(10, 'small', 50, [1, 1], schedule_once=True) for app in small_apps: cell.add_app(cell.partitions[None].allocation, app) large_apps = app_list(10, 'large', 60, [8, 8], schedule_once=True) for app in large_apps: cell.add_app(cell.partitions[None].allocation, app) placement = cell.schedule() # Check that all apps are placed. app2server = {app: after for app, _, _, after, _ in placement if after is not None} self.assertEqual(len(app2server), 20) # Add one app, higher priority than rest, will force eviction. medium_apps = app_list(1, 'medium', 70, [5, 5]) for app in medium_apps: cell.add_app(cell.partitions[None].allocation, app) cell.schedule() self.assertEqual(len([app for app in small_apps if app.evicted]), 0) self.assertEqual(len([app for app in small_apps if app.server]), 10) self.assertEqual(len([app for app in large_apps if app.evicted]), 1) self.assertEqual(len([app for app in large_apps if app.server]), 9) # Remove app, make sure the evicted app is not placed again. cell.remove_app(medium_apps[0].name) cell.schedule() self.assertEqual(len([app for app in small_apps if app.evicted]), 0) self.assertEqual(len([app for app in small_apps if app.server]), 10) self.assertEqual(len([app for app in large_apps if app.evicted]), 1) self.assertEqual(len([app for app in large_apps if app.server]), 9) @mock.patch('time.time', mock.Mock(return_value=100)) def test_eviction_server_down(self): """Tests app restore.""" cell = scheduler.Cell('top') large_server = scheduler.Server('large', [10, 10], traits=0, valid_until=10000) cell.add_node(large_server) small_server = scheduler.Server('small', [3, 3], traits=0, valid_until=10000) cell.add_node(small_server) # Create two apps one with retention other without. Set priority # so that app with retention is on the right of the queue, when # placement not found for app without retention, it will try to # evict app with retention. app_no_retention = scheduler.Application('a1', 100, [4, 4], 'app') app_with_retention = scheduler.Application('a2', 1, [4, 4], 'app', data_retention_timeout=3000) cell.add_app(cell.partitions[None].allocation, app_no_retention) cell.add_app(cell.partitions[None].allocation, app_with_retention) cell.schedule() # At this point, both apps are on large server, as small server does # not have capacity. self.assertEqual('large', app_no_retention.server) self.assertEqual('large', app_with_retention.server) # Mark large server down. App with retention will remain on the server. # App without retention should be pending. large_server.state = scheduler.State.down cell.schedule() self.assertEqual(None, app_no_retention.server) self.assertEqual('large', app_with_retention.server) @mock.patch('time.time', mock.Mock(return_value=100)) def test_restore(self): """Tests app restore.""" cell = scheduler.Cell('top') large_server = scheduler.Server('large', [10, 10], traits=0, valid_until=200) cell.add_node(large_server) small_server = scheduler.Server('small', [3, 3], traits=0, valid_until=1000) cell.add_node(small_server) apps = app_list(1, 'app', 50, [6, 6], lease=50) for app in apps: cell.add_app(cell.partitions[None].allocation, app) # 100 sec left, app lease is 50, should fit. time.time.return_value = 100 cell.schedule() self.assertEqual(apps[0].server, 'large') time.time.return_value = 190 apps_not_fit = app_list(1, 'app-not-fit', 90, [6, 6], lease=50) for app in apps_not_fit: cell.add_app(cell.partitions[None].allocation, app) cell.schedule() self.assertIsNone(apps_not_fit[0].server) self.assertEqual(apps[0].server, 'large') @mock.patch('time.time', mock.Mock(return_value=10)) def test_renew(self): """Tests app restore.""" cell = scheduler.Cell('top') server_a = scheduler.Server('a', [10, 10], traits=0, valid_until=1000) cell.add_node(server_a) apps = app_list(1, 'app', 50, [6, 6], lease=50) for app in apps: cell.add_app(cell.partitions[None].allocation, app) cell.schedule() self.assertEqual(apps[0].server, 'a') self.assertEqual(apps[0].placement_expiry, 60) time.time.return_value = 100 cell.schedule() self.assertEqual(apps[0].server, 'a') self.assertEqual(apps[0].placement_expiry, 60) time.time.return_value = 200 apps[0].renew = True cell.schedule() self.assertEqual(apps[0].server, 'a') self.assertEqual(apps[0].placement_expiry, 250) self.assertFalse(apps[0].renew) # fast forward to 975, close to server 'a' expiration, app will # migratoe to 'b' on renew. server_b = scheduler.Server('b', [10, 10], traits=0, valid_until=2000) cell.add_node(server_b) time.time.return_value = 975 apps[0].renew = True cell.schedule() self.assertEqual(apps[0].server, 'b') self.assertEqual(apps[0].placement_expiry, 1025) self.assertFalse(apps[0].renew) # fast forward to 1975, when app can't be renewed on server b, but # there is not alternative placement. time.time.return_value = 1975 apps[0].renew = True cell.schedule() self.assertEqual(apps[0].server, 'b') # Placement expiry did not change, as placement was not found. self.assertEqual(apps[0].placement_expiry, 1025) # Renew flag is not cleared, as new placement was not found. self.assertTrue(apps[0].renew) def test_partition_server_down(self): """Test placement when server in the partition goes down.""" cell = scheduler.Cell('top') srv_x1 = scheduler.Server('s_x1', [10, 10], valid_until=500, label='x') srv_x2 = scheduler.Server('s_x2', [10, 10], valid_until=500, label='x') srv_y1 = scheduler.Server('s_y1', [10, 10], valid_until=500, label='y') srv_y2 = scheduler.Server('s_y2', [10, 10], valid_until=500, label='y') cell.add_node(srv_x1) cell.add_node(srv_x2) cell.add_node(srv_y1) cell.add_node(srv_y2) app_x1 = scheduler.Application('a_x1', 1, [1, 1], 'app') app_x2 = scheduler.Application('a_x2', 1, [1, 1], 'app') app_y1 = scheduler.Application('a_y1', 1, [1, 1], 'app') app_y2 = scheduler.Application('a_y2', 1, [1, 1], 'app') cell.partitions['x'].allocation.add(app_x1) cell.partitions['x'].allocation.add(app_x2) cell.partitions['y'].allocation.add(app_y1) cell.partitions['y'].allocation.add(app_y2) placement = cell.schedule() self.assertEqual(len(placement), 4) # Default strategy will distribute two apps on each of the servers # in the partition. # # For future test it is important that each server has an app, so # we assert on that. self.assertEqual(len(srv_x1.apps), 1) self.assertEqual(len(srv_x2.apps), 1) self.assertEqual(len(srv_y1.apps), 1) self.assertEqual(len(srv_y2.apps), 1) # Verify that all apps are placed in the returned placement. for (_app, before, _exp_before, after, _exp_after) in placement: self.assertIsNone(before) self.assertIsNotNone(after) # Bring server down in each partition. srv_x1.state = scheduler.State.down srv_y1.state = scheduler.State.down placement = cell.schedule() self.assertEqual(len(placement), 4) # Check that in the updated placement before and after are not None. for (_app, before, _exp_before, after, _exp_after) in placement: self.assertIsNotNone(before) self.assertIsNotNone(after) def test_placement_shortcut(self): """Test no placement tracker.""" cell = scheduler.Cell('top') srv_1 = scheduler.Server('s1', [10, 10], valid_until=500, label='x') srv_2 = scheduler.Server('s2', [10, 10], valid_until=500, label='x') cell.add_node(srv_1) cell.add_node(srv_2) app_large_dim1 = scheduler.Application('large-1', 100, [7, 1], 'app') app_large_dim2 = scheduler.Application('large-2', 100, [1, 7], 'app') cell.partitions['x'].allocation.add(app_large_dim1) cell.partitions['x'].allocation.add(app_large_dim2) cell.schedule() self.assertIsNotNone(app_large_dim1.server) self.assertIsNotNone(app_large_dim2.server) # Add lower priority apps - can't be scheduled. # # As free size of top level node is 9x9, placement attempt will be # made. medium_apps = [] for appid in range(1, 10): app_med = scheduler.Application( 'medium-%s' % appid, 90, [4, 4], 'app') cell.partitions['x'].allocation.add(app_med) medium_apps.append(app_med) cell.schedule() for app in medium_apps: self.assertIsNone(app.server) class IdentityGroupTest(unittest.TestCase): """scheduler IdentityGroup test.""" def test_basic(self): """Test basic acquire/release ops.""" ident_group = scheduler.IdentityGroup(3) self.assertEqual(0, ident_group.acquire()) self.assertEqual(1, ident_group.acquire()) self.assertEqual(2, ident_group.acquire()) self.assertEqual(None, ident_group.acquire()) ident_group.release(1) self.assertEqual(1, ident_group.acquire()) def test_adjust(self): """Test identity group count adjustement.""" ident_group = scheduler.IdentityGroup(5) ident_group.available = set([1, 3]) ident_group.adjust(7) self.assertEqual(set([1, 3, 5, 6]), ident_group.available) ident_group.adjust(3) self.assertEqual(set([1]), ident_group.available) def test_adjust_relese(self): """Test releasing identity when identity exceeds the count.""" ident_group = scheduler.IdentityGroup(1) self.assertEqual(0, ident_group.acquire()) self.assertEqual(len(ident_group.available), 0) ident_group.adjust(0) ident_group.release(0) self.assertEqual(len(ident_group.available), 0) def _time(string): """Convert a formatted datetime to a timestamp.""" return time.mktime(time.strptime(string, '%Y-%m-%d %H:%M:%S')) class RebootSchedulerTest(unittest.TestCase): """reboot scheduler test.""" def test_bucket(self): """Test RebootBucket.""" bucket = scheduler.RebootBucket(_time('2000-01-03 00:00:00')) # cost of inserting into empty bucket is zero server1 = scheduler.Server('s1', [10, 10], up_since=_time('2000-01-01 00:00:00')) self.assertEqual(0, bucket.cost(server1)) # insert server into a bucket bucket.add(server1) self.assertEqual(bucket.servers, set([server1])) self.assertTrue(server1.valid_until > 0) # inserting server into a bucket is idempotent valid_until = server1.valid_until bucket.add(server1) self.assertEqual(bucket.servers, set([server1])) self.assertEqual(server1.valid_until, valid_until) # cost of inserting into non-empty bucket is size of bucket server2 = scheduler.Server('s2', [10, 10], up_since=_time('2000-01-01 00:00:00')) self.assertEqual(1, bucket.cost(server2)) # when server would be too old, cost is prohibitive server3 = scheduler.Server('s3', [10, 10], up_since=_time('1999-01-01 00:00:00')) self.assertEqual(float('inf'), bucket.cost(server3)) # when server is too close to reboot date, cost is prohibitive server4 = scheduler.Server('s1', [10, 10], up_since=_time('2000-01-02 10:00:00')) self.assertEqual(float('inf'), bucket.cost(server4)) # remove server from a bucket bucket.remove(server1) self.assertEqual(bucket.servers, set([])) # removing server from a bucket is idempotent bucket.remove(server1) def test_reboots(self): """Test RebootScheduler.""" partition = scheduler.Partition(now=_time('2000-01-01 00:00:00')) server1 = scheduler.Server('s1', [10, 10], up_since=_time('2000-01-01 00:00:00')) server2 = scheduler.Server('s2', [10, 10], up_since=_time('2000-01-01 00:00:00')) server3 = scheduler.Server('s3', [10, 10], up_since=_time('2000-01-01 00:00:00')) server4 = scheduler.Server('s4', [10, 10], up_since=_time('1999-12-24 00:00:00')) # adding to existing bucket # pylint: disable=W0212 timestamp = partition._reboot_buckets[0].timestamp partition.add(server1, timestamp) self.assertEqual(timestamp, server1.valid_until) # adding to non-existsing bucket, results in finding a more # appropriate bucket partition.add(server2, timestamp + 600) self.assertNotEqual(timestamp + 600, server2.valid_until) # will get into different bucket than server2, so bucket sizes # stay low partition.add(server3) self.assertNotEqual(server2.valid_until, server3.valid_until) # server max_lifetime is respected partition.add(server4) self.assertTrue( server4.valid_until < server4.up_since + scheduler.DEFAULT_SERVER_UPTIME ) def test_reboot_dates(self): """Test reboot dates generator.""" # Note: 2018/01/01 is a Monday start_date = datetime.date(2018, 1, 1) schedule = utils.reboot_schedule('sat,sun') dates_gen = scheduler.reboot_dates(schedule, start_date) self.assertEqual( list(itertools.islice(dates_gen, 2)), [ _time('2018-01-06 23:59:59'), _time('2018-01-07 23:59:59'), ] ) schedule = utils.reboot_schedule('sat,sun/10:30:00') dates_gen = scheduler.reboot_dates(schedule, start_date) self.assertEqual( list(itertools.islice(dates_gen, 2)), [ _time('2018-01-06 23:59:59'), _time('2018-01-07 10:30:00'), ] ) class ShapeTest(unittest.TestCase): """App shape test cases.""" def test_affinity_constraints(self): """Test affinity constraints.""" aff = scheduler.Affinity('foo', {}) self.assertEqual(('foo',), aff.constraints) aff = scheduler.Affinity('foo', {'server': 1}) self.assertEqual(('foo', 1,), aff.constraints) def test_app_shape(self): """Test application shape.""" app = scheduler.Application('foo', 11, [1, 1, 1], 'bar') self.assertEqual(('bar', 0,), app.shape()[0]) app.lease = 5 self.assertEqual(('bar', 5,), app.shape()[0]) app = scheduler.Application('foo', 11, [1, 1, 1], 'bar', affinity_limits={'server': 1, 'rack': 2}) # Values of the dict return ordered by key, (rack, server). self.assertEqual(('bar', 1, 2, 0,), app.shape()[0]) app.lease = 5 self.assertEqual(('bar', 1, 2, 5,), app.shape()[0]) def test_placement_tracker(self): """Tests placement tracker.""" app = scheduler.Application('foo', 11, [2, 2, 2], 'bar') placement_tracker = scheduler.PlacementFeasibilityTracker() placement_tracker.adjust(app) # Same app. self.assertFalse(placement_tracker.feasible(app)) # Larger app, same shape. app = scheduler.Application('foo', 11, [3, 3, 3], 'bar') self.assertFalse(placement_tracker.feasible(app)) # Smaller app, same shape. app = scheduler.Application('foo', 11, [1, 1, 1], 'bar') self.assertTrue(placement_tracker.feasible(app)) # Different affinity. app = scheduler.Application('foo', 11, [5, 5, 5], 'bar1') self.assertTrue(placement_tracker.feasible(app)) if __name__ == '__main__': unittest.main()
558
0
184
efa430cb70cf52f5c59fbc4ba2d6a6aab983b47e
129
py
Python
main.py
shilu10/Dummy_Deployment
9ed3309ac3b48940fb19df3deae732376c52cf42
[ "MIT" ]
null
null
null
main.py
shilu10/Dummy_Deployment
9ed3309ac3b48940fb19df3deae732376c52cf42
[ "MIT" ]
null
null
null
main.py
shilu10/Dummy_Deployment
9ed3309ac3b48940fb19df3deae732376c52cf42
[ "MIT" ]
null
null
null
from flask import Flask app = Flask(__name__) @app.route("/")
21.5
53
0.666667
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "<h1 style='color:blue'>Hello There!</h1>"
45
0
22
c66bb2c99e1c48f2b7c2cc56061fca2ede4c8347
1,198
py
Python
College/HVCC/Python Programming/Final Project/runOstranderCustomer.py
lwoluke/Projects
88f288b32db594a96af98b8b3420f7e5f9a5a47d
[ "MIT" ]
null
null
null
College/HVCC/Python Programming/Final Project/runOstranderCustomer.py
lwoluke/Projects
88f288b32db594a96af98b8b3420f7e5f9a5a47d
[ "MIT" ]
null
null
null
College/HVCC/Python Programming/Final Project/runOstranderCustomer.py
lwoluke/Projects
88f288b32db594a96af98b8b3420f7e5f9a5a47d
[ "MIT" ]
null
null
null
""" File: runOstranderCustomer.py Final Project - Main file Reads the files of a company, which contain its customers and their orders, and prints the contents in a comprehendible format. """ from ostranderCustomer import OstranderCustomer # customers is {304: ostranderCustomer.OstranderCustomer object at 0x00...} if __name__ == "__main__": main()
23.490196
90
0.630217
""" File: runOstranderCustomer.py Final Project - Main file Reads the files of a company, which contain its customers and their orders, and prints the contents in a comprehendible format. """ from ostranderCustomer import OstranderCustomer def readCustomers(): f = open("customers.txt", 'r') customers = {} for line in f: items = line.split(',') number = int(items[0].strip()) name = items[1].strip() c = OstranderCustomer(number, name) customers[number] = c return customers # customers is {304: ostranderCustomer.OstranderCustomer object at 0x00...} def readOrders(customers): f = open("orders.txt", 'r') for line in f: items = line.split(',') number = int(items[0].strip()) product = items[1].strip() quantity = items[2].strip() amt = items[3].strip() if customers.get(number) is not None: customers.get(number).addOrder((product, quantity, amt)) def main(): customers = readCustomers() readOrders(customers) print("Genco Pura Olive Oil Customer List\n") for c in customers: print(customers[c]) if __name__ == "__main__": main()
767
0
68
9569039ee886648db8def483d0eef0999c6c8786
3,292
py
Python
dregcli/tests/tests_unit/test_repository.py
jssuzanne/dregcli
328e8aacf4e46f538e2b62c8c3cceba002feb367
[ "MIT" ]
null
null
null
dregcli/tests/tests_unit/test_repository.py
jssuzanne/dregcli
328e8aacf4e46f538e2b62c8c3cceba002feb367
[ "MIT" ]
1
2019-04-12T13:46:52.000Z
2019-04-15T15:26:47.000Z
dregcli/tests/tests_unit/test_repository.py
jssuzanne/dregcli
328e8aacf4e46f538e2b62c8c3cceba002feb367
[ "MIT" ]
1
2019-04-12T13:44:53.000Z
2019-04-12T13:44:53.000Z
import os import sys from unittest import mock import pytest sys.path.append( os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir) ) from fixtures import ( fixture_registry_url, fixture_repository, fixture_repositories, fixture_tags, fixture_digest, fixture_tags_url, fixture_tags_json, fixture_image_url, fixture_image_json, ) from dregcli.dregcli import DRegCliException, Client, Repository, Image
31.056604
79
0.615735
import os import sys from unittest import mock import pytest sys.path.append( os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir) ) from fixtures import ( fixture_registry_url, fixture_repository, fixture_repositories, fixture_tags, fixture_digest, fixture_tags_url, fixture_tags_json, fixture_image_url, fixture_image_json, ) from dregcli.dregcli import DRegCliException, Client, Repository, Image class TestRepository: @pytest.mark.usefixtures( 'fixture_registry_url', 'fixture_repository', 'fixture_tags_url', 'fixture_tags_json' ) def test_tags( self, fixture_registry_url, fixture_repository, fixture_tags_url, fixture_tags_json ): expected_url = fixture_registry_url + fixture_tags_url mock_res = mock.MagicMock() mock_res.status_code = 200 mock_res.json = mock.MagicMock(return_value=fixture_tags_json) with mock.patch('requests.get', return_value=mock_res) as mo: repository = Repository( Client(fixture_registry_url), fixture_repository ) tags = repository.tags() assert isinstance(tags, list) and \ tags == fixture_tags_json['tags'] @pytest.mark.usefixtures( 'fixture_registry_url', 'fixture_repository', 'fixture_tags', 'fixture_digest', 'fixture_image_url', 'fixture_image_json' ) def test_image( self, fixture_registry_url, fixture_repository, fixture_tags, fixture_digest, fixture_image_url, fixture_image_json ): expected_url = fixture_registry_url + fixture_image_url mock_res = mock.MagicMock() mock_res.status_code = 200 mock_res.json = mock.MagicMock( return_value=fixture_image_json ) # mock response headers response_headers = {} response_headers[Repository.Meta.manifest_response_header_digest] = \ fixture_digest mock_res.headers.__getitem__.side_effect = response_headers.__getitem__ mock_res.headers.get.side_effect = response_headers.get # mock get mock_res.headers.__iter__.side_effect = response_headers.__iter__ expected_image_name = "{repo}:{tag}".format( repo=fixture_repository, tag=fixture_tags[0] ) with mock.patch('requests.get', return_value=mock_res) as mo: repository = Repository( Client(fixture_registry_url), fixture_repository ) image = repository.image(fixture_tags[0]) mo.assert_called_once_with( expected_url, headers=Repository.Meta.manifests_headers ) assert type(image) == Image and \ image.name == fixture_repository and \ image.tag == fixture_tags[0] and \ image.digest == fixture_digest and \ image.data == fixture_image_json and \ str(image) == "{repo}:{tag}".format( repo=fixture_repository, tag=fixture_tags[0])
2,398
413
23
0b0f55e3259c754e6f41e0aa8589e9c775309a29
477
py
Python
srcode/user/decorator.py
Bnjorogedev/Flaskgram-instaclone
c1efb66e9b6394d661f51cd3621066b1e02ddd17
[ "MIT" ]
1
2020-09-22T21:01:36.000Z
2020-09-22T21:01:36.000Z
srcode/user/decorator.py
Bnjorogedev/Flaskgram
c1efb66e9b6394d661f51cd3621066b1e02ddd17
[ "MIT" ]
1
2020-10-18T07:05:11.000Z
2020-10-18T07:05:11.000Z
srcode/user/decorator.py
Bnjorogedev/Flaskgram-instaclone
c1efb66e9b6394d661f51cd3621066b1e02ddd17
[ "MIT" ]
null
null
null
from flask import flash, redirect, url_for, abort from flask_login import current_user from srcode.models import Permission, User from functools import wraps def check_confirmed(func): '''Checks whether a certain user is confirmed''' @wraps(func) return decorated_function
31.8
59
0.706499
from flask import flash, redirect, url_for, abort from flask_login import current_user from srcode.models import Permission, User from functools import wraps def check_confirmed(func): '''Checks whether a certain user is confirmed''' @wraps(func) def decorated_function(*args, **kwargs): if not current_user.confirmed: return redirect(url_for('auth.unconfirmed')) return func(*args, **kwargs) return decorated_function
160
0
27
0cc1bc76ee8680d1873dbebc5d44e30fed7a3a0c
293
py
Python
src/kol/test/TestLogin.py
danheath/temppykol
7f9621b44df9f9d2d9fc0a5b2a06db116b9ccfab
[ "BSD-3-Clause" ]
19
2015-02-16T08:30:49.000Z
2020-05-01T06:06:33.000Z
src/kol/test/TestLogin.py
danheath/temppykol
7f9621b44df9f9d2d9fc0a5b2a06db116b9ccfab
[ "BSD-3-Clause" ]
5
2015-01-13T23:01:54.000Z
2016-11-30T15:23:43.000Z
src/kol/test/TestLogin.py
danheath/temppykol
7f9621b44df9f9d2d9fc0a5b2a06db116b9ccfab
[ "BSD-3-Clause" ]
19
2015-05-28T09:36:19.000Z
2022-03-15T23:19:29.000Z
import TestData from kol.Session import Session import unittest
24.416667
69
0.665529
import TestData from kol.Session import Session import unittest class Main(unittest.TestCase): def runTest(self): s = Session() s.login(TestData.data["userName"], TestData.data["password"]) self.assert_(s.isConnected == True) TestData.data["session"] = s
170
9
49
b14424ac4aec20fd96ca92e13bc9a33f0e87d8bc
4,974
py
Python
src/spn/io/Text.py
kripa-experiments/SPFlow
32eada604bf5442d8aa10223581b187f7a57d540
[ "Apache-2.0" ]
null
null
null
src/spn/io/Text.py
kripa-experiments/SPFlow
32eada604bf5442d8aa10223581b187f7a57d540
[ "Apache-2.0" ]
null
null
null
src/spn/io/Text.py
kripa-experiments/SPFlow
32eada604bf5442d8aa10223581b187f7a57d540
[ "Apache-2.0" ]
null
null
null
''' Created on March 21, 2018 @author: Alejandro Molina ''' from collections import OrderedDict from enum import Enum from spn.algorithms.Validity import is_valid from spn.structure.Base import Product, Sum, rebuild_scopes_bottom_up, assign_ids, Leaf import numpy as np _node_to_str = {} _str_to_spn = OrderedDict()
30.145455
112
0.624045
''' Created on March 21, 2018 @author: Alejandro Molina ''' from collections import OrderedDict from enum import Enum from spn.algorithms.Validity import is_valid from spn.structure.Base import Product, Sum, rebuild_scopes_bottom_up, assign_ids, Leaf import numpy as np def to_JSON(node): import json from collections import OrderedDict def dumper(obj): if isinstance(obj, np.ndarray): return str(obj) if isinstance(obj, Enum): return obj.name try: return obj.toJSON() except: obj_dict = obj.__dict__ values = OrderedDict([(key, obj_dict[key]) for key in sorted(obj_dict.keys()) if key[0] != "_"]) return {obj.__class__.__name__: values} return json.dumps(node, default=dumper) def spn_to_str_ref_graph(node, feature_names=None, node_to_str=None): if node_to_str is not None: t_node = type(node) if t_node in node_to_str: return node_to_str[t_node](node, feature_names, node_to_str) if isinstance(node, Leaf): return str(node) + " " + spn_to_str_equation(node, feature_names) + "\n" if isinstance(node, Product): dbg = "" if node.debug is not None: dbg = node.debug pd = ", ".join(map(lambda c: c.name, node.children)) chld_str = "".join(map(lambda c: spn_to_str_ref_graph(c, feature_names, node_to_str), node.children)) chld_str = chld_str.replace("\n", "\n\t") return "%s ProductNode(%s){\n\t%s}\n" % (str(node), pd, chld_str) if isinstance(node, Sum): w = node.weights ch = node.children sumw = ", ".join(map(lambda i: "%s*%s" % (w[i], ch[i].name), range(len(ch)))) child_str = "".join(map(lambda c: spn_to_str_ref_graph(c, feature_names, node_to_str), node.children)) child_str = child_str.replace("\n", "\n\t") return "%s SumNode(%s){\n\t%s}\n" % (str(node), sumw, child_str) raise Exception('Node type not registered: ' + str(type(node))) _node_to_str = {} def add_node_to_str(node_type, lambda_func): _node_to_str[node_type] = lambda_func def spn_to_str_equation(node, feature_names=None, node_to_str=_node_to_str): t_node = type(node) if t_node in node_to_str: return node_to_str[t_node](node, feature_names, node_to_str) if isinstance(node, Product): children_strs = map(lambda child: spn_to_str_equation(child, feature_names, node_to_str), node.children) return "(" + " * ".join(children_strs) + ")" if isinstance(node, Sum): def fmt_chld(w, c): return str(w) + "*(" + spn_to_str_equation(c, feature_names, node_to_str) + ")" children_strs = map(lambda i: fmt_chld(node.weights[i], node.children[i]), range(len(node.children))) return "(" + " + ".join(children_strs) + ")" raise Exception('Node type not registered: ' + str(type(node))) _str_to_spn = OrderedDict() def add_str_to_spn(name, lambda_func, grammar, obj_type): _str_to_spn[name] = (lambda_func, grammar, obj_type) def str_to_spn(text, features=None, str_to_spn_lambdas=_str_to_spn): from lark import Lark ext_name = "\n".join(map(lambda s: " | " + s, str_to_spn_lambdas.keys())) ext_grammar = "\n".join([s for _, s, _ in str_to_spn_lambdas.values()]) grammar = r""" %import common.DECIMAL -> DECIMAL %import common.WS %ignore WS %import common.WORD -> WORD %import common.DIGIT -> DIGIT ALPHANUM: "a".."z"|"A".."Z"|DIGIT PARAMCHARS: ALPHANUM|"_" FNAME: ALPHANUM+ PARAMNAME: PARAMCHARS+ NUMBER: DIGIT|DECIMAL NUMBERS: NUMBER+ list: "[" [NUMBERS ("," NUMBERS)*] "]" ?node: prodnode | sumnode """ + ext_name + r""" prodnode: "(" [node ("*" node)*] ")" sumnode: "(" [NUMBERS "*" node ("+" NUMBERS "*" node)*] ")" """ + ext_grammar parser = Lark(grammar, start='node') # print(grammar) tree = parser.parse(text) def tree_to_spn(tree, features): tnode = tree.data if tnode == "sumnode": node = Sum() for i in range(int(len(tree.children) / 2)): j = 2 * i w, c = tree.children[j], tree.children[j + 1] node.weights.append(float(w)) node.children.append(tree_to_spn(c, features)) return node if tnode == "prodnode": if len(tree.children) == 1: return tree_to_spn(tree.children[0], features) node = Product() for c in tree.children: node.children.append(tree_to_spn(c, features)) return node if tnode in str_to_spn_lambdas: return str_to_spn_lambdas[tnode][0](tree, features, str_to_spn_lambdas[tnode][2], tree_to_spn) raise Exception('Node type not registered: ' + tnode) spn = tree_to_spn(tree, features) rebuild_scopes_bottom_up(spn) valid, err = is_valid(spn) assert valid, err assign_ids(spn) return spn
4,508
0
138